我正在开发一个使用设备麦克风来获得振幅的项目。这是使用UI(主)线程中的单独线程完成的。线程更新全局变量( amp ),按下一个简单按钮后,输出Log,显示全局变量。
问题在于,10次中有9次输出为0.0,有时会达到预期的数字(100s或1000s),具体取决于捕获的声音,但这完全是随机的。我无法弄清楚到底发生了什么。
这是我的代码:
package com.example.mark.sound_test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
SoundMeter s = new SoundMeter();
Button listen;
double amp;
TextView textView;
public void updateAmp(double n) //updates global variable with input
{
amp = n;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listen = (Button) findViewById(R.id.listen);
textView = (TextView) findViewById(R.id.textView);
new Thread(new Runnable() { //new Thread which listens to amplitude
public void run()
{
s.start();
double tmp;
while(true) {
tmp = s.getAmplitude();
updateAmp(tmp); //update global variable with new amplitude
}
}
}).start();
listen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
Log.i("myapp","Amplitude:"+amp); //display amplitude on button click
}
});
}
}
这是我得到的输出(在嘈杂的环境中):
根据要求:
SoundMeter代码:
package com.example.mark.sound_test;
import android.media.MediaRecorder;
import java.io.IOException;
public class SoundMeter {
private MediaRecorder mRecorder = null;
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(IOException e) {
return;
}
mRecorder.start();
}
}
public void stop() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
public double getAmplitude() {
if (mRecorder != null)
return mRecorder.getMaxAmplitude();
else
return 0;
}
}