What is the best way to play audio utilzing the J2ME Media libary? For example, should I make use of the MMAPI or should I just use the Midlet's platformRequest(String s) method?
The following code should work for 90-95% of handsets out there that support JSR-135. Ordering of all the various method calls is key for this to be portable. This is for sounds local to your JAR. Any streamed audio would be another problem altogether :)
// loads the InputStream for the sound
InputStream inputStream = this.getClass().getResourceAsStream( musicFile );
// create the standard Player
musicPlayer = Manager.createPlayer( inputStream, musicEncoding );
musicPlayer.prefetch();
// add player listener to access sound events
musicPlayer.addPlayerListener( this );
if( loopMusic )
{
// use the loop count method for infinite looping
musicPlayer.setLoopCount( -1 );
}
// The set occurs twice to prevent sound spikes at the very
// beginning of the sound.
VolumeControl volumeControl =
(VolumeControl) musicPlayer.getControl( "VolumeControl" );
volumeControl.setLevel( curVolume );
// finally start the piece of music
musicPlayer.start();
// set the volume once more
volumeControl = (VolumeControl) musicPlayer.getControl( "VolumeControl" );
volumeControl.setLevel( curVolume );
// finally, delete the input stream to save on resources
inputStream.close();
inputStream = null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With