AhmadLang / Java, How To Program, 2004
.pdf
[Page 987 (continued)]
21.5. Loading and Playing Audio Clips
Java programs can manipulate and play audio clips. Users can capture their own audio clips, and many clips are available in software products and over the Internet. Your system needs to be equipped with audio hardware (speakers and a sound card) to be able to play the audio clips.
Java provides several mechanisms for playing sounds in an applet. The two simplest are the Applet's play method and the play method of the AudioClip interface. Additional audio capabilities are
available in the Java Media Framework and Java Sound APIs. If you would like to play a sound once in a program, the Applet method play loads the sound and plays it oncethe sound is marked for garbage collection after it plays. The Applet method play has two versions:
[Page 988]
public void play( URL location, String soundFileName ); public void play( URL soundURL );
The first version loads the audio clip stored in file soundFileName from location and plays the sound. The first argument is normally a call to the applet's getdocumentBase or getCodeBase method. Method geTDocumentBase returns the location of the HTML file that loaded the applet. (If the applet is in a package, the method returns the location of the package or the JAR file containing the package.) Method getCodeBase indicates the location of the applet's .class file. The second version of method play takes a URL that contains the location and the file name of the audio clip. The statement
[Page 990]
play( getDocumentBase(), "hi.au" );
loads the audio clip in file hi.au and plays the clip once.
[Page 991]
The sound engine that plays the audio clips supports several audio file formats, including Sun Audio file format (.au extension), Windows Wave file format (.wav extension), Macintosh AIFF file format (.aif or .aiff extensions) and Musical Instrument Digital Interface (MIDI) file format (.mid or .rmi extensions). The Java Media Framework (JMF) and Java Sound APIs support additional formats.
The program of Fig. 21.5 demonstrates loading and playing an AudioClip (package java.applet). This technique is more flexible than Applet method play. An applet can use an AudioClip to store audio for repeated use throughout a program's execution.
Figure 21.5. Loading and playing an AudioClip.
(This item is displayed on pages 991 - 992 in the print version)
1 // Fig. 21.5: LoadAudioAndPlay.java 2 // Load an audio clip and play it.
3import java.applet.AudioClip;
4import java.awt.event.ItemListener;
5import java.awt.event.ItemEvent;
6import java.awt.event.ActionListener;
7import java.awt.event.ActionEvent;
8import java.awt.FlowLayout;
9import javax.swing.JApplet;
10import javax.swing.JButton;
11import javax.swing.JComboBox;
12
13public class LoadAudioAndPlay extends JApplet
14{
15private AudioClip sound1, sound2, currentSound;
16private JButton playJButton, loopJButton, stopJButton;
17private JComboBox soundJComboBox;
18
19// load the image when the applet begins executing
20public void init()
21{
22setLayout( new FlowLayout() );
23
24String choices[] = { "Welcome", "Hi" };
25soundJComboBox = new JComboBox( choices ); // create JComboBox
27 |
soundJComboBox.addItemListener( |
28 |
|
29new ItemListener() // anonymous inner class
30{
31 |
// stop sound and change to sound to user's selection |
32 |
public void itemStateChanged( ItemEvent e ) |
33 |
{ |
34 |
currentSound.stop(); |
35 |
currentSound = soundJComboBox.getSelectedIndex() == 0 ? |
36 |
sound1 : sound2; |
37 |
} // end method itemStateChanged |
38} // end anonymous inner class
39); // end addItemListener method call
41add( soundJComboBox ); // add JComboBox to applet
43// set up button event handler and buttons
44ButtonHandler handler = new ButtonHandler();
46// create Play JButton
47playJButton = new JButton( "Play" );
48playJButton.addActionListener( handler );
49add( playJButton );
51// create Loop JButton
52loopJButton = new JButton( "Loop" );
53loopJButton.addActionListener( handler );
54add( loopJButton );
56// create Stop JButton
57stopJButton = new JButton( "Stop" );
58stopJButton.addActionListener( handler );
59add( stopJButton );
61// load sounds and set currentSound
62sound1 = getAudioClip( getDocumentBase(), "welcome.wav" );
63sound2 = getAudioClip( getDocumentBase(), "hi.au" );
64currentSound = sound1;
65} // end method init
67// stop the sound when the user switches Web pages
68public void stop()
69{
70currentSound.stop(); // stop AudioClip
71} // end method stop
72
73// private inner class to handle button events
74private class ButtonHandler implements ActionListener
75{
76// process play, loop and stop button events
77public void actionPerformed( ActionEvent actionEvent )
78{
79if ( actionEvent.getSource() == playJButton )
80 |
currentSound.play(); // play AudioClip once |
|
||||||||
81 |
else |
if |
( |
actionEvent.getSource() |
== |
loopJButton |
) |
|||
82 |
currentSound.loop(); |
// |
play |
AudioClip continuously |
||||||
83 |
else |
if |
( |
actionEvent.getSource() |
== |
stopJButton |
) |
|||
84 |
currentSound.stop(); |
// |
stop |
AudioClip |
|
|||||
85} // end method actionPerformed
86} // end class ButtonHandler
87 } // end class LoadAudioAndPlay
[Page 993]
Applet method getAudioClip has two forms that take the same arguments as method play described previously. Method getAudioClip returns a reference to an AudioClip. An AudioClip has three methodsplay, loop and stop. As mentioned earlier, method play plays the audio clip once. Method loop continuously loops through the audio clip in the background. Method stop terminates an audio clip that is currently playing. In the program, each of these methods is associated with a button on the applet.
Lines 6263 in the applet's init method use getAudioClip to load two audio filesa Windows Wave file (welcome.wav) and a Sun Audio file (hi.au). The user can select which audio clip to play from the JComboBox soundJComboBox. Note that the applet's stop method is overridden at lines 6871. When the user switches Web pages, the applet container calls the applet's stop method. This enables the applet to stop playing the audio clip. Otherwise, it continues to play in the backgroundeven if the applet is not displayed in the browser. This is not necessarily a problem, but it can be annoying to the user if the audio clip is looping. The stop method is provided here as a convenience to the user.
Look-and-Feel Observation 21.5
When playing audio clips in an applet or application, provide a mechanism for the user to disable the audio.
[Page 993 (continued)]
21.6. Playing Video and Other Media with Java Media Framework
A simple video can concisely and effectively convey a great deal of information. Recognizing the value of bringing extensible multimedia capabilities to Java, Sun Microsystems, Intel and Silicon Graphics worked together to produce the multimedia API Java Media Framework (JMF), discussed briefly in Section 21.1. Using the JMF API, programmers can create Java applications that play, edit, stream and capture many popular media types. While the features of JMF are quite extensive, this section briefly introduces some popular media formats and demonstrates playing video using the JMF API.
IBM and Sun developed the latest JMF specificationversion 2.0. Sun also provides a reference implementation of the JMF specificationJMF 2.1.1ethat supports media file types such as Microsoft Audio/Video Interleave (.avi), Macromedia Flash 2 movies (.swf), Future Splash (.spl),
MPEG Layer 3 Audio (.mp3), Musical Instrument Digital Interface (MIDI; .mid or .rmi extensions), MPEG-1 videos (.mpeg, .mpg), QuickTime (.mov), Sun Audio file format (.au extension), and Macintosh AIFF file format (.aif or .aiff extension). You have already seen some of these files types.
Currently, JMF is available as an extension separate from the Java 2 Software Development Kit. The most recent JMF implementation (2.1.1e) can be downloaded from:
http://java.sun.com/products/java-media/jmf/2.1.1/download.html
You need to accept the license agreement prior to downloading.
The JMF Web site provides versions of the JMF that take advantage of the performance features of certain platforms. For example, the JMF Windows Performance Pack provides extensive media and device support for Java programs running on Microsoft Windows platforms (Windows 95/98/NT 4.0/2000/XP). JMF's official Web site (java.sun.com/products/java-media/jmf) provides continually updated support, information and resources for JMF programmers.
[Page 994]
Once the file finishes downloading, open it and follow the on-screen instructions to install the program. Leave all options at their defaults. You may need to restart your computer to finish the installation.
Creating a Simple Media Player
The JMF offers several mechanisms for playing media. The simplest mechanism is using objects that implement interface Player declared in package javax.media. Package javax.media and its subpackages contain the classes that compose the Java Media Framework. To play a media clip you must first create a URL object that refers to it. Then pass the URL as an argument to static method createRealizedPlayer of class Manager to obtain a Player for the media clip. Class Manager declares utility methods for accessing system resources to play and to manipulate media. Figure 21.6 declares a JPanel that demonstrates some of these methods.
Figure 21.6. JPanel that plays a media file from a URL.
(This item is displayed on page 995 in the print version)
1 // Fig. 21.6: MediaPanel.java
2 // A JPanel the plays media from a URL
3import java.awt.BorderLayout;
4import java.awt.Component;
5import java.io.IOException;
6import java.net.URL;
7import javax.media.CannotRealizeException;
8import javax.media.Manager;
9import javax.media.NoPlayerException;
10import javax.media.Player;
11import javax.swing.JPanel;
12
13public class MediaPanel extends JPanel
14{
15public MediaPanel( URL mediaURL )
16{
17setLayout( new BorderLayout() ); // use a BorderLayout
Figure 21.7. Test application that creates a MediaPanel from a userselected file.
(This item is displayed on pages 996 - 997 in the print version)
1// Fig. 21.7: MediaTest.java
2// A simple media player
3import java.io.File;
4import java.net.MalformedURLException;
5import java.net.URL;
6import javax.swing.JFileChooser;
7import javax.swing.JFrame;
8
9public class MediaTest
10{
11// launch the application
12public static void main( String args[] )
13{
14// create a file chooser
15JFileChooser fileChooser = new JFileChooser();
17// show open file dialog
18int result = fileChooser.showOpenDialog( null );
20if ( result == JFileChooser.APPROVE_OPTION ) // user chose a file
21{
22URL mediaURL = null;
24try
25{
26 |
// get the |
file as URL |
27 |
mediaURL = |
fileChooser.getSelectedFile().toURL(); |
28} // end try
29catch ( MalformedURLException malformedURLException )
30{
31System.err.println( "Could not create URL for the file" );
32} // end catch
33 |
|
34 |
if ( mediaURL != null ) // only display if there is a valid URL |
35{
36JFrame mediaTest = new JFrame( "Media Tester" );
37mediaTest.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
39MediaPanel mediaPanel = new MediaPanel( mediaURL );
40mediaTest.add( mediaPanel );
41
42mediaTest.setSize( 300, 300 );
43mediaTest.setVisible( true );
44} // end inner if
45} // end outer if
46} // end main
47} // end class MediaTest
[View full size image]
[Page 997]
Method main (lines 1246) assigns a new JFileChooser to local variable fileChooser (line 15), shows an open file dialog (line 18) and assigns the return value to result. Line 20 checks result to determine whether the user chose a file. To create a Player to play the selected media file, you must convert the File object returned by JFileChooser to a URL object. Method toURL of class File returns a URL that points to the File on the system, possibly throwing a MalformedURLException if it cannot create a URL object for the File. The try statement (lines 2432) creates a URL for the selected file and assigns it to mediaURL. The if statement in lines 3444 checks that mediaURL is not null and creates the GUI components to play the media.
[Page 997 (continued)]
21.7. Wrap-Up
In this chapter, you learned how to make applications more exciting by including sound, images, graphics and video. We introduced Java's multimedia capabilities, including the Java Media Framework API, Java Sound API and Java 3D API. You used classes Image and ImageIcon to display and manipulate images stored in files, and you learned about the different image formats supported by Java. You created animation by displaying a series of images in a specific order. You used image maps to make an application more interactive. You then learned how to load audio clips, and how to play them either once or in a continuous loop. The chapter concluded with a demonstration of loading and playing video. In the next chapter, you will continue your study of GUI concepts, building on the techniques you learned in Chapter 11.
[Page 998]
[Page 998 (continued)]
21.8. Internet and Web Resources
www.nasa.gov/multimedia/highlights/index.html
The NASA Multimedia Gallery contains a wide variety of images, audio clips and video clips that you can download and use to test your Java multimedia programs.
sunsite.tus.ac.jp/multimed
The Sunsite Japan Multimedia Collection also provides a wide variety of images, audio clips and video clips that you can download for educational purposes.
www.anbg.gov.au/anbg/index.html
The Australian National Botanic Gardens Web site provides links to the sounds of many animals. Try, for example, the Common Birds link under the "Animals in the Gardens" section.
www.thefreesite.com
TheFreeSite.com has links to free sounds and clip art.
www.soundcentral.com
SoundCentral provides audio clips in WAV, AU, AIFF and MIDI formats.
www.animationfactory.com
The Animation Factory provides thousands of free GIF animations for personal use.
www.clipart.com
ClipArt.com is a subscription-based service for images and sounds.
www.pngart.com
PNGART.com provides over 50,000 free images in PNG format.
java.sun.com/developer/techDocs/hi/repository
The Java look and feel Graphics Repository provides images designed for use in a Swing GUI, including toolbar button images.
www.freebyte.com/graphicprograms
This guide contains links to several free graphics software programs. The software can be used to modify images and draw graphics.
graphicssoft.about.com/od/pixelbasedfreewin
This site provides links for free graphics programs designed for use on Windows machines.
Java Multimedia API References
java.sun.com/products/java-media/jmf
This is the Java Media Framework (JMF) API home page. Here you can download the latest Sun implementation of the JMF. The site also contains the documentation for the JMF.
java.sun.com/products/java-media/sound
The Java Sound API home page. Java Sound provides capabilities for playing and recording audio.
java.sun.com/products/java-media/3D
The Java 3D API home page. This API can be used to produce three-dimensional images typical of today's video games.
java.sun.com/developer/onlineTraining/java3d
This site provides a Java 3D API tutorial.
[Page 999]
java.sun.com/products/java-media/jai
The Java Advanced Imaging API home page. This API provides image-processing capabilities, such as contrast enhancement, cropping, scaling and geometric warping.
java.sun.com/products/java-media/speech
The Java Speech API enables programs to perform speech synthesis and speech recognition.
freetts.sourceforge.net/docs/index.php
FreeTTS is an implementation of the Java Speech API.
java.sun.com/products/java-media/2D
This is the Java 2D API home page. This API (introduced in Chapter 12) provides complex twodimensional graphics capabilities.
java.sun.com/j2se/1.4.2/docs/guide/imageio
This site contains a guide to the Java Image I/O API, which enables programs to load and save images using formats that are not currently supported by the Java APIs.
