In j2s, the Mobile Media API (MMAPI) is used to process the audio. This package is an optional package of MIDP1.0, which is included in MIDP2.0. Therefore, if you use MIDP1.0, check whether your runtime environment is supported.
Generally, audio files supported by mobile phones are in wav, mid, and mpg formats. For more information, see your mobile phone instructions.
There are many processing methods in sound processing. Here we will talk about the most common situation, playing wav files in JAR files.
Stream of playing audio files:
1. Read audio files in a certain format.
Playing a sound file in a JAR file is generally a form of processing the sound file into a stream. Sample Code:
InputStream is = this. getClass (). getResourceAsStream ("/Autorun.wav ");
In this example, the Autorun.wav file is located in the root directory of the JAR file. If it is located in another directory, you need to add the directory name, such as/res/Autorun.wav.
2. Pass the read content to the player.
The stream information is transmitted to the player. The Player decodes the stream information in a certain format. Example code:
Player player = Manager. createPlayer (is, "audio/x-wav ");
The first parameter is the stream object, and the second parameter is the audio file format.
3. Play the sound.
Use the start method of the Player Object to play the sound. Example code:
Player. start ();
You can also set the number of audio playback times when playing a sound. You can use the setLoopCount method in the Player class. For details, refer to the API documentation.
Below is the test passed in the NOKIA S60 simulator. The Code is as follows:
Package sound;
Import javax. microedition. midlet .*;
Import javax. microedition. lcdui .*;
Import javax. microedition. media .*;
Import java. io .*;
Public class SoundMIDlet extends MIDlet {
Private Player player = null;
/** Constructor */
Public SoundMIDlet (){
Try {
InputStream is = this. getClass (). getResourceAsStream ("/Autorun.wav ");
Player = Manager. createPlayer (is, "audio/x-wav ");
} Catch (IOException e ){
System. out. println ("1:" + e );
} Catch (MediaException e ){
System. out. println ("2:" + e );
} Catch (Exception e ){
System. out. println ("3:" + e );
}
}
/** Main method */
Public void startApp (){
If (player! = Null ){
Try {
Player. start ();
} Catch (MediaException e ){
System. out. println ("4:" + e );
}
}
}
/** Handle pausing the MIDlet */
Public void pauseApp (){
}
/** Handle destroying the MIDlet */
Public void destroyApp (boolean unconditional ){
}
}