Audio gets delayed from the second scene load. please help

I’m making a rhythm game. Because it’s test, when entering MainScene I scripted code to play the song one second later using coroutine and OnSceneLoaded function. And when the player dies, MenuScene is loaded. If I press the startbutton to load scene(1), the song is played delayed. No, actually it is played faster than first scene load.

I can figure out the difference between the first load and the second load so I can timing it directly after the second load, but I want a more fundamental solution.

As I tried everything to fixed this problem, I found some suspected parts.

  1. If I don’t use delay function, like coroutine or Invoke, this problem didn’t seem to appear.
  2. I used Debug.Log to check if time is delayed but the difference between OnSceneLoaded and PlayBgm functions at the first and second loads was the same.
  3. I tried LoadSceneAsync, but it didn’t work.
public class GameManager : MonoBehaviour
{
    WaitForSeconds wait = new WaitForSeconds(1f);
    
    void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode)
    {
        if (SceneManager.GetActiveScene().buildIndex == 1)
        {
            StartCoroutine(PlayBgm());
        }
    }

    IEnumerator PlayBgm()
    {
        yield return wait;
        SoundManager.Instance.PlayBgm(true);
    }

    void OnEnable()
    {
        SceneManager.sceneLoaded += OnSceneLoaded;
    }
}

This is some of the main codes related to the question I took out among my codes.
Do you have any solution?

hey guys I think I found a little weird solution. I played the bgm and stopped right away on the OnSceneLoad function. then I played the bgm a second later with coroutine as I wanted.

But I’m still curious about why first playing audiosource has a lag. I’d like to know exactly about this phenomenon because I’m so annoyed that I’ve wasted hours because of this simple dog-like error.

What loading policy are you using on the AudioClip? If it’s a big file and you’re using CompressedInMemory you might have a small lag due to the file decoding time. DecompressOnLoad should start the process as soon as the scene is loaded, which might help for this.

Besides that, the Wait and Coroutine might be the problem as you suggested. These function are sensitive when it relates to loading and frames, so for precise timings, I recommend you use Time.realtimeSinceStartup or AudioSettings.dspTime which are generally more robust clocks.

loading policy was already DecompressOnLoad. I think coroutine problem is right. thank you for replying

1 Like