I'm trying to get the decibels from the microphone and have looked everywhere how to correctly do it but they don't seem to work.
I get the amplitude like this
public class SoundMeter {
static final private double EMA_FILTER = 0.6;
private MediaRecorder mRecorder = null;
private double mEMA = 0.0;
public void start() {
if (mRecorder == null) {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("/dev/null/");
try {
mRecorder.prepare();
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
mRecorder.start();
mEMA = 0.0;
}
}
public void stop() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
public double getTheAmplitude(){
if(mRecorder != null)
return (mRecorder.getMaxAmplitude());
else
return 1;
}
public double getAmplitude() {
if (mRecorder != null)
return (mRecorder.getMaxAmplitude()/2700.0);
else
return 0;
}
public double getAmplitudeEMA() {
double amp = getAmplitude();
mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
return mEMA;
}
}
Then In my other activity I call the getAmplitude method an it returns the amplitude.To convert it to decibels I use this:
dB = 20 * Math.log10(soundMeter.getAmplitude() / 32767);
Ive tried many different values in place for the 32767 but none of them seem to give me a realistic decibel answer. It's usually negative and sometimes -infinity. Please help if you know how to find decibels the right way.
getMaxAmplitude returns a number between 0 and 32767. To convert that to dB you need to first scale it to to a value between 0 and -1.
20*log10(1)==0
and20*log10(0)==-inf
.If you're getting -inf then this can only be because you're passing 0 to the log function. This is most likely because you are doing integer division. Change the denominator to a double to force a floating point division.