识别Android中录制的声音中的主导频率

时间:2018-11-14 16:49:45

标签: java audio signal-processing fft pcm

我正在尝试转换位于的Python程序 https://github.com/rraval/pied-piper/blob/master/decode.py 到Android Java文件。

第一步是确定主导频率。我编写了以下Java程序来做到这一点

private class RecordAudio
        extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... paramVarArgs) {
        int audioSource = AudioSource.MIC;
        int sampleRateInHz = 44100;
        int channelConfig = AudioFormat.CHANNEL_IN_MONO;
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
        int bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
        byte Data[] = new byte[bufferSizeInBytes];

        AudioRecord audioRecorder = new AudioRecord(audioSource,
                sampleRateInHz,
                channelConfig,
                audioFormat,
                bufferSizeInBytes);
        audioRecorder.startRecording();

        boolean isRecording = true;
        while (isRecording) {
            audioRecorder.read(Data, 0, Data.length);
            fftPrint(Data, bufferSizeInBytes);
        }
        return null;
    }

    boolean fftPrint(byte[] waveArray, int bufferSizeInBytes) {
        double HANDSHAKE_START_HZ = 8192;
        double HANDSHAKE_END_HZ = 8192 + 512;
        int len = waveArray.length;
        double[] waveTransformReal = new double[len];
        double[] waveTransformImg = new double[len];

        for (int i = 0; i < len; i++) {
            waveTransformReal[i] = waveArray[i]; //copy of original
            waveTransformImg[i] = waveArray[i]; //FFT transformed below
        }

        RealDoubleFFT p = new RealDoubleFFT(bufferSizeInBytes);
        p.ft(waveTransformImg);

        //Calculating abs
        double[] abs = new double[len];
        for (int i = 0; i < len; i++) {
            abs[i] = (Math.sqrt(waveTransformReal[i] * waveTransformReal[i] + waveTransformImg[i] * waveTransformImg[i]));
        }

        //calculating maxIndex
        int maxIndex = 0;
        for (int i = 0; i < len; i++) {
            if (abs[i] > abs[maxIndex])
                maxIndex = i;
        }

        double dominantFrequency = (maxIndex * 44100) / len;
        if (dominantFrequency > 0) Log.d("Freq: ", String.format("%f", dominantFrequency));

        if (match(dominantFrequency, HANDSHAKE_START_HZ)) {
            Log.i("Handshake start:", "FOUND START");
        }
        if (match(dominantFrequency, HANDSHAKE_END_HZ)) {
            Log.i("Handshake end:", "FOUND END");
            return true;
        }
        return false;
    }

    boolean match(double freq1, double freq2) {
        return (Math.abs(freq1 - freq2) < 20);
    }

注意:RealDoubleFFT来自ca.uol.aig.fftpack

不确定我是否做对了。我正在Logcat中打印出频率,但是他们找不到正在播放的音频中存在的HANDSHAKE_START_HZ。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

请注意,FFT幅度峰值的频率分辨率取决于FFT的长度(以及窗口等)。该长度未在代码中指定或限制,因此您甚至不知道任何FFT结果bin是否有可能在目标频率的20 Hz之内。