- Home /
Unable to play audio clips simultaneously from within a coroutine
I am using Unity 2017.3.1f1. I have created a co-routine for a car engine controller which would play a car start sound once, and while it is fading, it would start a looping sound that would gradually increase its volume while the start sound is still playing. Here is what I have written:
public virtual IEnumerator PlayEngineSounds()
{
float playtimeStarted = Time.unscaledTime, startSoundLength = startSound.clip.length;
startSound.Play();
if (loopSound == null)
{
yield return new WaitUntil(() => startSound.isPlaying);
}
else
{
while (startSound.isPlaying)
{
var percent = (Time.unscaledTime - playtimeStarted) / startSoundLength;
loopSound.volume = percent*_loopSoundMaxVolume;
Debug.Log("Loopsound % = " + percent, this);
yield return null;
}
loopSound.volume = _loopSoundMaxVolume;
yield return null;
}
}
Basically I am taking the percentage of the start sound and I use that for the level of the loop sound. The more completely the start sound is played, the louder the loop sound should get.
What I observe, is that my logged messages appear correctly in time, but the volume level of the loop sound is not affected. Then, when the start sound completes, the loop level gradually increases its volume. It behaves as if the volume updates are "delayed" and executed after the start sound is finished, instead of playing both simultaneously.
The startSound
and loopSound
are separate AudioSource
components, that reside in different game objects within the hierarchy of my vehicle. I am invoking the PlayEngineSounds
corouine from my Start
method like this:
internal void Start()
{
StartCoroutine(PlayEngineSounds());
// other code ...
}