Playing short .wav files - Android

17,307

The SoundPool is the correct class for this. The below code is an example of how to use it. It is also the code I use in several apps of mine to manage the sounds. You can have as may sounds as you like (or as memory permits).

public class SoundPoolPlayer {
    private SoundPool mShortPlayer= null;
    private HashMap mSounds = new HashMap();

    public SoundPoolPlayer(Context pContext)
    {
        // setup Soundpool
        this.mShortPlayer = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);


        mSounds.put(R.raw.<sound_1_name>, this.mShortPlayer.load(pContext, R.raw.<sound_1_name>, 1));
        mSounds.put(R.raw.<sound_2_name>, this.mShortPlayer.load(pContext, R.raw.<sound_2_name>, 1));
    }

    public void playShortResource(int piResource) {
        int iSoundId = (Integer) mSounds.get(piResource);
        this.mShortPlayer.play(iSoundId, 0.99f, 0.99f, 0, 0, 1);
    }

    // Cleanup
    public void release() {
        // Cleanup
        this.mShortPlayer.release();
        this.mShortPlayer = null;
    }
}

You would use this by calling:

SoundPoolPlayer sound = new SoundPoolPlayer(this); 

in your Activity's onCreate() (or anytime after it). After that, to play a sound simple call:

sound.playShortResource(R.raw.<sound_name>);

Finally, once you're done with the sounds, call:

sound.release();

to free up resources.

Share:
17,307
CookieMonssster
Author by

CookieMonssster

Updated on June 07, 2022

Comments

  • CookieMonssster
    CookieMonssster about 2 years

    I would like to play sound after touching the button. MediaPlayer works fine, but I read somewhere that this library is for long .wav (like music).

    Is there any better way to play short .wav(2-3 sec.)?

  • CookieMonssster
    CookieMonssster over 11 years
    It works very well, but I have two questions. 1. I have to relase after every use (like MediaPlayer) or maybe when I'm quitung from app//activity? 2.There is any way to stop sample?
  • Raghav Sood
    Raghav Sood over 11 years
    You should only release it when you're done playing any sound for the entire app session (so onDestroy() would be a good choice). You can add a pause() method that uses the SoundPools's pause() method.
  • Mark Cramer
    Mark Cramer over 8 years
    This was super easy. FWIW, Eclipse suggested SparseIntArray() for mSounds for better performance, so that's what I did.
  • Yaroslav
    Yaroslav about 7 years
    In the future where I'm from, SoundPool is deprecated. Check this for more answers: stackoverflow.com/questions/2458833/…
  • Vladimir Marton
    Vladimir Marton almost 7 years
    Soundpool is not deprecated, you just need to use Builder to construct objects, instead of creating the new instance yourself.