Play a Sound with Java Media Framework #72
Chapter 10, Audio
|
369
HACK
The Code
The demo in Example 10-4 is basically a port of the CoreJavaSound demo
used in playing audio with JavaSound
[Hack #71]
, except that the event-
handling has been simplified to a “quit when done” implementation. JMF’s
playback metaphor involves
Player
s, which simply play media, and
Processor
s, which may take action on the media, such as adding effects or
transcoding to other formats. This allows the simple stuff to stay simple: to
play a file, you wire it up to a
Player, tell everything to get initialized (“real-
ized” in JMF parlance), and call
start( ). Notice that while the other imports
are omitted as usual, this listing shows the
import javax.media.* that will
bring in the JMF classes used here.
Example 10-4. Playing audio with Java Media Framework
import javax.media.*;
public class JMFSound extends Object
implements ControllerListener {
File soundFile;
JDialog playingDialog;
public static void main (String[] args) {
JFileChooser chooser = new JFileChooser( );
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile( );
try {
JMFSound s = new JMFSound (f);
} catch (Exception e) {
e.printStackTrace( );
}
}
public JMFSound (File f)
throws NoPlayerException, CannotRealizeException,
MalformedURLException, IOException {
soundFile = f;
// prepare a dialog to display while playing
JOptionPane pane = new JOptionPane ("Playing " + f.getName( ),
JOptionPane.PLAIN_MESSAGE);
playingDialog = pane.createDialog (null, "JMF Sound");
playingDialog.pack( );
// get a player
MediaLocator mediaLocator =
new MediaLocator(soundFile.toURL( ));
Player player =
Manager.createRealizedPlayer (mediaLocator);

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.