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!
I’ve solved it. My c and r variables needed to persist throughout calls to OnAudioFilterRead(). Making them members fixed it. Here is my complete, working code: