在runnable中的Android if语句并不总是触发

时间:2016-12-20 20:12:58

标签: java android

我正在尝试写一个简单的小东西,当用户通过与手机通话“中断”它时,停止播放音频文件。我正在使用SoundMeter class that this person wrote来获取麦克风的maxAmplitude。我已将阈值设置为800,并希望不断地(每50毫秒)测试一次麦克风幅度的回归。

出于某种原因,当我出现“中断”以及音频停止时,它会被击中或错过。我希望中断显示振幅高于800的整个时间。

    handler = new Handler();
    final Runnable r = new Runnable() {
        @Override
        public void run() {
            mic_amplitude.setText(""+mSoundMeter.getAmplitude());
            if(mSoundMeter.getAmplitude() > threshold) {
                Log.d("INTERRUPT", "INTERRUPT");
                interrupt.setText("Interrupt");
                mBackgroundAudio.pause(mp);
                audioButton.setText("Resume Audio");
            } else {
                interrupt.setText("");
            }
            handler.postDelayed(this, 50);
        }
    };
    handler.postDelayed(r, 50);

在查看此内容时,我可以看到振幅稳定在40-50,而没有背景噪音,在静静地说话时峰值为1200-1500。我希望中断能够在800以上随时显示,但它目前只是间歇性地出现。

1 个答案:

答案 0 :(得分:0)

好的,我明白了。我通过记录放大器和中断来测试我的振幅是什么,我看到我得到了0.我意识到我一直在测试一个新的振幅(除了我正在显示的放大器),所以我将振幅分配给一个变量并在其他地方使用变量。

这是我的结果:

    handler = new Handler();
    final Runnable r = new Runnable() {
        @Override
        public void run() {
            mAmplitude = mSoundMeter.getAmplitude();
            mic_amplitude.setText(""+mAmplitude);
            if(mAmplitude > threshold) {
                Log.d("INTERRUPT", "INTERRUPT " + mAmplitude);
                interrupt.setText("Interrupt");
                mBackgroundAudio.pause(mp);
                audioButton.setText("Resume Audio");
            } else {
                interrupt.setText("");
            }
            handler.postDelayed(this, 100);
        }
    };
    handler.postDelayed(r, 100);