Reputation: 23
I am trying to read a .wav file, convert it into double array and FFT the array.
I have the recorded .wav file in storage but I have no idea how I can read the file and use the data.
I am a beginner in application development so it would be nice if you could lead me through step by step as well as show some sample code.
Appreciate your help.
Upvotes: 2
Views: 1616
Reputation: 833
I can't give you a full code since it's a long solution and I have other things to do. I can give you hints.
First, check this link as reference.
As you see, a .wav or a WAVE file does not only contain the audio samples but it also contains other metadata that describes the contents of the file. To correctly read the audio samples, you'll need the values of these metadata.
To do this, first instantiate a FileInputstream
. You will need a File
object representing your .wav file to do that.
Next, you'll need to read each field from top to bottom. As you see from the illustration, the number of bytes for each field is indicated. Use the following code when reading a field.
byte[] bytes = new byte[numOfBytes];
fileInputStream.read(bytes, 0, bytes.length);
// The value of current field is now stored in the bytes array
After each read, the fileInputStream
will automatically point to the next field. Just repeat the above code until you have reached the start of the audio samples data.
To interpret the obtained values, you'll have to carefully read the description of each field.
To convert field from byte array to ASCII or String, use:
String value = new String(bytes);
To convert field from byte array to a number, use:
ByteBuffer buffer = ByteBuffer.allocate(numOfBytes);
buffer.order(BIG_ENDIAN); // Check the illustration. If it says little endian, use
// LITTLE_ENDIAN
buffer.put(bytes);
buffer.rewind();
If field consists of two bytes:
Short value = buffer.getShort();
If field consists of 4 bytes:
Int value = buffer.getInt();
To read the samples, just continue what you're doing above. But you'll also have to consider the number of bits per sample as given by the BitsPerSample
field. For 8 bits, read 1 byte. For 16 bits, read 2 bytes, and so on and so forth. Just repeat to get each sample until you reach the end of file.
To check the end of file, get the returned value from read and check if it is -1:
int read = fileInputSream.read(bytes, 0, bytes.length);
// If read equals -1 then end of file
Upvotes: 3