Android实时静音检测

时间:2017-04-11 06:42:42

标签: android audio real-time

我正在尝试从用户那里获取实时音频输入,并且每300毫秒我都会采用样本的平均值。我正在使用PCM 16位样本和44100采样率。 我正在从录音机读取数据到一个短阵列,我每300毫秒打印所有样本的平均值。 但是,问题是平均值似乎是随机的,即使存在沉默(也不应该是),它也显示出很大的值。 我想知道我是否以正确的方式使用短阵列。

public void startRecording() {
    recorder = new AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, SAMPLE_RATE,
            channels, AUDIO_FORMAT, Buffersize);

    recorder.startRecording();

    isRecording = true;
    NoiseSuppressor.create(recorder.getAudioSessionId());
    AcousticEchoCanceler.create(recorder.getAudioSessionId());
    AutomaticGainControl.create(recorder.getAudioSessionId());

    recordingThread = new Thread(new Runnable()

    {
        public void run() {
            writeAudioData();
        }

    });
    recordingThread.start();

}
private void writeAudioData() {

    short data[] = new short[Buffersize/2];

    while(isRecording) {

        samplesread =0;
        value = 0;
        long ftime = System.currentTimeMillis()+300;
        while (ftime > System.currentTimeMillis()) { // loop for taking average of 300 ms

            if(isRecording){
                samplesread += recorder.read(data, 0, Buffersize/2); // reads the data from the recorder and srores in the short array
                int i=0;
                while(i<Buffersize/2) {

                    //value += (long)(data[i]);
                    value += (long)(data[i] & 0xFFFF); // considering the PCM samples are signed I tried this


                    i++;

                }

            }
        }
        show = value;
        div = samplesread;

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                TextView tv = (TextView) findViewById(R.id.textView);
                tv.setText(""+(show/(div))+" "+div);
                TextView tv2 = (TextView) findViewById(R.id.textView2);
                tv2.setText(show+" "+ System.currentTimeMillis());

            }
        },0);

    }

}

1 个答案:

答案 0 :(得分:1)

数组值由带符号的数字组成,因此,在取平均值时未显示所需的结果。它在我使用RMS值而不是平均值时起作用。