1. Confusion on byte declaration
I have successfully read raw data from the microphone using AudioRecord class in Android. In my code, the raw data is saved as: byte data[] = new byte[bufferSize];
Here bufferSize is a constant number (I guess) 7680. My first question is: what's the difference between
byte data[] = new byte[bufferSize]; and byte[] data = new byte[bufferSize];? My code seems to be not different in both cases.
2. byte to float
My next step is to do some calculation with the raw data. For better precision, I want to convert byte type data to float. Here's the code:
private void writeAudioDataToFile() {
byte data[] = new byte[bufferSize];
String filename = getTempFilename();
FileOutputStream os = null;
try {
os = new FileOutputStream(filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int read = 0;
if(null != os) {
while(isRecording) {
// First print: raw data from microphone
Log.v("print1", "data");
read = recorder.read(data, 0, bufferSize);
System.out.println(Arrays.toString(data));
// Second print: byte[] to float[]
Log.v("print2", "buff");
float[] inBufferMain = new float[bufferSize];
for (int i = 0; i < bufferSize; i++) {
inBufferMain[i] = (float) data[i];
}
System.out.println(Arrays.toString(inBufferMain));
// Calculating inBufferMain here
// ...
// Third print: float[] to byte[]
Log.v("print3", "data");
for (int i = 0; i < bufferSize; i++) {
data[i] = (byte) inBufferMain[i];
}
System.out.println(Arrays.toString(data));
if(AudioRecord.ERROR_INVALID_OPERATION != read) {
try {
os.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the code above, after reading data from the microphone, I print it in logcat. The results are around 1000 integer numbers. Why 1000? Because the buffer read 7680 bits in all and saved as byte, that is 7680 / 8 ≈ 1000. Please correct me if my analysis is wrong. But after byte-to-float conversion, the results are only around 600 float numbers. The first 600 value in the float array is same as the one in the byte array, but the remaining numbers are missing. Is there anything wrong with my method of printing?
3. float to byte
Assumed that I've processed the float array and now is time for float-to-byte conversion. But the results of the third print are all 0. How to convert float[] to byte[]?
Thanks