So i've done a script so it plays music from a table and I just don't know how to make it choose again from the table when it ends
local songs = {160442087,705243700} function playmusic() local sound = Instance.new("Sound", game:GetService("Workspace")) if sound then sound.SoundId = "rbxassetid://"..songs[math.random(1,#songs)] sound:Play() end end playmusic()
Firstly, let's use an infinite loop (while true do ... end
) to have the music system function indefinitely:
while true do -- ... end
Now, we'll pick and play a random song at the beginning of the statement body. Instead of using math.random
, we'll use the recommended Random
object; the algorithm provides more randomised numbers. According to some developers, math.random
has been updated to use this new algorithm anyway, but I cannot confirm this. We'll also refrain from using the second parent parameter of Instance.new
, as it is deprecated:
local songs = { 160442087, 705243700, } local sound -- Create a new Random. local random = Random.new() while true do -- Pick and play a random song. sound = Instance.new("Sound") sound.SoundId = "rbxassetid://" .. songs[random:NextInteger(1, #songs)] sound.Parent = workspace sound:Play() end
Lastly, let's use the Sound.Ended
event to wait until the song ends. Once it ends, we'll start again:
local songs = { 160442087, 705243700, } local sound -- Create a new Random. local random = Random.new() while true do -- Pick and play a random song. sound = Instance.new("Sound") sound.SoundId = "rbxassetid://" .. songs[random:NextInteger(1, #songs)] sound.Parent = workspace sound:Play() -- Yield until the sound ends. sound.Ended:Wait() end
I have a script but this changes your table. Try using this script:
local songs = {160442087,705243700} local sound = Instance.new("Sound", game:GetService("Workspace")) while true do if sound then sound.SoundId = "rbxassetid://"..songs[math.random(1,#songs)] sound:Play() wait(sound.Timelength) end end