Search Unity

Question AudioSource.PlayScheduled causes problems in WebGL build

Discussion in 'Web' started by samboknight, May 10, 2023.

  1. samboknight

    samboknight

    Joined:
    Aug 31, 2019
    Posts:
    25
    I have a game that plays looping music using AudioSource.PlayScheduled. Browsers won't let HTML games play audio until the user clicks on the game window. When the user clicks outside the window, audio pauses until the user clicks in the window again. Unfortunately, AudioSource.PlayScheduled doesn't account for this pause, causing the scheduled clip to play early, which results in two copies of the music track playing over each other until the first audio source reaches the end of the clip. Then, after end of the second clip, there is a long gap of silence.

    Is there some way for me to 1) detect when the game loses focus and 2) account for the audio pause so the scheduled playback stays in sync?

    In case it helps, I have included my music player code.

    Unity version is 2021.3.14.
     

    Attached Files:

    Last edited: Jun 19, 2023
  2. samboknight

    samboknight

    Joined:
    Aug 31, 2019
    Posts:
    25
    Added additional information.
     
  3. Unifikation

    Unifikation

    Joined:
    Jan 4, 2023
    Posts:
    1,087
    I don't think so. You can set an AudioSource to loop, though. Which would negate the need to use PlayScheduled.

    Does that help?
     
  4. samboknight

    samboknight

    Joined:
    Aug 31, 2019
    Posts:
    25
    I am aware of the AudioSource loop feature. Unfortunately, it isn't really an option for my use case.

    One level in my game has a music track that dynamically changes its loop points depending on the player's progression through the level. This necessitates using two AudioSources that "take turns." One of them plays the AudioClip for the current part of the music, while the other one waits for the end of the current clip to play the next one.