Method
The way I'd go about doing this, would be to create a function that creates a new table, with all the same keys and values to the original song list. You could just randomize the order of the initial song list, though if you plan to use it for anything else and the order matters, you're going to want to create a new table for it.
This is also a great opportunity to take advantage of the wait method you can call on events, to suspend the thread until being resumed again. We can use this method on the Ended event of the Sound object, and it's very well compact. I'll go over all of this in the explanation below.
Starting off
First, let's add the variables and create the function:
local Songs = {309109778,304029790,243372213,417500483,281929968}
local Speaker = workspace:WaitForChild("Sound")
local function PlayRandomSounds()
end
Next, we need to create a copy of the table (just like you did with your "Queue" table). This will allow us to select and remove random elements from the table, without effecting the original one:
local function PlayRandomSounds()
local Songs = {unpack(Songs)}
end
Now for choosing random songs, we're going to use a for loop to iterate the copy of the table we just made. As the loop is traversing through the table, it will select random elements along with removing them (to prevent selecting the same random song twice).
local function PlayRandomSounds()
local Songs = {unpack(Songs)}
for i = 1,#Songs do
local selected = table.remove(Songs,math.random(#Songs))
Speaker.SoundId = selected
Speaker:Play()
Speaker.Ended:wait()
end
end
So with that covering everything I talked about initially, and applying this example, the final result should look like this:
local Songs = {309109778,304029790,243372213,417500483,281929968}
local Speaker = workspace:WaitForChild("Sound")
local function PlayRandomSounds()
local Songs = {unpack(Songs)}
for i = 1,#Songs do
local selected = table.remove(Songs,math.random(#Songs))
Speaker.SoundId = selected
Speaker:Play()
Speaker.Ended:wait()
end
end
Hope this helped, if you have any questions, just let me know.
2 comments
the problem is that you can't get the timelength of the song on the serverside. use a songended event.
Perfect, thank you!