I am working on a music system and need the songs to go in a random order, how would I do this?
Code (for the song changer):
while true do
for _, Song in ipairs(sounds:GetChildren()) do
mainSpeaker.SoundId = Song.SoundId
mainSpeaker:Play()
mainSpeaker.TimePosition = 0
Event:FireAllClients(Song:WaitForChild("Name").Value,Song:WaitForChild("Artist").Value)
mainSpeaker.Ended:Wait()
end
end
The math.random operator works quite well.
If you have a table of song names, then do math.random to pick a sign out, play it, then remove it from the list to a new list for repeat once all songs are played, then just do math.random(1,#tableofsongs)
Check above code for the solution. You essentially will remove the song that has just played out of one table and add it to another. Once all songs are played do the same thing in reverse and the # allows you to always only pick a random song out of the total possible number of songs in the current table you are looking through.
You can use math.random() to get a random number and use it to index a random song from the array:
while true do
songs = sounds:GetChildren()
local Song = songs[math.random(1,#songs)]
mainSpeaker.SoundId = Song.SoundId
mainSpeaker:Play()
mainSpeaker.TimePosition = 0
Event:FireAllClients(Song:WaitForChild("Name").Value,Song:WaitForChild("Artist").Value)
mainSpeaker.Ended:Wait()
end
This is an example of what you could do if you want the whole list to play randomly, without having to listen to the same music twice.
local function Shuffle()
local MusicArray = sounds:GetChildren()
for i = 1, #MusicArray do
local index = math.random(1, #MusicArray)
local Song = MusicArray[index]
mainSpeaker.SoundId = Song.SoundId
mainSpeaker:Play()
mainSpeaker.TimePosition = 0
Event:FireAllClients(Song:WaitForChild("Name").Value,Song:WaitForChild("Artist").Value)
mainSpeaker.Ended:Wait()
table.remove(MusicArray, index)
end
end
while wait() do
Shuffle()
end