Game Development Reference
In-Depth Information
Getting the AssetFileDescriptor is straightforward via the AssetManager.openFd() method.
Loading the sound effect via the SoundPool is just as easy. The first argument of the SoundPool.
load() method is our AssetFileDescriptor , and the second argument specifies the priority of
the sound effect. This is currently not used, and should be set to 1 for future compatibility.
The SoundPool.load() method returns an integer, which serves as a handle to the loaded sound
effect. When we want to play the sound effect, we specify this handle so that the SoundPool
knows what effect to play.
Playing the sound effect is again very easy:
soundPool.play(explosionId, 1.0f, 1.0f, 0, 0, 1);
The first argument is the handle we received from the SoundPool.load() method. The next two
parameters specify the volume to be used for the left and right channels. These values should be
in the range between 0 (silent) and 1 (ears explode).
Next come two arguments that we'll rarely use. The first one is the priority, which is currently
unused and should be set to 0 . The other argument specifies how often the sound effect should
be looped. Looping sound effects is not recommended, so you should generally use 0 here. The
final argument is the playback rate. Setting it to something higher than 1 will allow the sound
effect to be played back faster than it was recorded, while setting it to something lower than 1
will result in a slower playback.
When we no longer need a sound effect and want to free some memory, we can use the
SoundPool.unload() method:
soundPool.unload(explosionId);
We simply pass in the handle we received from the SoundPool.load() method for that sound
effect, and it will be unloaded from memory.
Generally, we'll have a single SoundPool instance in our game, which we'll use to load, play, and
unload sound effects as needed. When we are done with all of our audio output and no longer
need the SoundPool, we should always call the SoundPool.release() method , which will release
all resources normally used up by the SoundPool . After the release, you can no longer use the
SoundPool , of course. Also, all sound effects loaded by that SoundPool will be gone.
Let's write a simple test activity that will play back an explosion sound effect each time we tap
the screen. We already know everything we need to know to implement this, so Listing 4-9
shouldn't hold any big surprises.
Listing 4-9. SoundPoolTest.java; Playing Back Sound Effects
package com.badlogic.androidgames;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
Search WWH ::




Custom Search