
Play a Sound in an Applet #70
Chapter 10, Audio
|
359
HACK
H A C K
#70
Play a Sound in an Applet
Hack #70
If you’re forced to write to the old Applet API for sound, here’s how you do it.
Good luck.
Let me be very clear up front: applet-based sound sucks. If you are in a
hurry to get sound into your application and can count on your users hav-
ing Java 1.3 or better, go ahead and use JavaSound instead
[Hack #71]. Applet-
based sound is going to be most useful to those who must deliver applets
(and only applets) to very old browsers and JVMs. And it’s not going to be
pretty.
Java 1.0 and 1.1 shipped with no support for application-based sound.
None. The only sound support was for applets, presumably so they could
punt the responsibilities for audio to the enclosing browser. The idea in the
early JDKs is built around an
AudioClip, a class found in the java.awt.
applet
package—as David Flanagan says in Java Foundation Classes in a
Nutshell (O’Reilly), “only because there is no better place for it.”
The Code
To demonstrate AudioClips, Example 10-1 shows a hacked up little applet.
Example 10-1. Playing an AudioClip in an applet
public class AppletSound extends Applet
implements ActionListener {
JButton fileButton, loadButton, playButton, loopButton, stopButton;
JLabel urlLabel;
JTextField urlField;
AudioClip clip;
public AppletSound( ) {
setLayout (new GridLayout (2,1));
// first row layout
JPanel topPanel = new ...