I’m working on a project that is going to have dynamic music. I have all my music clips in an array, and I switch to another clip whenever I want the music to vary.
Right now, I just play one clip, and in the update loop, I check if the audio is playing. If audio.isPlaying is false, I tell it to play the next clip. However, this makes a small gap in the audio that isn’t present if I simply “loop” one clip. This is distracting and stifles the energy of the song.
We solved this issue by writing a cross-fading script.
Think of it as a DJ cross-fades two songs together - he lowers the volume of the currently playing song while raising the volume of the 2nd song.
I played around with this issue too and after trying all kinds of things the best result I got was using FixedUpdate. I realized that the gap occurred because Update is called only once per frame and that meant the new track loaded at the beginning of the new frame. So until the new frame loaded there was a slight but noticeable gap. FixedUpdate is called multiple times per frame, not always, but most of the times. This code might help:
var bgMusicArray : AudioSource[]; //Add audiosources in the inspector
private var bgMusic : AudioSource;
var playNext : boolean = false;
function FixedUpdate()
{
if(!bgMusic.isPlaying)
{
playNext = true;
}
if(playNext)
ChangeMusic(2);
}
function ChangeMusic(musicNumber : int)
{
if(playNext)
{
playNext = false;
bgMusic = bgMusicArray[musicNumber];
bgMusic.Play();
}
}
The result is not completely satisfactory, I will keep working on this but for now it suffices.