Table of ContentsDeveloping with MIDP 2Enhanced LCDUI

Sound

One of the great additions to MIDP is the inclusion of sound. Whereas with MIDP 1 you were limited to a simple beep (through the Alert class) without using a device SDK, MIDP 2 lets you play tones and (on some implementations) even sampled audio (WAV files).

NOTE

Note

The sound components of MIDP 2 are actually just a subset of the MMAPI (Mobile Media API) JSR 135. You can check out the full API on the Java Web site.

The sound functions are available under the javax.microedition.media class hierarchy. The simplest sound you can make is to generate a tone using the Manager class method playTone. This call takes a frequency value representing the tone you want to play, duration in milliseconds, and a volume ranging between 0 and 100. Here's an example that plays a low tone for 500 milliseconds at half volume:

try
{
    Manager.playTone(20, 500, 50);
}
catch (MediaException e) { }

Every MIDP 2 device must support at least tone generation; however, they will most likely also support WAV file playback, which gives you far greater potential to add some great sound to games.

To play a WAV sound you need to add a resource file to the JAR and then load it as an input stream. You can then play it back using a Player object. For example:

try
{
    InputStream in = getClass().getResourceAsStream("/fire1.wav");
    Player p = Manager.createPlayer(in, "audio/x-wav");
    p.start();
}
catch (MediaException me) { }
catch (IOException ioe) { }

You also can check the state of a sound (such as whether it's already playing) using the getState() method.

    Table of ContentsDeveloping with MIDP 2Enhanced LCDUI