• $10 Game Dev' Courses - Use code "BREAKTHRU"

    Video courses

Unity Pro Development A to Z – Build 10 Android/iOS Games

The Complete Android & Java Developer Course – Build 21 Apps

The Complete Java Developer Course. Learn Step by Step

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.

  • Learning java by building Android games

    Learning Java by Building Android Games

    Want to learn Java for Android? Even if you are completely new to either Java, Android, or game programming but are aiming to publish Android games, then this book is for you. This book also acts as a refresher for those who already have experience in Java on other platforms or other object-oriented languages.
    • Setup your own Android game programming environment using Android Studio
    • Control logic, branch your code, and add real decision-making depth to your games
    • Design and use 2d sprite animations, smooth pixel graphics, sound FX, simple collision detection and artificial intelligence (AI)
    • Build around a dozen sample test apps and 4 complete working games!
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US only)
    small_book

    Android Game Programming by Example

    Learn to build exciting Android game projects. Build a simple flappy-bird like game to a multi-environment, tough, retro platformer then an OpenGL ES 2 Asteroids clone, running at hundreds of frames per second .
    • Animate your characters with sprite sheets, add multiple scrolling parallax backgrounds, and implement genuinely tough, playable levels in your games
    • Every single line of code is printed in the book! No need to refer to the code files while trying to follow along. All the code files are also supplied separately so you can refer to them in their completed form and copy/paste them into your project if you like.
    • Implement a multitude of other game features such as pickups, firing weapons, HUD’s, generating and playing sound FX, scenery, level transition, high scores, and more
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US Only)

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);

    }
}

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