Play a Sound with JavaSound #71
Chapter 10, Audio
|
367
HACK
The example sets up a LineListener on the Clip and looks at the type of
received events for four values defined in the
LineEvent.Type class: OPEN,
CLOSE
,
START
, and
STOP
. All of these are logged to standard out, and then an
appropriate action is taken:
START
makes the dialog visible,
STOP
hides the
dialog and closes the clip (this is called when you OK the dialog), and
CLOSE
exits the application (and is called as a side effect of
clip.close( )
in the
handling of
STOP).
There are a lot more classes in the package, and you can write really confus-
ing code with them—and I haven’t even mentioned MIDI. But for the stated
goal of playing a small audio file with a minimum of fuss, that’s how you do
it with JavaSound.
Listen Up
When you run the demo program, it brings up a regular JFileChooser. You
need to pick a sound file from one of JavaSound’s supported file formats…
of which there are only three: WAV, AIFF, and AU (not MP3, WMA, or
Ogg). You knew there had to be a catch, right? Moreover, by default, Java-
Sound only plays uncompressed sound files, so if the data in the file is in
ALAW, ULAW, MACE, etc., it won’t play.
If JavaSound can read it, it will start playing the chosen file immediately.
The demo also shows a dialog like Figure 10-3, showing the name of the
chosen audio file.
Clicking the OK button clears the dialog and unblocks the AWT so that
when the clip finishes playing, the
STOP event can remove the dialog from the
screen and close the clip, which exits the demo.
Working with the
AudioSystem and having to pass around description
objects is a little strange, especially with JavaSound’s habit of using public
inner classes as descriptor objects, but thanks to the
Clip class, it does offer
a pretty reasonable way to play small audio clips from your program.
Figure 10-3. Dialog showing current sound file

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.