Free Android app covering all aspects of addiction, including prevention and treatment

Using Android's SoundPool class: A tutorial

  • Written by  Clive

Playing sound clips in your apps

Android soundpool icon

The SoundPool class lets you load a number of sound clips into a device’s memory. You can then play these sound clips on demand. You can even play a number of sound clips at the same time.

The clips are decompressed and decoded when they’re loaded so there’s no delay when you play them.

Our tutorial shows you how you can use the SoundPool class to play sound clips in your apps

.

So here’s our tutorial

We set up a sound pool and load up 5 audio clips.

One clip starts playing when the activity starts. It’s looped to play forever. We control another looped clip by pressing the Start Play and Stop Play buttons.

We can play the remaining short sound clips by pressing their buttons.

A toggle button pauses and resumes play of all the active sound clips.

Android soundpool tutorial screenshot

Our tutorial app’s screen: The toggle button pauses and resumes all active streams. The start/stop buttons control the play of a single looped stream while the remaining buttons each start playing a short sound clip

Some stuff you should know about Sound Pools

Your files

Your sound files are loaded into memory. Memory is scarce so keep your clips short and the file sizes as small as possible.

Compress your files

Most of the popular audio formats are supported. Go for the one that has the best quality for the smallest size.

You can put your files in:

  • The assets folder
  • The res/raw folder
  • In a folder within Android’s File System

The Maximum number of streams and your Play Priority determines play

Your files are decompressed and decoded into raw 16-bit PCM streams when they’re loaded into your sound pool. The SoundPool class then takes care of optimizing their resource management.

You can play one stream at a time, all at the same time or anywhere in-between.

When you create your sound pool, you specify the maximum number of streams that you would like to play at the same time. You also specify the priority of each stream when you call play().

If you are already playing the maximum number of sound clips and call play() to start another, then the stream with the lowest priority will be stopped.

If there are a number of streams with the same priority then the oldest one will be stopped.

Controlling play

You can control play with the following methods:

  • play(), pause(), resume(), stop() – used for single streams
  • autoPause() and autoResume() – pauses and resumes all active streams
Looping

You can play sound clips once-off or loop them any number of times, till forever!

Playback rate

You can alter the playback rate (frequency), or speed of playback from 0.5 to 2.

Priority

You can set the priority of a stream from low to high.

A stream’s priority is used to keep the number of streams within the maximum number of streams that can be played at the same time.

The Stream Allocator will stop the lowest priority stream to allow a new stream to play without exceeding the maximum. If there are multiple streams with the same priority, then the oldest one will be stopped.

If the new stream priority is lower than the active streams then it will not play.

Streams can be stopped due to resource constraints.

Each sound clip is given a stream ID when you call play() to start it playing. This ID is unique and refers to this instance of the stream.

You should release all resources used by the SoundPool object and set it to null when you’ve finished using it.

You can make changes to the sound stream while it’s playing

While the stream is playing, you can:

  • setLoop() – set how many times the stream should loop
  • setRate() – change the speed of playback
  • setVolume() – set the stream’s volume
  • setPriority() – change the priority of the stream

Our Tutorial app

Getting creative: Create your sound pool

We construct our SoundPool object:

Android soundpool tutorial create SoundPool

We construct our SoundPool object, setting the maximum number of streams, the stream type and the source quality

Note the following:

  • mySoundPool – our SoundPool object
  • MAX_NUMBER_STREAMS – our constant for the maximum number of streams that we would like to be able to play at the same time
  • STREAM_MUSIC – this is the audio stream type. STREAM_MUSIC is the most widely used type
  • SOURCE_QUALITY – the sample-rate used to convert the file. It’s not used currently so set it to the default of 0
  • setOnLoadCompleteListener – our interface that monitors the loading of our sound files into the sound pool

Getting wet: Loading your sound clips into the pool

Use the load() method to load your sound files into the sound pool. Our files are in the res/raw folder so we use the following load() method:

Android soundpool tutorial create SoundPool load Clips

Loading the sound file into the sound pool returns a sound ID which you can use to play or unload the sound

Note the following:

  • correctSoundId – a unique ID for this sound. You can use it to play and unload the sound
  • load – we load the sound clip into the sound pool. There are three parameters:
    • the context
    • the resource id
    • the priority of the sound. Currently this has not effect. Set it to 1 for future compatibility

All done and dusted: Once the loading is complete

We use the SoundPool.OnLoadCompleteListener interface to monitor the loading of the sound clips into the sound pool. Its onLoadComplete() method is executed when the sound clip has finished loading:

Android soundpool tutorial create SoundPool load Clips onLoadCompleted

onLoadComplete() executes when the sound file has finished loading

Note the following:

  • the onLoadComplete() method receives three parameters:
    • the sound pool instance used when loading the sound clip
    • the sample ID of the loaded sound clip. This is the ID that is returned by the load() method
    • the status of the load operation. 0 indicates success
  • we use a switch statement to set an appropriate boolean to true, indicating the successful loading of that sound file

Make a noise: Playing your sound

Use the play() method to play a sound clip from the sound pool:

Android soundpool tutorial create SoundPool play sound

We call play() to start playing our sound clip

Note the following:

  • correctSoundId – this is the sound clip’s ID as returned by the load() method
  • leftVolume – the left volume which can range from 0.0 to 1.0
  • rightVolume – the right volume which can range from 0.0 to 1.0
  • priority – the priority for this sound clip. 0 is the lowest priority, the higher the number, the higher the priority
  • LOOP_FOREVER – our constant of -1 specifying that the sound clip should loop forever
  • frequency – the playback rate or speed of playback. Ranges from 0.5 to 2.0 with 1.0 being the normal playback rate

The play() method returns a unique stream ID for each sound clip. It’s used in the following SoundPool methods:

  • pause() – pause a playing sound clip
  • resume() – resumes playback of the paused sound clip
  • setLoop() – set how many times the sound clip should loop
  • setRate() – change the speed of playback
  • setVolume() – set the sound clip’s volume
  • setPriority() – change the priority of the sound clip
  • stop() – stops playing the currently playing sound clip

Take a break: Pausing and resuming play

You can pause and resume playing individual active sound clips:

  • pause() – pauses the sound clip identified by the parameter, streamId, which was returned by the play() method
  • resume() – resumes playing the sound clip identified by the parameter, streamId, which was returned by the play() method

You can also pause and resume all the currently playing sounds, as we’ve done below:

Android soundpool tutorial create SoundPool play autoPause() autoResume()

We use a toggle button to pause and resume all active streams

Note the following:

  • We use the toggle button to pause and resume all sound clips that are playing
  • autoResume – resumes playing all sound clips that were paused with autoPause()
  • autoPause – pauses all currently playing sound clips. It also sets a flag indicating that the paused stream can be resumed with autoResume()

End of story: Stopping play

Use the stop() method to stop playing a sound clip. It also releases any resources used by the sound clip:

Android soundpool tutorial create SoundPool streamId

The play() method returns a stream ID (e.g. crashBurnStreamId) for the sound clip. You use this stream ID to identify the sound clip that you want to stop

Android soundpool tutorial stop()

Use the stop() method to stop playing a stream. You’ll need to pass it the stream ID of the stream that you want to stop playing

Note the following:

  • crashBurnStreamId – the stream ID returned when we started playing this sound clip by calling  play()
  • stop – stops the sound clip identified by the stream ID. It also releases any resources used by this sound clip
  • crashBurnStreamId – we set the stream ID to 0. We use it determine whether or not the crash burn stream is playing when the Start Play button is pressed

Share the love: Release all the resources used by the SoundPool object

You should release all memory and other resources used by the SoundPool object when you no longer need it.

We do this in the activity’s onPause() method:

Android soundpool tutorial onPause() release()

Release all resources when you no longer need the SoundPool object

Note the following:

  • onPause – is always called when the activity is about to go into the background. You may want to read, The Activity Lifecycle for more on this.
  • release – releases all the resources used by the SoundPool object
  • null – this SoundPool object can no longer be used so set it to null to help the Garbage Collector identify it as reclaimable
You may find these links useful

You can get free sound effects at www.freesfx.co.uk.

Audacity, which you can get from http://audacity.sourceforge.net/, is a great free sound editing and recording package.

Also, you want to check out, Recording and playing back audio files and Perfect sound using the Equalizer effect: a tutorial.

I hope that you have found this tutorial helpful.

This project was created using Android Studio.

You can download the project files here Download icon

Are you using Eclipse or another IDE? Here's how you can use this project's Android Studio files.