370
|
Chapter 10, Audio
#72 Play a Sound with Java Media Framework
HACK
The major change from the CoreJavaSound demo is in the constructor, after
the dialog is readied. You create a
MediaLocator, a sort of generic means of
referring to the source location of media, from a URL of the selected file.
The
MediaLocator allows you to create a Player with a one-line call to
Manager.createRealizedPlayer(MediaLocator). A lot occurs in this call: the
Manager, a sort of central point of access to JMF resources, creates a Player,
wires it up to the
MediaLocator, calls prefetch( ) to process some of the
media data (to reduce startup delay), and calls
realize( ) to allocate system-
dependent media resources. The result is a ready-to-play
Player.
To add event-awareness, add a listener with
addControllerListener( ),
Controller being a superclass of Player. Finally, you can play the media with
start( ).
The
ControllerListener interface defines a single method, controllerUpdate(),
which receives a
ControllerEvent. In JMF, the class of the event is used for
determining behavior; there are more than a dozen you might choose to deal
with. To get the “end of the media” event, you just check to see if the event
is an
EndOfMediaEvent object, which in this case is handled by hiding the dia-
log and quitting the application.
Take JMF for a Spin
Functionally, the application is largely identical to the CoreJavaSound demo:
a
JFileChooser asks you to pick a file. When you do, it starts playing and a
dialog box shows you the filename. When the audio completes, the applica-
tion quits.
player.addControllerListener (this);
player.prefetch( );
player.start( );
playingDialog.setVisible(true);
}
// ControllerListener implementation
public void controllerUpdate (ControllerEvent e) {
System.out.println (e.getClass().getName( ));
if (e instanceof EndOfMediaEvent) {
playingDialog.setVisible(false);
System.exit (0);
}
}
}
Example 10-4. Playing audio with Java Media Framework (continued)

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.