我正在尝试编写一个程序来识别我在钢琴上弹奏的音符,我发现 Goertzel 滤波器是一种易于实现的算法,但我不知道如何使用它。
这是代码:
using NAudio.Wave;
using System.Windows;
using System;
using System.Collections.Generic;
namespace WpfTest {
public partial class MainWindow : Window {
private BufferedWaveProvider buffer;
private WaveIn waveIn;
private WaveOut waveOut;
private const double TargetFreaquency = 261.626;//C4 note
private const int SampleRate = 44100;
public MainWindow() {
InitializeComponent();
InitializeSound();
waveIn.StartRecording();
waveOut.Play();
}
private void InitializeSound() {
waveIn = new WaveIn();
waveOut = new WaveOut();
buffer = new BufferedWaveProvider(waveIn.WaveFormat);
waveIn.DataAvailable += WaveInDataAvailable;
waveOut.Init(buffer);
}
private void WaveInDataAvailable(object sender, WaveInEventArgs e) {
buffer.AddSamples(e.Buffer, 0, e.BytesRecorded);
var floatBuffer = new List<float>();
for (int index = 0; index < e.BytesRecorded; index += 2) {
short sample = (short)((e.Buffer[index + 1] << 8) |
e.Buffer[index + 0]);
float sample32 = sample / 32768f;
floatBuffer.Add(sample32);
}
if (NotePlayed(floatBuffer.ToArray(), e.BytesRecorded)) {
Console.WriteLine("You have played C4");
}
}
private bool NotePlayed(float[] buffer, int end) {
double power = GoertzelFilter(buffer, TargetFreaquency, buffer.Length);
if (power > 500) return true;
return false;
}
private double GoertzelFilter(float[] samples, double targetFreaquency, int end) {
double sPrev = 0.0;
double sPrev2 = 0.0;
int i;
double normalizedfreq = targetFreaquency / SampleRate;
double coeff = 2 * Math.Cos(2 * Math.PI * normalizedfreq);
for (i = 0; i < end; i++) {
double s = samples[i] + coeff * sPrev - sPrev2;
sPrev2 = sPrev;
sPrev = s;
}
double power = sPrev2 * sPrev2 + sPrev * sPrev - coeff * sPrev * sPrev2;
return power;
}
}
}
代码无法正常工作,但我应该如何在控制台中写入:每次我向麦克风播放 C4 音符时,我应该怎么做?