簡體   English   中英

使用C#和NAudio檢測鋼琴音符

[英]Detecting piano note using C# with NAudio

我試圖編寫一個程序來識別我在鋼琴上彈奏的音符,但我發現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音符時,如何在控制台中寫“您已經彈過C4”?

您似乎在假設麥克風輸入將是44100Hz的16位PCM采樣。 不一定是這樣。 您可以檢查“默認”麥克風格式,並將其強制為您期望的格式,如下所示:

private void InitializeSound()
{
    waveIn = new WaveIn();

    // Add this here to see what the waveIn default format is.
    // Step through this line in the debugger.  If this isn't
    // 44100Hz sampling rate, 16-bit PCM, 1-channel, then that's
    // probably what's going wrong.
    WaveFormat checkformat = waveIn.WaveFormat;

    // Note that these are the default values if we used the 
    // parameterless WaveFormat constructor, but just expanding
    // here to show that we're forcing the input to what you're 
    // expecting:
    WaveFormat myformat = new WaveFormat(44100, 16, 2);
    waveIn.WaveFormat = myformat;
    SampleRate = myformat.SampleRate;

    waveIn.DataAvailable += WaveInDataAvailable;

    waveOut = new WaveOut();
    buffer = new BufferedWaveProvider(waveIn.WaveFormat);
    waveOut.Init(buffer);
}

我不確定在事件處理程序中將short轉換為float時的字節序(我已經老了,我不記得哪一端了:)),所以這可能也是一個問題。 您最好使用BitConverter.ToInt16來做到這一點,而不是現在進行的移位/添加:

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 = BitConvert.ToInt16(e.Buffer, index);
        float sample32 = (float)sample;
        sample32 /= (float)Int16.MaxValue;
        floatBuffer.Add(sample32);
    }

    if (NotePlayed(floatBuffer.ToArray(), e.BytesRecorded))
    {
        Console.WriteLine("You have played C4");
    }
}

看起來NotePlayedend參數還沒有使用,這實際上很好! e.BytesRecorded end參數的含義, e.BytesRecorded都不是正確的值,因為這不是樣本計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM