This class uses the MIDP 2.0 Media API to play four sound effects: a sheep's "baa," a dog's bark, and two short game-over MIDI tunes.
Create the SoundEffects
class
file
Import the required classes.
// unnamed package import javax.microedition.media.*; import java.io.*;
Create the SoundEffects
class.
The Player
class controls the rendering of time based
media data. It provides the methods to manage the Player
's
life cycle, controls the playback progress and obtains the presentation components.
For
more informations, see Player
in
the MIDP 2.0 API specification.
class SoundEffects { private static SoundEffects instance; private Player sheepSoundPlayer; private Player dogSoundPlayer;
Initialize
the sound effects for the animal noises. The createPlayer
method
is detailed later in step 7.
private SoundEffects() { sheepSoundPlayer = createPlayer("/sheep.wav", "audio/x-wav"); dogSoundPlayer = createPlayer("/dog.wav", "audio/x-wav"); } static SoundEffects getInstance() { if (instance == null) { instance = new SoundEffects(); } return instance; }
Create methods for playing the sound effects.
void startSheepSound() { startPlayer(sheepSoundPlayer); } void startDogSound() { startPlayer(dogSoundPlayer); } void startGameOverSound() { startPlayer(createPlayer("/gameover.mid", "audio/midi")); } void startHighScoreSound() { startPlayer(createPlayer("/highscore.mid", "audio/midi")); }
Create a method
to control the playing of the sound effects detailed in step 5. The stop
method
stops the Player
, start
starts the Player
as
soon as possible and setMediaTime
sets the Player
's
media time. A MediaException
indicates an unexpected
error condition in a method.
For more information, see stop
, start
, setMediaTime
and MediaException
in
the MIDP 2.0 API specification.
private void startPlayer(Player p) { if (p != null) { try { p.stop(); p.setMediaTime(0L); p.start(); } catch (MediaException me) { // ignore } } }
Create a method
for fetching the individual sounds from external files. Manager
is
the access point for obtaining system dependent resources such as Player
s
for multimedia processing. The createPlayer
method creates
a Player
to play back media from an InputStream
whereas
the prefetch
method acquires the scarce and exclusive
resources and processes as much data as necessary to reduce the start latency.
For
more information, see Manager
, createPlayer
, prefetch
in
and the MIDP 2.0 API specification.
private Player createPlayer(String filename, String format) { Player p = null; try { InputStream is = getClass().getResourceAsStream(filename); p = Manager.createPlayer(is, format); p.prefetch(); } catch (IOException ioe) { // ignore } catch (MediaException me) { // ignore } return p; } }