Java Reference
In-Depth Information
To manipulate a sound for an audio clip, use the
play()
,
loop()
, and
stop()
methods in
java.applet.AudioClip
, as shown in Figure 18.14.
«interface»
java.applet.AudioClip
+play()
Starts playing this audio clip. Each time this method
is called, the clip is restarted from the beginning.
+loop()
+stop()
Plays the clip repeatedly.
Stops playing the clip.
F
IGURE
18.14
The
AudioClip
interface provides the methods for playing sound.
Listing 18.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
URL
object for the audio file, line 13
creates an audio clip for the file, and line 14 repeatedly plays the audio.
L
ISTING
18.12
DisplayImagePlayAudio.java
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
13
14
15 }
16
17 @Override
18
get image URL
create a label
URL urlForAudio = getClass().getResource(
"audio/denmark.mid"
);
get audio URL
create an audio clip
play audio repeatedly
audioClip = Applet.newAudioClip(urlForAudio);
audioClip.loop();
public void
start() {
start audio
19
if
(audioClip !=
null
) audioClip.loop();
20 }
21
22 @Override
23
public void
stop() {
24
if
(audioClip !=
null
) audioClip.stop();
stop audio
25 }
26 }
main method omitted
The
stop
method (lines 23-25) stops the audio when the applet is not displayed, and the
start
method (lines 18-20) restarts the audio when the applet is redisplayed. Try to run this
applet without the
stop
and
start
methods from a browser and observe the effect.
Run this program as a standalone application from the main method and from a Web browser
to test it. Recall that, for brevity, the
main
method in all applets is not printed in the text.
18.24
✓
✓
What types of audio files are used in Java?
Check
18.25
Point
How do you create an audio clip from the file
anthem/us.mid
in the class directory?
18.26
How do you play, repeatedly play, and stop an audio clip?