Chapter 10, Audio
#77 Show Audio Information While Playing Sound
H A C K
Show Audio Information While Playing SoundHack #77
Providing visual feedback for JavaSound audio, or at least trying to….
You might want to play a clip without any corresponding visuals; for exam-
ple, if you were using it to signal the end of a long-running process such as
uploading a file. On the other hand, if the sound is the focus of the applica-
tion, as in a music-player application, you might need to show the user some
information about the audio he’s playing.
You already know how to play audio from a file or stream [Hack #76]; building
on that, you can create a simple GUI that shows some of the basic traits of
the audio, by pulling fields out of the
AudioFormat object, which can be
retrieved from the
Line once it has been created. These fields include the
audio format, bits/sample, frame size and rate, and endianness (which indi-
cates how two-byte values are to be interpreted: big-endian means the first
byte is more significant, and little-endian means the second is).
DataLine provides a getLevel( ) method that returns the
current level of the audio being played, as a float from
0.0 (silence) to 1.0
(maximum volume). You can use this to create a graphical level meter by
getting the level and coloring in that percentage of a component. For exam-
ple, if the level is
0.5, you’d fill in half of the component.
Drawing this level meter is pretty straightforward: create a
paint( ) method clears the Graphics, gets the line level, and fills a rectangle
(0,0) with a height equal to the component’s height and a width
equal to the level times the component’s width. Then you need to set up an
javax.swing.Timer is convenient because it avoids any
thread-safety issues while doing the painting—to repeatedly call
on the meter.
Figure 10-7. Playing a large AIFF file in JavaSound