如何临时暂停循环

时间:2018-03-22 10:01:00

标签: java android-studio

我正在制作一个始终检测噪音的APP。当它检测到巨大的噪音时,它会启动一个功能。

当功能发生时,我需要暂时暂停检测噪音的循环。

我该怎么做?

Hares我的代码:

private void readAudioBuffer() {

    try {
        short[] buffer = new short[bufferSize];
        int bufferReadResult;
        do {
            bufferReadResult = audio.read(buffer, 0, bufferSize);
            for (int i = 0; i < bufferReadResult; i++){
                if (buffer[i] > lastLevel) {
                    lastLevel = buffer[i];
                }
            }
            // if sound level is over 20000 start voice recognition
            if (lastLevel > 20000){
                lastLevel = 0;
            // Pause this function:
                startVoiceRecognitionActivity();
            }

        } while (bufferReadResult > 0 && audio.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:0)

基本上添加 了Thread.sleep(5000); 诀窍

    try {
        short[] buffer = new short[bufferSize];
        int bufferReadResult;
        do {


            bufferReadResult = audio.read(buffer, 0, bufferSize);
            for (int i = 0; i < bufferReadResult; i++){
                if (buffer[i] > lastLevel) {
                    lastLevel = buffer[i];
                }
            }
            // if sound level is over 20000 start voice recognition
            if (lastLevel > 20000){
                lastLevel = 0;
                startVoiceRecognitionActivity();
                Thread.sleep(5000);
            }

        } while (bufferReadResult > 0 && audio.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

答案 1 :(得分:-1)

private void readAudioBuffer() {

try {
    short[] buffer = new short[bufferSize];
    int bufferReadResult;
    do {
        while(audio.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING){
                //Wait for certain time. If it is in a recording state then it would enter this loop and wait else it would go ahead to check for sound levels.
           }
        bufferReadResult = audio.read(buffer, 0, bufferSize);
        for (int i = 0; i < bufferReadResult; i++){
            if (buffer[i] > lastLevel) {
                lastLevel = buffer[i];
            }
        }
        // if sound level is over 20000 start voice recognition
        if (lastLevel > 20000){
            lastLevel = 0;
            startVoiceRecognitionActivity();
        }

    } while (bufferReadResult > 0);

} catch (Exception e) {
    e.printStackTrace();
}
}