Game Development Reference
In-Depth Information
Listing 5-4. AndroidMusic.java; Implementing the Music Interface
package
com.badlogic.androidgames.framework.impl;
import
java.io.IOException;
import
android.content.res.AssetFileDescriptor;
import
android.media.MediaPlayer;
import
android.media.MediaPlayer.OnCompletionListener;
import
com.badlogic.androidgames.framework.Music;
public class
AndroidMusic
implements
Music, OnCompletionListener {
MediaPlayer mediaPlayer;
boolean
isPrepared=
false
;
The
AndroidMusic
class stores a
MediaPlayer
instance along with a Boolean called
isPrepared
.
Remember, we can only call
MediaPlayer.start()
/
stop()
/
pause()
when the
MediaPlayer
is
prepared. This member helps us keep track of the
MediaPlayer
's state.
The
AndroidMusic
class implements the
Music
interface as well as the
OnCompletionListener
interface. In Chapter 4, we briefly defined this interface as a means of informing ourselves about
when a
MediaPlayer
has stopped playing back a music file. If this happens, the
MediaPlayer
needs to be prepared again before we can invoke any of the other methods. The method
OnCompletionListener.onCompletion()
might be called in a separate thread, and since we set
the
isPrepared
member in this method, we have to make sure that it is safe from concurrent
modifications.
public
AndroidMusic(AssetFileDescriptor assetDescriptor) {
mediaPlayer=
new
MediaPlayer();
try
{
mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
assetDescriptor.getStartOffset(),
assetDescriptor.getLength());
mediaPlayer.prepare();
isPrepared=
true
;
mediaPlayer.setOnCompletionListener(
this
);
}
catch
(Exception e) {
throw new
RuntimeException("Couldn't load music");
}
}
In the constructor, we create and prepare the
MediaPlayer
from the
AssetFileDescriptor
that is
passed in, and we set the
isPrepared
flag, as well as register the
AndroidMusic
instance as an
OnCompletionListener
with the
MediaPlayer
. If anything goes wrong, we throw an unchecked
RuntimeException
once again.
public void
dispose() {
if
(mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
}