16.10. (Optional) Playing Audio |
There are several formats for audio files. Prior to Java 2, sound files in the AU format used on the UNIX operating system were the only ones Java was able to play. With Java 2, you can play sound files in the WAV, AIFF, MIDI, AU, and RMF formats, with better sound quality.
To play an audio file in an applet, first create an audio clip object for the audio file. The audio clip is created once and can be played repeatedly without reloading the file. To create an audio clip, use the static method newAudioClip() in the java.applet.Applet class:
AudioClip audioClip = Applet.newAudioClip(url);
Audio was originally used with Java applets. For this reason, the AudioClip interface is in the java.applet package.
The following statements, for example, create an AudioClip for the beep.au audio file in the class directory:
Class metaObject = this .getClass(); URL url = metaObject.getResource( "beep.au" ); AudioClip audioClip = Applet.newAudioClip(url);
To manipulate a sound for an audio clip, use the play() , loop() , and stop() methods in java.applet.AudioClip , as shown in Figure 16.15.
Listing 16.12 gives the code that displays the Danish flag and plays the Danish national anthem repeatedly. The image file image/denmark.gif and audio file audio/denmark.mid are stored under the class directory. Line 12 obtains the audio file URL. Line 13 creates an audio clip for the file. Line 14 repeatedly plays the audio.
1 import javax.swing.*; 2 import java.net.URL; 3 import java.applet.*; 4 5 public class DisplayImagePlayAudio extends JApplet { 6 private AudioClip audioClip; 7 8 public DisplayImagePlayAudio() { 9 URL urlForImage = getClass().getResource( "image/denmark.gif" ); 10 add( new JLabel( new ImageIcon(urlForImage))); 11 12 URL urlForAudio = getClass().getResource( "audio/denmark.mid" ); 13 audioClip = Applet.newAudioClip(urlForAudio); 14 audioClip.loop(); 15 } 16 17 public void start() { 18 if (audioClip != null ) audioClip.loop(); 19 } 20 21 public void stop() { 22 if (audioClip != null ) audioClip.stop(); 23 } 24 } |
The stop method (lines 21 “23) stops the audio when the applet is not displayed, and the start method (lines 17 “19) restarts the audio when the applet is redisplayed. Please try to run this applet from a browser and observe the effect without the stop and start methods.