C#低通滤波器的以下代码如何运行?

时间:2015-04-01 17:21:25

标签: c# audio naudio lowpass-filter

我在NAudio网站上找到了以下用于低通过滤器的C#代码:

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

        filter_LowPass();
    }

    private void filter_LowPass()
    {
        channels = sourceProvider.WaveFormat.Channels;
        filters = new BiQuadFilter[channels];

        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;
    }

我的读函数在哪里被调用?

为什么需要它?

我用这种方式调用函数filter_LowPass:

        myFilter.setValues(audioFileReader, currentCutOff);

        waveOut.Init(myFilter);

如果我希望在将每个样本传递给低通滤波器后将其与常量值相乘,我在哪里编写代码?

1 个答案:

答案 0 :(得分:2)

NAudio在这里使用拉模型。声卡将要求waveOut进行采样,因此它将调用myFilter.Read()的上游,然后调用audioFileReader.Read()

如果你想增加一些额外的增益,你可以按照相同的模式创建一个新的ISampleProvider,或者将其内联到低通滤波器的读取功能中:

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] = gain * filters[(i % channels)].Transform(buffer[offset + i]);
        //                   ^^^^

    return samplesRead;
}