Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Audio Clicks/Pops from Filter Code

I'm creating a C# script for audio filters in the Unity engine.

My problem is that the after being run through my filter, the resulting audio has consistent and frequent "clicks", "pops", or "skips". It sounds a bit like an old radio.
I'm not sure what's causing this.

Here's my code:

public float cutoff;
public float resonance;

int sampleRate;

void Start()
{
    cutoff = 200;
    resonance = 1;

    sampleRate = AudioSettings.outputSampleRate;
}

void OnAudioFilterRead(float[] data, int channels)
{
    float c = 2 * Mathf.PI * cutoff/sampleRate;
    float r = 1 / resonance;

    float v0 = 0;
    float v1 = 0;

    for (int i = 0; i < data.Length; i++)
    {
        v0 =  (1 - r * c) * v0  -  (c) * v1  + (c) * data[i];
        v1 =  (1 - r * c) * v1  +  (c) * v0;

        data[i] = v1;
    }
}

Here is the documentation for OnAudioFilterRead().
Here is where I got the original low-pass code.

As the cutoff nears its maximum value (127), the clicks and pops become quieter.

I'm rather new to audio programming, as may be evident, so I'm not sure what would be causing it.
Could someone more knowledgeable than me explain what I'm doing wrong?

Thanks!

like image 631
chjolo Avatar asked Oct 20 '12 16:10

chjolo


1 Answers

Common causes of clicks and pops (in order of 'commonness') are:

  • wrong buffer length (you overlapped the buffer or failed to fill it to the boundary)
  • your sample are clipping, and you don't handle it like you should - for example you are calculating everything in shorts, and don't care about wrapping the values
  • your DSP algorithm is behaving badly
  • your algorithm is too slow for some reason, and audio sample isn't delivered in time, causing audio gaps

One good debugging technique for this is to try to narrow down the cause of the problem by, for example, inserting PCM dumping directly inside the routine that processes the audio. That way, you'll know if the output of your routine is OK or not, and be able to focus your debugging efforts accordingly.

like image 126
Daniel Mošmondor Avatar answered Sep 19 '22 05:09

Daniel Mošmondor