Game Development Reference
In-Depth Information
The
AudioManager
class is a singleton class so that we can access it from anywhere
in the code. It features a couple of overloaded
play()
methods just like the original
Sound
and
Music
interfaces. The advantage of overloading these methods is that
you can make some parameters optional. The methods in this class check against
the values in
GamePreferences
, which holds the currently loaded audio settings
among others. If the checkbox for sounds is not selected in the
Options
menu,
GamePreferences.instance.sound
will return
false
, and therefore any call of
AudioManager
class's
play()
will be aborted before the actual
play()
call of a
sound is executed.
Next, add the following code to the same class:
public void play (Music music) {
stopMusic();
playingMusic = music;
if (GamePreferences.instance.music) {
music.setLooping(true);
music.setVolume(GamePreferences.instance.volMusic);
music.play();
}
}
public void stopMusic () {
if (playingMusic != null) playingMusic.stop();
}
public void onSettingsUpdated () {
if (playingMusic == null) return;
playingMusic.setVolume(GamePreferences.instance.volMusic);
if (GamePreferences.instance.music) {
if (!playingMusic.isPlaying()) playingMusic.play();
} else {
playingMusic.pause();
}
}
This code adds another overloaded
play()
method, which takes an instance of
Music
that will be played. If music is already playing, it is stopped first. Then, new
music is initialized for playback and started if
Music
is enabled in the game settings.
The
onSettingsUpdated()
method is used to allow the
Options
menu to inform
AudioManager
when settings have changed to execute appropriate actions, such as
setting a new music volume.