I would like to play background music in my J2ME game. How can I code that function?
+3
A:
You have a similar question at http://stackoverflow.com/questions/473809/playing-audio-with-j2me
For ease I have posted some code from that thread:
// 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;
Suraj Chandran
2010-01-12 05:15:05
If this is for background music in a game, I would also suggest using MIDI audio data, instead of a simple .wav file.
QuickRecipesOnSymbianOS
2010-01-12 11:35:33
@ QuickRecipesOnSymbianOS: could you be more specific and give me some code sample?
Chan Pye
2010-01-13 01:40:20
A:
In reference to QuickRecipes comment Chan, MIDIs are preferable to use for background music since they are much smaller than WAVs and the primary disadvantage of MIDIs, a possibly delay start time is less of an issue when playing background music than it would be for sound effects such as gunshots that need to play instantly. As far as code changes MIDIs and WAVs are just different encoded types, a generic Player can play either type so the code changes are essentially nill.
Colin
2010-02-05 17:45:58