我使用公式计算分贝double dB = 20 * Math.log10(p/p0);
p = recorder.getMaxAmplitude()/51805.5336;
p0 = 0.0002;
但是这个类所做的是表示声音幅度在 40 到 70 之间的范围内,它很容易达到 70(最大值),只需在设备上敲击我的手指。
final Runnable updater = new Runnable(){
public void run(){
updateTv();
};
};
final Handler mHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.textView1);
tv.setText("Start");
startRecording();
if (runner == null)
{
runner = new Thread(){
public void run()
{
while (runner != null)
{
try
{
Thread.sleep(500);
Log.i("Noise", "Tock");
} catch (InterruptedException e) { };
mHandler.post(updater);
}
}
};
runner.start();
Log.d("Noise", "start runner()");
}
}
public void onResume()
{
super.onResume();
}
protected void updateTv() {
double decibel = Math.rint(100*getAmplitudeEMA())/100;
tv.setText("" + decibel + " dB");
AppLog.logString(Double.toString((getAmplitudeEMA())) + " dB");
}
private double getAmplitudeEMA() {
double p = getAmplitude()/51805.5336;
double p0 = 0.0002;
//mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
double mEMA2 = 20 * Math.log10(p/p0);
Log.i("MY", "" + recorder.getMaxAmplitude());
return mEMA2;
}
private double getAmplitude() {
if(recorder != null){
return recorder.getMaxAmplitude(); }
else
return 0;
}
private String getFilename(){
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,AUDIO_RECORDER_FOLDER);
AppLog.logString(filepath);
if(!file.exists()){
file.mkdirs();
}
AppLog.logString(file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
}
private void startRecording(){
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}