Chapter 10, Audio
#71 Play a Sound with JavaSound
Realistically, you actually need to host the applet (HTML and code) on a
web server and access it via a URL. If you have access to a web server, put
index.html and AppletAudio.class in their own web directory, along with
some known-to-work audio files, then access it remotely with a browser.
Type in a URL to one of those audio files by hand and try to load it. This
time, it should work (finally).
But what formats are supported? Back in Java 1.0 and 1.1,
AudioClips had to
be encoded in mono at 8,000 Hz with µ-law encoding…which was pretty
awful. In Java 1.4.2, a few simple container formats are supported. AIFF and
WAV both work, but Mac OS X doesn’t support the .au format, which used
to be the only option (Windows can play .au, by the way). Also,
can’t play WAVs and AIFFs whose contents are compressed in any way.
And neither Mac nor Windows supports MP3 as
You can also load audio from sites other than the one hosting your applet,
which seems contrary to the stringent applet security seen earlier.
java.awt.applet’s AudioClip means your application has to be an
applet, it can only run a handful of audio formats, and your media can’t be
local unless you go through the hassle of overriding the
As you might imagine, early Java developers demanded a replacement.
H A C K
Play a Sound with JavaSound Hack #71
Get a small clip to play from memory with a lot less hassle.
The JavaSound API was developed to answer complaints about the inade-
quacies of the
AudioClip class in the applet package…not the least of which
was the fact that it couldn’t be used in applications. JavaSound consists of
javax.sound.sampled and javax.sound.midi—plus two ser-
vice provider interface (
spi) sub-packages for adding support for new
devices, formats, converters, etc.
JavaSound was introduced as an extension to Java 1.2 (I know, I know,
“Java 2 Standard Edition, version 1.2”), and it became part of Core Java in
1.3. In other words, you’re pretty safe assuming that it’s present on your
user’s machine. That’s one big point in its favor.
Putting JavaSound to Work
To show off JavaSound, the code in Example 10-3 exhibits a short applica-
tion that allows the user to pick a file from the local filesystem and play it. A