Game Development Reference
In-Depth Information
To stop the playback, we call the following method:
mediaPlayer.stop();
Note that when we want to start a stopped
MediaPlayer
, we first have to call the
MediaPlayer.
prepare()
method again.
We can set the
MediaPlayer
to loop the playback with the following method:
mediaPlayer.setLooping(true);
To adjust the volume of the music playback, we can use this method:
mediaPlayer.setVolume(1, 1);
This will set the volume of the left and right channels. The documentation does not specify within
what range these two arguments have to be. From experimentation, the valid range seems to be
between 0 and 1.
Finally, we need a way to check whether the playback has finished. We can do this in two ways.
For one, we can register an
OnCompletionListener
with the
MediaPlayer
that will be called when
the playback has finished:
mediaPlayer.setOnCompletionListener(listener);
If we want to poll for the state of the
MediaPlayer
, we can use the following method instead:
boolean isPlaying = mediaPlayer.isPlaying();
Note that if the
MediaPlayer
is set to loop, none of the preceding methods will indicate that the
MediaPlayer
has stopped.
Finally, if we are done with that
MediaPlayer
instance, we make sure that all the resources it
takes up are released by calling the following method:
mediaPlayer.release();
It's considered good practice always to do this before throwing away the instance.
In case we didn't set the
MediaPlayer
for looping and the playback has finished, we can restart
the
MediaPlayer
by calling the
MediaPlayer.prepare()
and
MediaPlayer.start()
methods again.
Most of these methods work asynchronously, so even if you called
MediaPlayer.stop()
, the
MediaPlayer.isPlaying()
method might return for a short period after that. It's usually nothing
we worry about. In most games, we set the
MediaPlayer
to be looped and then stop it when
the need arises (for example, when we switch to a different screen where we want other music
to be played).
Let's write a small test activity where we play back a sound file from the
assets/
directory
in looping mode. This sound effect will be paused and resumed according to the activity life
cycle—when our activity gets paused, so should the music, and when the activity is resumed,
the music playback should pick up from where it left off. Listing 4-10 shows how that's done.