我想创建一个 Android 应用程序,如果麦克风的幅度达到一定水平,我必须在其中使用react。
现在我正在使用此代码:
MediaRecorder soundRecorder = new MediaRecorder();
soundRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
soundRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
soundRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
soundRecorder.setOutputFile("/dev/null");
soundRecorder.prepare();
soundRecorder.start();
int amplitude = 0;
while (amplitude < MyApp.this.ampToReact) {
amplitude = soundRecorder.getMaxAmplitude();
}
但我知道这是非常糟糕的编程(并且我的应用程序不断崩溃)。
所以我想创建一个带有 onAmplitudeReachedDefiniteLevel()
方法的监听器来替换这个丑陋的 while 循环。
最佳答案
仅当存在某些代码来检测事件时,监听器才会工作。但据我所知,您需要手动执行此操作。相反,如果您重复采样超过阈值的内容,最好使用计时器进行轮询。
采样率是多少?
您需要的最低延迟是多少?
例如,在44100 kHz下,如果你想以1ms的精度使用react,那么你只需要每44个样本检查一次。
为什么不设置一个 timer/回调,每1毫秒调用一次?然后在你“ react ”之后取消计时器?
有几种方法可以做到这一点。这是其中之一,使用 android Handler
(未经测试 - 抱歉,如果需要调整!)
final int POLL_INTERVAL = 100; // milliseconds
Handler h = new Handler(); // this is where you feed in messages
OnClickListener startbuttonListener = new OnClickListener() {
// for example, if you want to start listening after a button press:
public void onClick(View v) {
h.postDelayed(poll, POLL_INTERVAL); // start running the poll loop
}
};
Runnable poll = new Runnable() {
public void run() {
if(soundRecorder.getMaxAmplitude() > MyApp.this.ampToReact){
h.postDelayed(soundTrigger, 0); // run your sound trigger if criterion met
}else h.postDelayed(this, POLL_INTERVAL); // post this Runnable (i.e. poll) again
}
}
Runnable soundTrigger = new Runnable() {
public void run(){
// TRIGGERED!
}
}
关于java - 创建自定义监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25835385/