Okay, so I am trying to create a shuffled playlist using 9 different sound instances, and a single script. The objective is to play each songs once, until they are all played, and then start over.
Currently, the only time music is played is when the first song is supposed to start. The first song is only played about 25% of the time. I have checked everywhere I can think of for answers, and no dice. My code is:
-- made by oCrxptic local length = 0 local songs = game.ReplicatedStorage.Songs:GetChildren() while true do wait(0.1) if #songs >= 1 then -- Music available to be played print("Playing") local index = math.random(1,#songs) songs[index]:Play() print("Playing: "..songs[index].Name) length = math.ceil(songs[index].TimeLength) table.remove(songs,index) wait(length) elseif #songs <= 0 then songs = game.ReplicatedStorage.Songs:GetChildren() print("Resetting songs...") else warn("Something went wrong with music.") end end
Line 12 always prints a new song name when it is supposed to, which is weird to me, because then I would think that the song should also be playing.
Any help is appreciated!
Honestly I don't know what is the issue but you can definitely clean this up a bit.
First don't hardcode wait the length of each song.
Sounds have a Ended
event which fires when the song ends. Think smarter, not harder. So use that.
Second, don't repeat yourself, you kept indexing for songs[index]
when you can just use a variable to reference the sound.
I also added a function that plays a song and waits for it to end.
local songs = game:GetService("ReplicatedStorage").Songs:GetChildren() local function play_song_and_wait(song) song:Play() song.Ended:Wait() end while true do play_song_and_wait(songs[1]) play_song_and_wait(songs[math.random(2, #songs)]) end
I start at 2 now since the first song is songs[1]
. Just so it doesn't potentially replay the same song twice in a row unless that is what you want.