Using SoundPool in Android

If your app/game need to play a sound when user click certain object, you will quickly found out that using MediaPlayer is a bad idea. This is what SoundPool is for, however, its API is still a bit unfriendly. This is some notes on how to use it and my suggested usage pattern.

Obtaining a SoundPool object

It is recommended to use the Builder, but lower SDK device does not support that, so this is what you do.

Load the sound clip

You can import your sound clip to the res/raw folder in your project, then you can use the load() method on the soundPool object.

Remember to store the int value returned for later use, for example

Play the sound

Pass the int we previously ontained to the play() method and there you go!

Recommended pattern

If you only need to play sound in a single Activity, then you can just maintain a SoundPool object in your Activity, but if you need to use it across multiple Activity, fragments, you can create a SoundManager class like the following.

Usage of SoundManager

Anywhere in your app when you need to play the sound

 

One Reply to “Using SoundPool in Android”

Share your thoughts