The AudioClip Class
Many of the shortcomings of Applet's play() method are remedied by the AudioClip class. AudioClip separates loading from playing and allows looping and termination via the loop() and stop() methods. Example 7-2 is an updated McDonald applet using AudioClip.
Example 7-2. Applet using the AudioClip class
import java.awt.*;
import javax.swing.*;
import java.applet.AudioClip;
public class McDonald extends JApplet
{
private AudioClip mcdClip;
public void init()
{ mcdClip = getAudioClip(getCodeBase(), "mcdonald.mid"); }
public void paint(Graphics g)
{ g.drawString("Old McDonald", 25, 25); }
public void stop()
{ mcdClip.stop(); }
public void start()
/* A looping play (and a call to play()) always starts at
the beginning of the clip. */
{ mcdClip.loop(); }
} // end of McDonald classThe clip is loaded with getAudioClip() in init(), causing the applet to suspend until the download is completed. The sound is played repeatedly due to the loop() call in start(), continuing until the applet is removed from the browser (triggering a call to stop()). If the page is displayed again, start()'s call to loop() will play the music from the beginning.
An application employs AudioClips in just about the same way, except that the clip is loaded with newAudioClip() from the Applet class, as shown in the PlaySound
application (see Example 7-3).
Example 7-3. Using newAudioClip() from an applet
import java.applet.Applet; import java.applet.AudioClip; public class PlaySound { public PlaySound(String ...