Monday, June 6, 2011


I was trying to implement the SoundPool class to play some .ogg files in my application, and I noticed there was a lack of documentation regarding this class, so once I got it to work I thought I would post some information in case anyone else was struggling with the same class. 

Just create the variables you need to use and reference the buttons you'll use to start and stop the audio : 

public class SimpleApp extends Activity {
    SoundPool mSoundPool;
    HashMap<Integer, Integer> mSoundPoolMap;
    AudioManager  mAudioManager;
    float streamVolume;
    int streamID;

    public void onCreate(Bundle savedInstanceState) {
        final Button startButton = (Button)findViewById(;
        final Button stopButton = (Button)findViewById(;


Then setup the sounds. Don't forget to add your .ogg file to a raw resource folder:

public void setupSounds() {
        mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        mSoundPoolMap = new HashMap<Integer, Integer>();
        mAudioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
        mSoundPoolMap.put(1, mSoundPool.load(this, R.raw.SoundName, 1));
        streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        streamVolume = streamVolume /  mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

Setup some methods for starting and stopping the audio.

    public void playSoundLoop(){
        streamID =, streamVolume, streamVolume, 1, -1, 1f);

Note here that this line will continuously loop the audio until the stop button is pressed. If you replace the -1 with a 1, it will play the audio once. If you replace it with any other integer, it will loop the audio that many times. The play method of the soundPool object will return the streamID. Use this integer to stop that particular stream within the stop method we create:

    public void stopSound(){

Then setup click listeners for the the buttons within the onCreate method.

        startButton.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {