386
|
Chapter 10, Audio
#76 Play Non-Trivial Audio
HACK
This hack shows you how to do all of the sample conversion
and painting you need to display a waveform very simplisti-
cally. However, you should address a few key issues before
using this in an audio application; for example, this only
deals with 16-bit audio. You probably would want to build
something a little more generic to deal with other sample
sizes. You may also want to deal with compression, so you
can display waveforms for MP3 files. That said, this hack
still gives you a good idea of how to dig into raw audio data
and get your audio visualization on.
—Jonathan Simon
H A C K
#76
Play Non-Trivial Audio Hack #76
When loading an entire audio clip into memory is a bad idea (or just
impossible), you have to take JavaSound responsibilities into your own
hands.
Playing JavaSound audio with a Clip [Hack #71] is a pretty convenient way to
play a short sound, like a sound effect for a desktop application. The only
problem is that the
Clip loads all the audio into memory, which could have
a couple of bad side effects:
It makes your application use more memory, which could cause problems.
The audio you need might not fit into memory at all.
You might have run into this second point if you tried to load a really big
audio file into a
Clip. For example, I took a 3 minute, 45 second track from
a CD and converted it to 8-bit mono PCM in an AIFF file, which ended up
being 9.4 MB. You can guess what happened:
[aeris:HacksBook/Media/52] cadamson% java CoreJavaSound
javax.sound.sampled.LineUnavailableException: Failed to allocate clip data:
Requested buffer too large.
at com.sun.media.sound.MixerClip.implOpen(MixerClip.java:536)
at com.sun.media.sound.MixerClip.open(MixerClip.java:161)
at com.sun.media.sound.MixerClip.open(MixerClip.java:249)
at CoreJavaSound.<init>(CoreJavaSound.java:39)
at CoreJavaSound.main(CoreJavaSound.java:17)
Unfortunately, most of the JavaSound code you’ll find on the Web deals
with
Clips only and not with getting a Line for larger files, or potentially
endless streams for that matter. Why? Perhaps because JavaSound doesn’t
do it for you—you are responsible for reading bytes and feeding them to
JavaSound!

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.