Java Reference
In-Depth Information
2.9.4 Working with Audio Content
In this section, we demonstrate how to play audio files with code from a
simple Audio Player MIDlet. We focus on the actual MMAPI code used
to play the audio file.
// code abbreviated for clarity
public void run()
{
try
{
player = Manager.createPlayer(url);
player.addPlayerListener(controller);
player.realize();
player.prefetch();
volumeControl = (VolumeControl)player.getControl("VolumeControl");
if (volumeControl != null)
{
volumeControl.setLevel(50);
}
else
{
controller.removeVolumeControl();
}
startPlayer();
}
catch (IOException ioe)
{
// catch exception connecting to the resource
}
catch (MediaException me)
{
// unable to create player for given MIME type
}
}
A
Player
is created and a
PlayerListener
is registered with it.
The controller reference serves two purposes: to facilitate callbacks to
the UI indicating the progress of the initialization (this has been omitted
for clarity); and to act as the
PlayerListener
which will be notified
of
Player
events. The
Player
is then moved through its states. In this
example, we obtain a
VolumeControl
(if the implementation supports
this feature) although it is not essential for simple audio playback. The
volume range provided is from 0-100. Here we set the volume level
midway and start the
Player
so the audio file content can be heard from
the phone's speakers.
Closing the player is a straightforward task:
public void closePlayer()
{
if (player != null)
{
player.close();
}
player = null;
volumeControl = null;
}