askanaan
askanaan

Reputation: 197

Android - Playing multiple sounds sequencially

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

Upvotes: 2

Views: 5412

Answers (2)

jfortunato
jfortunato

Reputation: 12067

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);
    }
}

Upvotes: 2

cyborg86pl
cyborg86pl

Reputation: 2617

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

Upvotes: 1

Related Questions