Playing media in J2ME
The simplest MMAPI MIDlet that can be built allows you to easily play a multimedia file from within your MIDlet without worrying about controls, feature sets, or security architecture. If all you’re doing is adding some sampled audio (or any other media) in a game, MMAPI allows you to do so in two lines of code. Listing below shows this code within a complete MIDlet.
//A Simple MMAPI MIDlet
import javax.microedition.midlet.MIDlet;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
public class SimplePlayer extends MIDlet {
public void startApp() {
try {
Player player = Manager.createPlayer(getClass().getResourceAsStream("/media/audio/chapter3/baby.wav"),"audio/x-wav");
player.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
To keep things simple at this stage, the media file is played by creating an InputStream on a wav file, which is embedded in the MIDlet’s JAR. This media file is kept in the folder media/audio/chapter3 and is called baby.wav (which is the sound of a baby crying).
Of course, you don’t need to play an audio file only. You can substitute the wav file with a video file, provided the emulator supports the format of the video file. The video will not show anywhere, because this listing doesn’t provide a mechanism to show the video. You can substitute the wav file for a midi, tone, or any other supported audio format. The point is that playing multimedia files using the MMAPI is as simple as creating a Player instance using the Manager class and calling method start() on it.
//A Simple MMAPI MIDlet
import javax.microedition.midlet.MIDlet;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
public class SimplePlayer extends MIDlet {
public void startApp() {
try {
Player player = Manager.createPlayer(getClass().getResourceAsStream("/media/audio/chapter3/baby.wav"),"audio/x-wav");
player.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
To keep things simple at this stage, the media file is played by creating an InputStream on a wav file, which is embedded in the MIDlet’s JAR. This media file is kept in the folder media/audio/chapter3 and is called baby.wav (which is the sound of a baby crying).
Of course, you don’t need to play an audio file only. You can substitute the wav file with a video file, provided the emulator supports the format of the video file. The video will not show anywhere, because this listing doesn’t provide a mechanism to show the video. You can substitute the wav file for a midi, tone, or any other supported audio format. The point is that playing multimedia files using the MMAPI is as simple as creating a Player instance using the Manager class and calling method start() on it.
Comments
Post a Comment