Reputation:
Hi i'm trying to read the data in a wav file so that i can plot it as a waveform. Following is the code that i have tried:
try {
RandomAccessFile file = new RandomAccessFile(myFile,"r");
while(file.read()>-1){
byte b1 = (byte) file.read();
byte b2 = (byte) file.read();
Log.d(TAG,"DATA:"+ (double) (b2 << 8 | b1 & 0xFF) / 32767.0);
}
file.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
My output is a value that ranges between -1 and +1 initially but later it gives only DATA:0 it seems like an infinite loop and there is a force close. According to me the loop should terminate when the end of file is reached. Can anyone pls suggest some terminating condition for the loop. Please Help.... Thanks is advance...
Upvotes: 3
Views: 2508
Reputation: 5083
This code snippet has the following issues:
1) Using file.read()>-1
in the while loop you still read bytes, so this code reads 3 bytes on every iteration.
2) WAV files may be (and very often are) RIFF containers with WAV blocks. Also, it is not guaranteed that values are encoded in integers (I've seen float encoding in WAV). Byte order seems to be ok, but containers' metainformation will be printed also.
I'm not an expert in Java, but running your expression with bytes (-1, -1) gives a value very close to 0.
To check for file termination, check if any of bytes are -1: while ((b1 != -1) && (b2 != -1))
Also, the conversion from int
to byte
seems to be wrong: byte is signed, so you'll get values from -128 to 127, which is not what you want (0..255).
Upvotes: 1