Game Development Reference
In-Depth Information
Setting the Volume Controls
If you have an Android device, you will have noticed that when you press the volume up and
down buttons, you control different volume settings depending on the application you are
currently using. In a call, you control the volume of the incoming voice stream. In a YouTube
application, you control the volume of the video's audio. On the home screen, you control the
volume of the system sounds, such as the ringer or an arriving instant message.
Android has different audio streams for different purposes. When we play back audio in our
game, we use classes that output sound effects and music to a specific stream called the
music
stream
. Before we think about playing back sound effects or music, we first have to make sure
that the volume buttons will control the correct audio stream. For this, we use another method of
the
Context
interface:
context.setVolumeControlStream(AudioManager.STREAM_MUSIC);
As always, the
Context
implementation of our choice will be our activity. After this call, the
volume buttons will control the music stream to which we'll later output our sound effects and
music. We need to call this method only once in our activity life cycle. The
Activity.onCreate()
method is the best place to do this.
Writing an example that only contains a single line of code is a bit of overkill. Thus, we'll
refrain from doing that at this point. Just remember to use this method in all the activities that
output sound.
Playing Sound Effects
In Chapter 3, we discussed the difference between streaming music and playing back sound
effects. The latter are stored in memory and usually last no longer than a few seconds. Android
provides us with a class called
SoundPool
that makes playing back sound effects really easy.
We can simply instantiate new
SoundPool
instances as follows:
SoundPool soundPool =
new
SoundPool(20, AudioManager.STREAM_MUSIC, 0);
The first parameter defines the maximum number of sound effects we can play simultaneously.
This does not mean that we can't have more sound effects loaded; it only restricts how many
sound effects can be played concurrently. The second parameter defines the audio stream
where the
SoundPool
will output the audio. We chose the music stream where we have set the
volume controls as well. The final parameter is currently unused and should default to 0.
To load a sound effect from an audio file into heap memory, we can use the
SoundPool.load()
method. We store all our files in the
assets/
directory, so we need to use the overloaded
SoundPool.load()
method, which takes an
AssetFileDescriptor
. How do we get that
AssetFileDescriptor
? Easy—via the
AssetManager
that we worked with before. Here's how we'd
load an OGG file called
explosion.ogg
from the
assets/
directory via the
SoundPool
:
AssetFileDescriptor descriptor = assetManager.openFd("explosion.ogg");
int
explosionId = soundPool.load(descriptor, 1);