Game Development Reference
In-Depth Information
The dispose() method checks if the MediaPlayer is still playing and, if so, stops it. Otherwise,
the call to MediaPlayer.release() will throw a RuntimeException .
public boolean isLooping() {
return mediaPlayer.isLooping();
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public boolean isStopped() {
return !isPrepared;
}
The methods isLooping() , isPlaying() , and isStopped() are straightforward. The first two use
methods provided by the MediaPlayer ; the last one uses the isPrepared flag, which indicates if
the MediaPlayer is stopped. This is something MediaPlayer.isPlaying() does not necessarily
tell us since it returns false if the MediaPlayer is paused but not stopped.
public void pause() {
if (mediaPlayer.isPlaying())
mediaPlayer.pause();
}
The pause() method simply checks whether the MediaPlayer instance is playing and calls its
pause() method if it is.
public void play() {
if (mediaPlayer.isPlaying())
return ;
try {
synchronized ( this ) {
if (!isPrepared)
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The play() method is a little more involved. If we are already playing, we simply return from
the function. Next we have a mighty try...catch block within which we check to see if the
MediaPlayer is already prepared based on our flag; we prepare it if needed. If all goes well,
we call the MediaPlayer.start() method, which will start the playback. This is conducted in a
synchronized block, since we are using the isPrepared flag, which might get set on a separate
thread because we are implementing the OnCompletionListener interface. In case something
goes wrong, we throw an unchecked RuntimeException .
 
Search WWH ::




Custom Search