Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Audio switching cause "lag spike?"

Discussion in 'Audio & Video' started by DK_Kalach, Sep 28, 2023.

  1. DK_Kalach

    DK_Kalach

    Joined:
    Sep 2, 2021
    Posts:
    13
    I want to switch from normal music to looped music at a certain point, The Problem is that it cause a "lag spike" or something, Would like to know why it happens and how to fix it, Thanks

    Code (CSharp):
    1.     public IEnumerator ChangeMusicToLooped(AudioClip Start_Clip, AudioClip Looped_clip, float time)
    2.     {
    3.         PlayMusic(Start_Clip);
    4.         yield return new WaitForSeconds(time);
    5.         PlayMusic(Looped_clip);
    6.     }
    Code (CSharp):
    1. StartCoroutine(audioManager.ChangeMusicToLooped(audioManager.Boss_Start, audioManager.Boss_Looped, 15.7f));
     
  2. SeventhString

    SeventhString

    Unity Technologies

    Joined:
    Jan 12, 2023
    Posts:
    290
    There are (at least) two things to consider to do this kind of transition.
    1. For "sample perfect" audio jumps, I recommend you use the WAV format, maybe OGG (MP3 encoding won't give you a clean looping effect
    2. You should consider using `AudioSettings.dspTime` and `AudioSource.PlayScheduled`
    This should allow you to avoid clicks or short silences between the two AudioClips you're using.
     
    DK_Kalach likes this.