java - 如何使用 Goertzel 算法检测频率

标签 java android frequency goertzel-algorithm

我真的很难弄明白这一点。本质上,我试图找出通过麦克风播放的频率。据我了解,我需要暴力破解 Goertzel 算法。所以基本上我只是使用 Goertzel 算法尝试每个频率,直到找到正确的频率。但是,我不明白我实际上是如何知道 Goertzel 算法何时找到正确算法的。有人可以帮助我吗。

主 Activity .java

import androidx.appcompat.app.AppCompatActivity;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Button recordButton;
    private TextView result;

    private AudioRecord recording;
    private static final int RECORDER_SAMPLERATE = 10000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
    double[] dbSample = new double[bufferSize];
    short[] sample = new short[bufferSize];
    private int frequency = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recordButton = findViewById(R.id.recordButton);
        result = findViewById(R.id.resultTextView);
        recordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recording = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, RECORDER_SAMPLERATE,
                                            RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSize);
                recording.startRecording();
                int bufferReadResult = recording.read(sample, 0, bufferSize);


                for (int j = 0; j < bufferSize && j < bufferReadResult; j++) {
                    dbSample[j] = (double) sample[j];
                    goertzel.processSample(dbSample[j]);
                }

                // Is this correct?
                magnitude = Math.sqrt(goertzel.getMagnitudeSquared());
                if(magnitude > maxMagnitude){
                    maxMagnitude = magnitude;
                    System.out.println("Freq is: " + Integer.toString(frequency));
                }
                goertzel.resetGoertzel();
                frequency += 1;
            }
        });

    }
}

Goertzel.java

public class Goertzel {
    private float samplingRate;
    private float targetFrequency;
    private long n;
    private double coeff, Q1, Q2;
    private double sine, cosine;

    public Goertzel(float samplingRate, float targetFrequency, long inN) {
        this.samplingRate = samplingRate;
        this.targetFrequency = targetFrequency;
        n = inN;
    }

    public void resetGoertzel() {
        Q1 = 0;
        Q2 = 0;
    }

    public void initGoertzel() {
        int k;
        float floatN;
        double omega;
        floatN = (float) n;
        k = (int) (0.5 + ((floatN * targetFrequency) / samplingRate));
        omega = (2.0 * Math.PI * k) / floatN;
        sine = Math.sin(omega);
        cosine = Math.cos(omega);
        coeff = 2.0 * cosine;
        resetGoertzel();
    }

    public void processSample(double sample) {
        double Q0;
        Q0 = coeff * Q1 - Q2 + sample;
        Q2 = Q1;
        Q1 = Q0;
    }

    public double[] getRealImag(double[] parts) {
        parts[0] = (Q1 - Q2 * cosine);
        parts[1] = (Q2 * sine);
        return parts;
    }

    public double getMagnitudeSquared() {
        return (Q1 * Q1 + Q2 * Q2 - Q1 * Q2 * coeff);
    }
}

最佳答案

您已经具体询问了暴力破解 Goertzel,所以这里有一个带注释的 JUnit 测试,说明了一种合理的方法:

public class TestGoertzel
{
    private float[] freqs;
    private Goertzel[] goertzels;
    private static final int RECORDER_SAMPLERATE = 10000;
    private static final int INPUT_SAMPLES = 256;   //Roughly 26 ms of audio. This small array size was
        //chosen b/c the number of frequency "bins" is typically related to the number of input samples,
        //for engineering applications. If we only check 256 samples of audio, our "DFT" need only include
        //128 output "bins". You can resize this to suit, but keep in mind that the processing time will
        //increase exponentially.

    @Test
    public void test()
    {
        freqs = new float[INPUT_SAMPLES / 2];   //To prevent frequency-domain aliasing, we cannot test for 256 frequencies; only the first 128.

        goertzels = new Goertzel[freqs.length];

        for(int n = 0; n < freqs.length; ++n)
        {
            freqs[n] = n * RECORDER_SAMPLERATE / INPUT_SAMPLES;     //Determine the frequency of a wave that can fit exactly n cycles in a block of audio INPUT_SAMPLES long.

            //Create a Goertzel for each frequency "bin":
            goertzels[n] = new Goertzel(RECORDER_SAMPLERATE, freqs[n], INPUT_SAMPLES);
            goertzels[n].initGoertzel();        //Might as well create them all at the beginning, then "reset" them as necessary.
        }

        //This gives you an idea of the quality of output that can be had for a real signal from your
        //microphone. The curve is not perfect, but shows the "smearing" characteristic of a wave
        //whose frequency does not fall neatly into a single "bin":
        testFrequency(1500.0f);

        //Uncomment this to see a full unit test:
        //for(float freq : freqs)
        //{
        //  testFrequency(freq);
        //}
    }

    private void testFrequency(float freqHz)
    {
        System.out.println(String.format("Testing input signal of frequency %5.1fHz", freqHz));
        short[] audio = generateAudioWave(freqHz, (short) 1000);

        short[] magnitudes = detectFrequencies(audio);

        for(int i = 0; i < magnitudes.length; ++i)
        {
            System.out.println(String.format("%5.1fHz: %d", freqs[i], magnitudes[i]));
        }
    }

    private short[] generateAudioWave(float freqHz, short peakAmp)
    {
        short[] ans = new short[INPUT_SAMPLES];

        float w0 = (float) ((2 * Math.PI) * freqHz / RECORDER_SAMPLERATE);

        for(int i = 0; i < ans.length; ++i)
        {
            ans[i] = (short) (Math.sin(w0 * i) * peakAmp);
        }

        return ans;
    }


    private short[] detectFrequencies(short[] audio)
    {
        short[] ans = new short[freqs.length];

        for(int i = 0; i < goertzels.length; ++i)
        {
            Goertzel goertzel = goertzels[i];
            goertzel.resetGoertzel();

            for(short s : audio)
            {
                goertzel.processSample((double) s);
            }

            ans[i] = (short) (Math.sqrt(goertzel.getMagnitudeSquared()) * 2 / INPUT_SAMPLES);
        }

        return ans;
    }
}

基本上,对于您读入的每 256 个音频样本,您都会获取该数组,并将其运行到涵盖您感兴趣的频率的 Goertzels 数组(每个 Goertzel 仅测量一个频率)。这给了你一个输出频谱。您可以根据自己的选择来解释该频谱;我把你的问题理解为“你如何找到输入音频中最响亮的分量的频率?”。在这种情况下,您将搜索 detectFrequencies() 的返回值以获得最大幅度。 freqs对应的成员就是你的答案。

事实是,您可能不想要 Goertzel,您想要一个 FFT ,由于 FFT 卓越的“计算效率”。由于 Goertzel 的速度稍慢(与 FFT 一样完整地覆盖频谱),您可能无法实时运行此答案。

顺便说一句,我认为在 Android 上不支持 10000 的采样率。

关于java - 如何使用 Goertzel 算法检测频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57216412/

相关文章:

java - 如何在应用程序中的 Activity 之间添加几秒钟的延迟?

java - 如何模拟Android GC杀死应用程序

java - Navigation Drawer关闭后如何执行操作,否则Android App会卡顿

java - 扩展 Eclipse JDT

java - 掷骰子程序

python - 计算列表中单词的频率并按频率排序

java - 使用Retrofit从json获取数据

android - XML 布局无法正确显示

math - 为空间域中的给定掩码在频域中找到等效的高斯滤波器掩码

python - 如何计算Python中列表成对比较的元素频率?