- Home /
Inconsistent results with music and synchronization
Hello there,
I'm having some minor issue with my game. I have a screen that show the score in a coroutine when the level is over and a music is playing. The thing is I want the music to be synchronized with some sound effects and it should be quite easy as the tempo is 120 (2 beats per sec). But the problem is sometimes for a reason I don't really understand the sfx and the music are not synchronized. Here is the code:
IEnumerator WinLevel()
{
//many things before
PlayWinMusic();
missionComplete.gameObject.SetActive(true);
yield return new WaitForSeconds(2f);
missionComplete.gameObject.SetActive(false);
endLevelBoard.DisplayEndLevelBoard(Mathf.FloorToInt(timer), timerBonus, GameControl.livesCount, livesBonus, perfect, perfectBonus, total);
}
void PlayWinMusic()
{
MusicScript.instance.SetTrack(TrackType.Win);
MusicScript.instance.PlayMusic();
}
public void SetTrack(TrackType type)
{
switch(type)
{
case TrackType.Menu:
clip=Resources.Load("Menu") as AudioClip;
break;
case TrackType.Overview:
clip=Resources.Load("Overview") as AudioClip;
break;
case TrackType.InGame:
clip=Resources.Load("InGame") as AudioClip;
break;
case TrackType.Win:
clip=Resources.Load("Win") as AudioClip;
break;
}
}
public void PlayMusic()
{
if(!music.isPlaying)
{
music.clip=clip;
music.Play();
}
else
StartCoroutine(WaitForPlay());
}
IEnumerator WaitForPlay()
{
while(music.isPlaying)
{
yield return null;
}
music.clip=clip;
music.Play();
}
I won't post the endLevelBoard function because if the missionComplete image appear in the right moment then everything follow nicely. So the problem basically happens between PlayWinMusic(); and missionComplete.gameObject.SetActive(true);
By the way it is absolutely sure that music is not playing when I call PlayWinMusic() so it's not going in the while(music.isPlaying) loop and therefore not in the yield return null.
Answer by barbe63 · Aug 13, 2015 at 03:06 PM
I think it is solved now, I just forgot to put my music files on streaming instead of decompression on load. Silly me...
Answer by ripridehi · Aug 13, 2015 at 02:53 PM
I don't fully understand your scenario, but you do have to queue audio clips ahead of time in order to have exact synchronization. Check out AudioSource.PlayScheduled().
Also note there has been a bug with PlayScheduled() where it consumes and plays a chunk of samples right away, even though it should wait until the specified time: Why does AudioSource.PlayScheduled() play for an instant?
$$anonymous$$y clips are also co$$anonymous$$g with images so I don't think this could help me. Anyway as I said the problem of synchronization appears in the beginning of the music playing. But maybe I could use this for start the music more softly so it won't use time for buffers... I'll give that a try thanks!
$$anonymous$$any thanks sir! Your answer put me on the right way!