Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

C# Discrete Time RLC Low/High Pass Filter Routines

5.00/5 (4 votes)
12 Nov 2013CPOL 18.3K  
Super-simplified routines to emulate real filters. Easy to implement or adjust to fit special needs.

Introduction

These are basic routines which take an audio stream with one or more channels and filter their contents approximating the response of a real RLC electronic filter.

Using the code

These are basic routines which take an audio stream, Input, with one or more channels and filter their contents approximating the response of a real RLC electronic filter. Input.Samples[Sample, Channel] contains double-type numbers describing the stream. Frequency is the filter's cutoff frequency in Hz. Q is the filter's quality factor as typically defined. Frequency and Q can be any number, but large Qs may cause the signal to explode as 'energy' may be stored faster than it is dissipated.

C#
static void LCLP(Audio Input, double Frequency, double Q)
{
    double O = 2.0 * Math.PI * Frequency / Input.SampleRate;
    double C = Q / O;
    double L = 1 / Q / O;
    for (int c = 0; c < Input.NumChannels; c++)
    {
        double V = 0, I = 0, T;
        for (int s = 0; s < Input.NumSamples; s++)
        {
            T = (I - V) / C;
            I += (Input.Samples[s, c] * O - V) / L;
            V += T;
            Input.Samples[s, c] = V / O;
        }
    }
}

static void LCHP(Audio Input, double Frequency, double Q)
{
    double O = 2.0 * Math.PI * Frequency / Input.SampleRate;
    double C = Q / O;
    double L = 1 / Q / O;
    for (int c = 0; c < Input.NumChannels; c++)
    {
        double V = 0, I = 0, T;
        for (int s = 0; s < Input.NumSamples; s++)
        {
            T = Input.Samples[s, c] * O - V;
            V += (I + T) / C;
            I += T / L;
            Input.Samples[s, c] -= V / O;
        }
    } 
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)