In this mini-project we will play a sound on an Android device. We will see how we use the SoundPool class to load a sound from a file and then play it. This is another significant step on the journey to build a complete game.

  • The courses above are up to 95% off - by clicking on ad above.

Create a new project

Create a new Android Studio project, call it Sound FX Demo with a Empty Activity called SoundFXDemoActivity. Delete all the code in SoundFXDemoActivity.java and enter the code below. I have listed all the import... code. Remember you can either type this in now or wait until we use the appropriate class and press the Alt|Enter keyboard combination to enter the import... line automatically.

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
import java.io.IOException;

public class SoundFXDemoActivity extends Activity {

    // This is the entry point to our game
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Our sound FX code will go here

    }
}

As you can see in the code above we have a typical project, much like our first ever blank project. Notice that we don’t call setContentView... to set the view to the screen. This is because this app won’t display anything, it will just play a sound.

Adding a sound file to the project

We need a sound FX file that we want to play. You can obtain them from free download sites like freesound.org or you can get a really cool free sound generating software package called BFXR.  Alternatively, you can download my warp file which I generated using BFX. Right-click this link and select Save as…


Here is what you will hear when the project is finished.

When you have your preferred sound effect make sure it is either .wav or .ogg format and name it warp.wav/warp.ogg. Using your operating system’s file browser go to the app\src\main folder of the project and add a folder called assets. Add your sound file to this folder. Now we are ready to write the sound FX code.

The sound code

We will split up the sound code into chunks and explain it as we go. Here are the first three lines of our sound code. First, we declare a  int variable called soundID. This int will hold a reference number that Android will use to identify the sound effect we want to play. For now, we initialize it to -1. Nex,t we create a new SoundPool object. And on the third new line of code we initialize it. The parameters used to initialize it are as follows.

1 is the number of simultaneous sound FX we might want to play.
AudioManager.STREAM_MUSIC is the type of FX we specify for our specific sound.
is the quality.

Enter the sound fX code below the comment that indicates where it should go.

SoundPool soundPool;

int soundID = -1;

// This SoundPool is deprecated but don't worry
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC,0);

If you are wondering why there is an unusual looking strikethrough on the word SoundPool in the line where we initialize the object; it is because the class is deprecated. What this means is that there is a newer, slightly more correct way to initialize the SoundPool object. We do it this way because the newer code only works on the very latest devices and yet this older code works on every Android device ever made. It is true that one day this code will stop working but that is not likely to happen for some years.

Next, we load the sound file into a format which is ready to play. We do this in a few steps. First, we create two objects an AssetManager and an AssetFileDescriptor. These two objects do all the complex work that is required behind the scenes.

Next, we see something new. We have a try/ catch block. The design of the AssetManager class means we must wrap our code in a try/ catch block. The code in the try part is what we want to do, the code in the catch part is what to do if it fails. We can think of this as a kind of mandatory if/ else block. In the try part, we initialize descriptor using the openFd method and passing in the name of our sound file. Then we use the load method to load the contents of descriptor (our sound FX) into memory.

try{
	// Create objects of the 2 required classes
    AssetManager assetManager = this.getAssets();
    AssetFileDescriptor descriptor;

    // Load our fx in memory ready for use
    descriptor = assetManager.openFd("warp.ogg");
    soundID = soundPool.load(descriptor, 0);

}catch(IOException e){
		// Print an error message to the console
        Log.e("error", "failed to load sound files");
}

Finally, we can play a sound using the play method like this. The parameters are as follows from left to right: Our soundID ID, left volume, right volume, priority (in case we are playing more sounds than we said when we initialized soundPool to play), the number of loops to play, the rate or frequency. Enter the last line of code.

soundPool.play(soundID, 1, 1, 0, 0, 1);

You can now run the app to hear the sound being played.

As we saw the vast majority of the code we wrote was setting up the sound ready to be played. In a real game, we would load all the sound FX that we need, each with a different id like, explodeID, shootID etc at the start of the game. Then whenever an appropriate event takes place in the game we will simply use the play method with the appropriate id.

Complete SoundFXDemoActivity code listing

package com.gamecodeschool.soundfxdemo;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
import java.io.IOException;

public class SoundFXDemoActivity extends Activity {

    // This is the entry point to our game
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SoundPool soundPool;

        int soundID = -1;

        // This SoundPool is deprecated but don't worry
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC,0);

        try{
            // Create objects of the 2 required classes
            AssetManager assetManager = this.getAssets();
            AssetFileDescriptor descriptor;

            // Load our fx in memory ready for use
            descriptor = assetManager.openFd("warp.ogg");
            soundID = soundPool.load(descriptor, 0);

        }catch(IOException e){
            // Print an error message to the console
            Log.e("error", "failed to load sound files");
        }

        soundPool.play(soundID, 1, 1, 0, 0, 1);

    }
}

  • The courses above are up to 95% off - by clicking on ad above.


Please visit the Android category of our game coding bookstore for beginners