O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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);

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required