Anyone else have a mildy annoying popping/clicking happening when you call Stop() on your thrust sound?
I’m not sure if this is actually happening in unity or if it is more of a symptom of a cheap bluetooth headset
Is this a normal problem playing back audio and stopping it in Unity and if so is there a built in way of handling it or a better way than what I have hacked together below?
I set the volume to what I want it to be played back at when space is pressed and call Play().
If space is released and the audio is still playing then I call AudioFade() which lowers the volume by .1 until the volume gets to zero THEN I call Stop().
thrustVolume is a [serializefield] so the playback volume is still adjustable from within Unity.
Yes this is “normal” (or an expected bug). This is due to the drastic difference in amplitude between the sound wave at the time of stopping and then immediately after stopping (going to zero quickly is a sound).
Here’s another way to deal with it using Coroutines that I posted on the Udemy Q&A :
I didn’t write that code but found a modified version of it in Unity answers :
//Use StartCoroutine();
IEnumerator VolumeFade(AudioSource _AudioSource, float _EndVolume, float _FadeLength)
{
float _StartTime = Time.time;
while (!soundPlaying &&
Time.time < _StartTime + _FadeLength)
{
float alpha = (_StartTime + _FadeLength - Time.time) / _FadeLength;
// use the square here so that we fade faster and without popping
alpha = alpha * alpha;
_AudioSource.volume = alpha * startVolume + _EndVolume * (1.0f - alpha);
yield return null;
}
if (_EndVolume == 0) { _AudioSource.UnPause(); }
}
Instead of stopping the sound abruptly (which usually cause the audio to “click” or create phantom noise as the output waveform goes from something to nothing in an instant) it does a slow fade out by playing with the volume. We have to remember the start volume in the Start() function.
I could also fade in instead of unpausing directly, but didn’t find the starting of the wave to click as much for some reason.
(also the loop should be adjusted so that at the end of the audio loop and the beginning match otherwise same thing, it can create phantom noises).
Cool. Good stuff, thanks for sharing.
I was assuming this had something to do with stopping the waveform abruptly but was caught kind of by surprise as I assumed Unity would handle it more gracefully by default. Oh well, easily dealt with.
I’m usually territorial when I meet another Greg but you seem alright so I’ll let it slide