2

I need to run many small sounds while the activity is running. Some files plays every fixed time interval (Ex. 5 seconds) Some files will be played in a sequence when one finishes the next starts (ex. sound1, sound2, sound3) when the screen is touched.

Total sounds are around 35 short mp3 files (max 3 seconds).

What is the best way to implement this?

Thanks

2 Answers 2

2

SoundPool is commonly used to play multiple short sounds. You could load up all your sounds in onCreate(), storing their positions in a HashMap.

Creating SoundPool

public static final int SOUND_1 = 1;
public static final int SOUND_2 = 2;

SoundPool mSoundPool;
HashMap<Integer, Integer> mSoundMap;

@Override
public void onCreate(Bundle savedInstanceState){
  mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 100);
  mSoundMap = new HashMap<Integer, Integer>();

  if(mSoundPool != null){
    mSoundMap.put(SOUND_1, mSoundPool.load(this, R.raw.sound1, 1));
    mSoundMap.put(SOUND_2, mSoundPool.load(this, R.raw.sound2, 1));
  }
}

Then when you need to play the sound, simple call playSound() with the constant value of your sound.

/*
*Call this function from code with the sound you want e.g. playSound(SOUND_1);
*/
public void playSound(int sound) {
    AudioManager mgr = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
    float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
    float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    float volume = streamVolumeCurrent / streamVolumeMax;  

    if(mSoundPool != null){
        mSoundPool.play(mSoundMap.get(sound), volume, volume, 1, 0, 1.0f);
    }
}
1

MediaPlayer has PlaybackCompleted state, so when one audio finishes, you can start playing another

public void setOnCompletionListener (MediaPlayer.OnCompletionListener listener)

source

And i would try Thread or AsyncTask to play different audio lines separately

1
  • Thanks, I believe there should be a better more efficient way to do it. this is because I will have to "Prepare" the medial player with each file. That's why I mentioned the number of files on hand.
    – askanaan
    Jul 7, 2012 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.