Search Unity

Audio Audio occasionally doesn't fade in/out properly

Discussion in 'Audio & Video' started by jak4694, Dec 17, 2019.

  1. jak4694

    jak4694

    Joined:
    Jan 24, 2019
    Posts:
    12
    Hello all,
    I'm currently trying to fade between sound clips using two audio sources and coroutines, but about 1% of the time the coroutine does not seem to run and leaves the music in its current state. Currently I am using a static AudioController class:
    Code (CSharp):
    1. public static class AudioController
    2. {
    3.     public static IEnumerator FadeOut(AudioSource audioSource, float FadeTime)
    4.     {
    5.         float startVolume = audioSource.volume;
    6.         while (audioSource.volume > 0)
    7.         {
    8.             audioSource.volume -= startVolume * Time.deltaTime / FadeTime;
    9.             yield return null;
    10.         }
    11.         audioSource.Stop();
    12.     }
    13.     public static IEnumerator FadeIn(AudioSource audioSource, float FadeTime)
    14.     {
    15.         audioSource.Play();
    16.         audioSource.volume = 0f;
    17.         while (audioSource.volume < 1)
    18.         {
    19.             audioSource.volume += Time.deltaTime / FadeTime;
    20.             yield return null;
    21.         }
    22.     }
    23. }
    and I am fading between them by calling the following code:
    Code (CSharp):
    1. StartCoroutine(AudioController.FadeIn(musicSource2, 0.12f));
    2. StartCoroutine(AudioController.FadeOut(musicSource, 0.12f));
    I've attempted to recreate the bug but it appears very infrequently and I cannot seem to find any pattern. Does anyone have any ideas why this might be occurring (or know of a better way to fade between audio sources)?