Soooo, I'm trying to write an Android app to measure sound level of environment.
I know that those kind of questions were asked many, many times and I've read many of them, but i'm still not sure, if my code is good.
private MediaRecorder mRecorder = null;
private TextView AmpCur, DbCur;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
//change text to actual amplitude
int Amp = mRecorder.getMaxAmplitude();
double db = 20 * Math.log10((double)Amp / 32767.0);
double db2 = 20 * Math.log10((double)Amp);
int db2I = (int) Math.round(db2);
Log.i("SoundMeasure", "amp=" + Amp + " db=" + db + " db2=" + db2);
AmpCur.setText(Integer.toString(Amp));
DbCur.setText(Integer.toString(db2I));
timerHandler.postDelayed(this, 250);
}
};
public void RecorderInit() {
String mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(mFileName);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e("SoundMeasure", "prepare() fail");
}
mRecorder.start();
timerHandler.postDelayed(timerRunnable, 250);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound_measure);
AmpCur = (TextView) findViewById(R.id.amp_cur);
DbCur = (TextView) findViewById(R.id.db_cur);
}
@Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
timerHandler.removeCallbacks(timerRunnable);
mRecorder.release();
mRecorder = null;
}
}
@Override
public void onResume() {
super.onResume();
if (mRecorder == null) {
RecorderInit();
}
}
App works, but the values are... a bit weird.
In very silent room, where other apps show ~15dB, I have
amp ~80 db ~-50 db2 ~40
When in blow into mic, other apps show 110+dB, and mine shows
amp 32767 db 0 db2 90
I've read that maxAmplitude can't get over 32767 and phones mics can't measure more than 90dB, but how other apps do that?