Game Development Reference
In-Depth Information
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
}
We keep a reference to the
MediaPlayer
in the form of a member of our activity. In the
onCreate()
method, we simply create a
TextView
for outputting any error messages, as always.
Before we start playing around with the
MediaPlayer
, we make sure that the volume controls
actually control the music stream. Having that set up, we instantiate the
MediaPlayer
. We fetch
the
AssetFileDescriptor
from the
AssetManager
for a file called
music.ogg
located in the
assets/
directory, and set it as the data source of the
MediaPlayer
. All that's left to do is to prepare
the
MediaPlayer
instance and set it to loop the stream. In case anything goes wrong, we set
the
MediaPlayer
member to
null
so we can later determine whether loading was successful.
Additionally, we output some error text to the
TextView
.
In the
onResume()
method, we simply start the
MediaPlayer
(if creating it was successful). The
onResume()
method is the perfect place to do this because it is called after
onCreate()
and after
onPause()
. In the first case, it will start the playback for the first time; in the second case, it will
simply resume the paused
MediaPlayer
.
The
onResume()
method pauses the
MediaPlayer
. If the activity is going to be killed, we stop the
MediaPlayer
and then release all of its resources.
If you play around with this, make sure you also test out how it reacts to pausing and resuming
the activity, by either locking the screen or temporarily switching to the home screen. When
resumed, the
MediaPlayer
will pick up from where it left off when it was paused.
Here are a couple of things to remember:
MediaPlayer.start()
,
MediaPlayer.pause()
, and
MediaPlayer.
resume()
can only be called in certain states, as just discussed. Never try to
call them when you haven't yet prepared the
MediaPlayer
. Call
MediaPlayer.
start()
only after preparing the
MediaPlayer
or when you want to resume it
after you've explicitly paused it via a call to
MediaPlayer.pause()
.
ï?®
MediaPlayer
instances are pretty heavyweight. Having many of them
instanced will take up a considerable amount of resources. We should
always try to have only one for music playback. Sound effects are better
handled with the
SoundPool
class.
Remember to set the volume controls to handle the music stream, or else
The methods
ï?®
ï?®
your players won't be able to adjust the volume of your game.
We are almost done with this chapter, but one big topic still lies ahead of us: 2D graphics.
Basic Graphics Programming
Android offers us two big APIs for drawing to the screen. One is mainly used for simple
2D graphics programming, and the other is used for hardware-accelerated 3D graphics
programming. This and the next chapter will focus on 2D graphics programming with the
Canvas