Deitel & Associates, Inc. Logo

Back to
digg.png delicious.png blinkit.png furl.png
Java How to Program, 6/e

© 2005
pages: 1576

Buy the Book!
Amazon logo
InformIT logo

Java, through its class libraries, provides extensive multimedia facilities that enable you to develop powerful multimedia applications. In this tutorial, we introduce basic audio playback capabilities. In our subsequent tutorial, we show how to play video and other media with the Java Media Framework. These tutorials are intended for students and developers who are familiar with Java GUIs and event handling.

Download the code examples for this tutorial.

[Note: This tutorial is an excerpt (Section 21.5) of Chapter 21, Multimedia, from our textbook Java How to Program, 6/e. This tutorial may refer to other chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., JAVA HOW TO PROGRAM, ©2005, pp.987-992. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]

21.5 Loading and Playing 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 once—the sound is marked for garbage collection after it plays. The Applet method play has two versions:

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

play( getDocumentBase(), "" );

loads the audio clip in file and plays the clip once.

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. 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 methods—play, 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.

Fig. 21.5 | Loading and playing an AudioClip.
1     // Fig. 21.5:
2     // Load an audio clip and play it.
3     import java.applet.AudioClip;
4     import java.awt.event.ItemListener;
5     import java.awt.event.ItemEvent;
6     import java.awt.event.ActionListener;
7     import java.awt.event.ActionEvent;
8     import java.awt.FlowLayout;
9     import javax.swing.JApplet;
10    import javax.swing.JButton;
11    import javax.swing.JComboBox;
13    public class LoadAudioAndPlay extends JApplet
14    {
15      private AudioClip sound1, sound2, currentSound;
16      private JButton playJButton, loopJButton, stopJButton;
17      private JComboBox soundJComboBox;
19       // load the image when the applet begins executing
20      public void init()
21      {
22         setLayout( new FlowLayout() );
24         String choices[] = { "Welcome", "Hi" };
25         soundJComboBox = new JComboBox( choices ); // create JComboBox
27         soundJComboBox.addItemListener(
29            new 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
41            add( soundJComboBox ); // add JComboBox to applet
43             // set up button event handler and buttons
44            ButtonHandler handler = new ButtonHandler();
46            // create Play JButton
47            playJButton = new JButton( "Play" );
48            playJButton.addActionListener( handler );
49            add( playJButton );
51            // create Loop JButton
52            loopJButton = new JButton( "Loop" );
53            loopJButton.addActionListener( handler );
54            add( loopJButton );
56            // create Stop JButton
57            stopJButton = new JButton( "Stop" );
58            stopJButton.addActionListener( handler );
59            add( stopJButton );
61             // load sounds and set currentSound
62            sound1 = getAudioClip( getDocumentBase(), "welcome.wav" );
63            sound2 = getAudioClip( getDocumentBase(), "" );
64            currentSound = sound1;
65         } // end method init
67          // stop the sound when the user switches Web pages
68         public void stop()
69    {
70            currentSound.stop(); // stop AudioClip
71         } // end method stop
73          // private inner class to handle button events
74         private class ButtonHandler implements ActionListener
75         {
76             // process play, loop and stop button events
77            public void actionPerformed( ActionEvent actionEvent )
78            {
79               if ( actionEvent.getSource() == playJButton )
80        ; // 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

Lines 62–63 in the applet's init method use getAudioClip to load two audio files—a Windows Wave file (welcome.wav) and a Sun Audio file ( The user can select which audio clip to play from the JComboBox soundJComboBox. Note that the applet's stop method is overridden at lines 68–71. 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 background—even 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.

Return to Tutorial Index