I am using the Android AudioRecord
to get a continuous audio buffer. During theread
, I want to evaluate the highest decibel from the buffer.
Below is the configuration of AudioRecord:
sample rate = 16000; channels = 1; bits per sample = 16;
Reading the buffer in a byte array:
int bufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
// bufferSize is 1280 with sampleRateInHz = 16000, channelConfig = 16 and audioFormat = 2
int bytesRead;
byte[] fullBuffer = null;
byte[] auxBuffer = null;
byte[] buffer = new byte[bufferSize];
while(isRecording) {
bytesRead = recorder.read(buffer, 0, buffer.length);
if(fullBuffer == null) {
fullBuffer = new byte[buffer.length];
fullBuffer = buffer.clone();
}
else {
auxBuffer = fullBuffer.clone();
fullBuffer = new byte[buffer.length + fullBuffer.length];
System.arraycopy(auxBuffer, 0, fullBuffer, 0, auxBuffer.length);
System.arraycopy(buffer, 0, fullBuffer, auxBuffer.length, buffer.length);
}
}
Converting this byte array to a short array:
public static short[] convertByteArrayToShortArray(byte[] byteArray) {
short[] shortArray = new short[byteArray.length / 2];
for (int i = 0; i < byteArray.length; i += 2) {
short sample = (short) ((byteArray[i] << 8) | byteArray[i + 1]);
shortArray[i / 2] = sample;
}
return shortArray;
}
Getting the Max Amplitde from the short array:
short[] shortBuffer = convertByteArrayToShortArray(fullBuffer);
double maxAmplitude = Integer.MIN_VALUE;
for (int i = 0; i < shortBuffer.length; i++) {
short sample = shortBuffer[i];
double amplitude = Math.abs(sample);
if (amplitude > maxAmplitude) {
maxAmplitude = amplitude;
}
}
Calculating the decibel from the max amplitude:
double db = 20 * Math.log10(maxAmplitude / 32768);
The above is not returning realistic values for decibels. The deviation in value between total silence and loudness is none.
Below are some logs (note that the Buffer value is same for all logs):
Buffer [B@25df3e4
Buffer Length 1280
Full Buffer [B@152c381
Full Buffer Length 28160
Short Buffer [S@e94bc26
Short Buffer Length 14080
Max Amplitude 32768.0
Decibel 0.0Buffer [B@25df3e4
Buffer Length 1280
Full Buffer [B@48074b2
Full Buffer Length 33280
Short Buffer [S@1ec1c03
Short Buffer Length 16640
Max Amplitude 32768.0
Decibel 0.0Buffer [B@25df3e4
Buffer Length 1280
Full Buffer [B@5f30f62
Full Buffer Length 33280
Short Buffer [S@ef998f3
Short Buffer Length 16640
Max Amplitude 32768.0
Decibel 0.0Buffer [B@25df3e4
Buffer Length 1280
Full Buffer [B@e040029
Full Buffer Length 33280
Short Buffer [S@876bfae
Short Buffer Length 16640
Max Amplitude 32768.0
Decibel 0.0
Please suggest what's wrong here.