
390
|
Chapter 10, Audio
#76 Play Non-Trivial Audio
HACK
Notice in the constructor that, as with the Clip, the way to get an actual
Line object is to construct a DataLine.Info object and then pass that to
AudioSystem
. This time, you construct a
DataLine.Info
class with both the
SourceDataLine
class—you need this subclass of
Line
because it provides the
write( )
method with which you supply bytes to the
Line
—and an
AudioFormat
object describing the data you’ll be supplying. Assuming that
doesn’t throw a
LineUnavailableException (and it shouldn’t, because the
format is already known to be PCM, which JavaSound always supports),
you’ll have a line that you can open and start writing bytes to.
As mentioned previously, the key issue for the thread that reads bytes from
the file and writes them to the
Line is that it has to be aware of frame bound-
aries. In this code,
readPoint indicates the index of the buffer to start read-
ing bytes into. When you have an incomplete frame after reading from the
input stream, you copy the bytes from the incomplete frame to the front of
the buffer in preparation for the next read. For example, if you have a frame
size of 4, and
bytesRead % 4 equals 3, then you copy those 3 bytes to the front
of the buffer and set
readPoint to 3. The next read( ) will start at 3, and the
first byte read into the buffer will complete the frame from the previous
read( ).
Big Files, Big Sound
Since this is ...