Shuffling music in Godot?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By fader

Perhaps what I am asking is more of a logic issue than specifically a Godot one, but I am not sure whether Godot has some useful built in functions to help this.

Essentially what I need to do is shuffle the music for a game and prevent tracks from repeating before other tracks have played. I can figure out how to randomize the music choices but I don’t know the best way to make sure the same track isn’t played back-to-back. I also need to be sure that whatever solution I use to do this won’t completely prevent the track from playing again, say a few tracks later.

Thanks in advance. Love how helpful and welcoming this community is to noobs like myself!

:bust_in_silhouette: Reply From: jgodfrey

If you really just want to ensure that a track doesn’t play twice in a row (or similar), you could just remember the last track (or two, or ??) and use that to assist in the next track’s selection. So, randomly select a track. If that track is the one you just played, select again. In pseudo-code, something like:

var newTrack = randomlySelectTrack()
while newTrack == prevTrack:
    newTrack = randomlySelectTrack()
prevTrack = newTrack
return newTrack

You could remember a number of previously selected tracks depending on your needs. Really though, you just want to “select again” if the track was recently played. If you need to skip some number of times before a replay becomes possible, you could manage the previously played tracks in another array. But, again, if the newly selected track “has been played recenlty” (is in the previously played array), just select again until a valid track is found.

Alternatively, if you want to play every track before one repeats, I’d suggest that as you play a track, you physically remove it from the array of available tracks. That way, you only have “non-played” tracks to choose from on each selection. Once the last track is selected and removed, you’d then restore the original array and start again.

This solution works perfectly, thanks. So simple, too, I must have been overthinking!

fader | 2020-03-31 05:00