SoundPool – Play Bundled Sound Asynchronously in Android

0
Shares
SoundPool – Play Bundled Sound Asynchronously in Android
4.8 (96.67%) 6 votes

Playing bundled sounds in Android is not difficult when you have multiple sound files and you play it individually.

You can use media player to get the job done, but what if you want to play them simultaneously?

Consider you are working on a Game app, where you need to have a background sound, which keeps on running in a loop and many individual sounds run over the background sound.

Now, what will you do?

1

 

Confused?

You don’t need to worry when SoundPool is there. But, if you want to support devices version with Lollipop and above, you need to use SoundPool.Builder.

SoundPool is memory efficient which improves the app performance. It is easy and fast to load all resource sound at the time of initialization of an application.

Today, in this Android application development tutorial, we are going to practice it, so you can understand it easily.

Open the Activity file, where you want to load the sounds, and import the classes mentioned below.

import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;

Now, declare the object in your activity class.

private SoundPool mSoundPool;
private final int MAX_STREAM = 10;
private boolean soundLoaded = false;

In your onCreate() method, add below code to initialize mSoundPool object, and setOnLoadCompleteListner to make sure that the sounds are loaded and ready to play.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        AudioAttributes attributes = new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_GAME)
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .build();

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        mSoundPool = new SoundPool.Builder()
            .setAudioAttributes(attributes)
            .setMaxStreams(MAX_STREAM);
            .build();
} else {
        @SuppressWarnings("deprecation")
        mSoundPool = new SoundPool(MAX_STREAM, AudioManager.STREAM_MUSIC, 0);
}

It’s the time to use the initialized SoundPool object. For that, first of all, you have to load all the sound file that you want to play by using following code. In this example, I am loading 2 sound files. We can load maximum 10 sound files, as it was declared while creating the MAX_STREAM. You can adjust the MAX_STREAM value as per your needs.

int backgroundSoundId = mSoundPool.load(this, R.raw.music_play_1, priority);
int coinSoundId = mSoundPool.load(this, R.raw.music_play_2, priority);

Set On Load Complete Listener to invoke the action required when the sound is loaded by the app.

mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int soundId, int status) {
                /**
                 * soundPool - SoundPool object from the load() method
                 * soundId - the sample ID of the sound loaded.
                 * status - the status of the load operation (0 = success)
                 **/

                if(status == 0) {
                        if(soundId == backgroundSoundId)
                                playBackgroundSound();
                        else
                                soundLoaded = true;
                }
        }
});

Now, it’s the time to play the loaded sound.

/**
 *
 * soundID - a soundID returned by the load() function
 * leftVolume - left volume value (range = 0.0 to 1.0)
 * rightVolume - right volume value (range = 0.0 to 1.0)
 * priority - stream priority (0 = lowest priority)
 * loop - loop mode (0 = no loop, -1 = loop forever)
 * rate - playback rate (1.0 = normal playback, range 0.5 to 2.0)
 *
 **/

// Change the parameter value as per your requirement.
// mSoundPool.play(soundId, leftVolume, rightVolume, priority, loop, rate);

private void playBackgroundSound() {
        mSoundPool.play(backgroundSoundId, 0.5, 0.5, 1, -1, 1.0);
}

Put the below line where you want to play the coin sound. In this example, I am playing this sound on tap of a button.

mSoundPool.play(coinSoundId, 0.5, 0.5, 1, -1, 1.0);

You can refer SoundPool document to check stop, pause etc. methods which you might need for your app.

2

Yes, it is as simple as 1,2,3…

Hope you enjoyed reading this blog.

It is fun to make the complex thing simple, isn’t it?

This post was written by Jigar Mistry, who is a Technical Head at Space-O Technologies. If you’ve any app development idea and want to make an Android app, send us your requirement by filling the following form. We will get back to you within 12 working hours.

This page was last edited on October 24th, 2017, at 7:42.
 
0
Shares
 

Have an App Idea?

Get your free consultation now