Executing part of a script when a sound is heard

Hey guys!

So I am currently working on a game with echolocation as a main gameplay element.

Long story short, I have gotten a sort of expansive wave to spawn every time I click, however, I now want to make it so that it happens when it detects sounds (Ideally a clicking sound, like when you make a clicking sound with your tongue, this is not necessary, but would be nice). I am aware that I could use visualizers, however, i want it so that it is not a continuous tracking, but a pulse every 5 seconds or so.

Here is a video of something very similar to what I have right now.

Many thanks in advance!

Sounds like you want something similar to an envelope detector with fast attack and a long release.
Haven’t seen a c# example but here’s a quick and dirty one that’s untested.

Basically this looks at the root mean square for a window which computes how “loud” your data buffer is. Then use the loudness to bump up an exponentially decaying envelope value. If the decay value is closer to 1, the longer the wait is between clicks. Once your envelope value bumps up above the threshold, your Click function is called. I think you’ll have to call Click in a different way because you can’t call it from the audio thread though…

float currentEnvelopeValue = 0.0f;
float decay = 0.995f;
const float threshold = 0.5f;

void ProcessSamples(float[] data)
{
    float squareSum = 0.0f;
    foreach (float sample in data)
        squareSum += sample * sample;

    float rms = Mathf.Sqrt(squareSum / data.Length);

    float nextEnvelopeValue = Mathf.Max(currentEnvelopeValue, rms);
    if (nextEnvelopeValue >= threshold && currentEnvelopeValue < threshold)
    {
        Click();
        nextEnvelopeValue = 1.0f;
    }

    currentEnvelopeValue = decay * nextEnvelopeValue;
}

void Click()
{
    //..
}