Game Development Reference
In-Depth Information
Java sound must be implemented using the MediaPlayer API. This is a powerful media tool, but it
has some drawbacks when dealing with game sound:
The MediaPlayer can only open raw resources (sound files within your project) or
files located in the file system. This is a serious caveat if the game packs sprites
and sounds in a single file. 3D games like Doom and Wolf 3D use a single file for
sprites and sounds, and they use a mixer device to combine streams of bytes
simultaneously. This solution is not possible with the MediaPlayer .
• The MediaPlayer API has some annoying idiosyncrasies when developing. For
example, playing a resource sound is easy:
MediaPlayer mPlayer = MediaPlayer.create(Context, RESOURCEID);
mPlayer.start();
However if you attempt to pause a sound before it plays or issue two simultaneous
play commands, the MediaPlayer throws an IllegalState exception. The same thing
happens if you try to replay a sound before preparing or making sure the player
has been paused. These limitations make dealing with the player annoying and
difficult for a game where multiple sounds must be replayed continuously.
• The MediaPlayer consumes significant resources and can slow things down quite a
bit, especially if you have lots of sounds.
Listing 3-8 shows the AudioClip sound class. It is designed to mirror the Java SE class of the same
name by wrapping an instance of the MediaPlayer and dealing with the media events behind the scenes.
Listing 3-8. An Audio Helper Class
package ch03.common;
import android.content.Context;
import android.media.MediaPlayer;
public class AudioClip {
private MediaPlayer mPlayer;
private String name;
private boolean mPlaying = false;
private boolean mLoop = false;
public AudioClip(Context ctx, int resID)
{
// clip name
name = ctx.getResources().getResourceName(resID);
// Create a media player
mPlayer = MediaPlayer.create(ctx, resID);
// Listen for completion events
mPlayer.setOnCompletionListener(
new MediaPlayer.OnCompletionListener() {
Search WWH ::




Custom Search