J2ME Learning (3) - How to Play Sound

xiaoxiao2021-03-06  42

J2ME Learning (3) - How to Play Sound

In J2ME, processing sound requires the Mobile Media API (MMAPI), which is the option package of MIDP 1.0, which already contains this package in MIDP2.0. So if you use MIDP1.0, please confirm if your running environment is supported.

The sound file format for general mobile phone is WAV, MID and MPG, etc. Please check your mobile phone documentation for details.

In sound processing, there are many ways to process, here is the most commonly used case, play the WAV file in the JAR file.

Play the flow of sound files:

1. Read the sound file in a certain format.

Sound files in the JAR file are generally in the form of a stream of sound files. Sample code:

InputStream IS = this.getClass (). GetResourceAsStream ("/ autorun.wav");

The autorun.wav file is located in the root of the JAR file. If you are in other directories, you need to add a directory name, such as / res /autorun.wav.

2. Pass the read content to the player.

Pass the stream information to the player, the player performs decoding operations in a certain format, sample code:

Player Player = Manager.createPlayer (IS, "AUDIO / X-WAV");

The first parameter is the stream object, the second parameter is the format of the sound file.

3, play the sound.

Use the Start method of the Player object, you can play the sound, sample code:

Player.start ();

When playing sound, you can also set the number of sound playbacks, you can implement the setLoopCount method in the Player class, which can be found in the API document.

The following is a test in the NOKIA S60 simulator. code show as below:

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) {

}

}

For more articles, please visit my blog:

http://blog.9cbs.net/mailbomb

转载请注明原文地址:https://www.9cbs.com/read-73463.html

New Post(0)