Monday, June 6, 2011

SoundPool

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;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        final Button startButton = (Button)findViewById(R.id.startButton);
        final Button stopButton = (Button)findViewById(R.id.stopButton);

setupSounds();
}

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 = mSoundPool.play(mSoundPoolMap.get(1), 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(){
        mSoundPool.stop(streamID);
    }

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

        startButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                playSound();
            }
    });
}

No comments:

Post a Comment