Search Unity

Question Correct way to keep looping audio sources in sync?

Discussion in 'Audio & Video' started by Iron-Warrior, Nov 6, 2020.

  1. Iron-Warrior

    Iron-Warrior

    Joined:
    Nov 3, 2009
    Posts:
    838
    I have a layered music system that I use for my game's main menu, where each instrument is played by a different audio source. When the user enters different menu screens, certain instruments have their volume set to 0 or 1. Currently, the audio sources all play in Awake() when the menu scene loads.

    Sometimes the various layers will desync and no longer play in harmony but...I don't know enough about Unity's audio system to know what would cause this and I'm having trouble reproducing the problem reliably. I'm guessing it's either
    1. The audio sources are not all initially being played in sync.
    2. When the clip reaches the end, the loop functionality is causing them to desync
    3. Unity's audio system retrieves the samples in a way that the sources can desync any time
    I'm thinking this should be a common problem, so I'm wondering: is there a correct way to keep audio sources synchronized? I've found AudioSource.PlayScheduled, but that would only solve the problem if point 1 above is the cause. Normally I'd just give it a shot, but because I'm having trouble reproing the issue I figured it would be better to learn more about this.

    Thanks for any help,
    Erik
     
  2. JLF

    JLF

    Joined:
    Feb 25, 2013
    Posts:
    140
    Hi, you're right that you need PlayScheduled to do this. It's most likely that the clips are being started at very slightly different times, even if they are triggered during the same frame.

    Whilst you usually wouldn't normally a difference in playback time if all the Audio Sources were triggered at the same time from the same Script, PlayScheduled works with the Audio System directly (i.e. it's not framerate dependent).

    Put simply, if you want to any kind of precise audio timing, like with a music system, PlayScheduled is absolutely what you need and it's what I've used in every music system I've built.

    If it helps, I wrote an in-depth guide on PlayScheduled on my blog here: https://gamedevbeginner.com/ultimate-guide-to-playscheduled-in-unity/

    Hope that helps,

    John.
     
    FuzzyOnion and Iron-Warrior like this.
  3. Iron-Warrior

    Iron-Warrior

    Joined:
    Nov 3, 2009
    Posts:
    838
    Awesome, thanks so much!