如何使用NAudio的BiQuadFilter?

时间:2017-11-09 22:00:24

标签: c# filter naudio

我使用NAudio录制麦克风的声音并将其保存在文件中。我用它:

    public WaveFileWriter m_WaveFile = null;

    m_WaveFile = new WaveFileWriter(strFile, m_WaveSource.WaveFormat);  


    void DataAvailable(object sender, WaveInEventArgs e)
    {
        if (m_WaveFile != null)
        {
            m_WaveFile.Write(e.Buffer, 0, e.BytesRecorded);
        }
    }

现在我想对录制的声音应用highpassfilter和lowpassfilter。到目前为止,我发现BiQuadFilters会为我做这个,但到目前为止,我不明白如何使用它。

我发现的例子看起来都像这样:

    var r = BiQuadFilter.LowPassFilter(44100, 1500, 1);
    var reader = new WaveFileReader(File.OpenRead(strFile));
    var filter = new MyWaveProvider(reader, r); // reader is the source for filter
    var waveOut = new WaveOut();
    waveOut.Init(filter); // filter is the source for waveOut
    waveOut.Play();

如果我理解正确,那么Filter将应用于播放声音的类。但是我不想播放声音,我希望将高和日志传递过滤器应用于文件并将结果保存在文件中。我怎么能这样做?

编辑: 这是MyWaveProvider类:

class MyWaveProvider : ISampleProvider
{
    private ISampleProvider sourceProvider;
    private float cutOffFreq;
    private int channels;
    private BiQuadFilter[] filters;

    public MyWaveProvider (ISampleProvider sourceProvider, int cutOffFreq)
    {
        this.sourceProvider = sourceProvider;
        this.cutOffFreq = cutOffFreq;

        channels = sourceProvider.WaveFormat.Channels;
        filters = new BiQuadFilter[channels];
        CreateFilters();
    }

    private void CreateFilters()
    {
        for (int n = 0; n < channels; n++)
            if (filters[n] == null)
                filters[n] = BiQuadFilter.LowPassFilter(44100, cutOffFreq, 1);
            else
                filters[n].SetLowPassFilter(44100, cutOffFreq, 1);
    }

    public WaveFormat WaveFormat { get { return sourceProvider.WaveFormat; } }

    public int Read(float[] buffer, int offset, int count)
    {
        int samplesRead = sourceProvider.Read(buffer, offset, count);

        for (int i = 0; i < samplesRead; i++)
            buffer[offset + i] = filters[(i % channels)].Transform(buffer[offset + i]);

        return samplesRead;
    }
}

2 个答案:

答案 0 :(得分:0)

以下代码应该满足您的要求:

using (var reader = new WaveFileReader(File.OpenRead(strFile)))
{
    var r = BiQuadFilter.LowPassFilter(44100, 1500, 1);

    // reader is the source for filter
    using (var filter =  new MyWaveProvider(reader, r))
    {
        WaveFileWriter.CreateWaveFile("filteroutput.wav", filter);
    } 
}

答案 1 :(得分:0)

有一个使用BiQuadFilter在NAudio WPF演示代码中制作多频段均衡器的示例。您可以看到Equalizer代码here