
380
|
Chapter 10, Audio
#75 Build an Audio Waveform Display
HACK
Frame
A frame is a cross section of samples across all channels in the audio file.
So, a 16-bit stereo (two channel) audio file will have 32-bit frames (16
bits per sample * 2 channels per frame = 32 bits per frame).
Load the Raw Data
Java reads raw audio data in 8-bit bytes, but most audio has a higher sam-
ple size. So, in order to represent the audio, you’ll have to combine multiple
bytes to create samples in the audio format. But first, you’ll need to load all
of the audio into a
buffer
before you combine the bytes into samples.
Start by getting an audio stream from a file:
File file = new File(filename);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new
BufferedInputStream (new FileInputStream (file)));
Now that you have the AudioInputStream, you can read in the audio data.
AudioInputStream has a read( ) method that takes an unpopulated byte[]
and reads in data the length of the byte[]. To read in the entire audio file in
one shot, create a
byte[] the length of the entire audio file. The complete
length of the file in bytes is:
total number of bytes = bytes per frame * total number of frames
You can get the number of frames for the whole file (frameLength) and the
size of the frame (
frameSize) from the AudioInputStream:
int frameLength = (int) audioInputStream.getFrameLength( );
int frameSize = (int) audioInputStream.getFormat().getFrameSize( ...