How would I make this random?

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

2 Likes

math.random or something like that

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)

1 Like

How and where would I interperet this? :smile:

1 Like
local RandomSound = sounds[math.random(1,#sounds)]

That should do.

Make sure you delete the songs from the table after they’re played, then when the table’s empty, re-introduce all the songs.

3 Likes

when playing the song and stuff

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.

1 Like

Where would I place

inside of

?

Ye. You could probably do math.random and use an array. I’m not a scripter though so I apologize.

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
1 Like

I recommend using local r = Random.new(), and r:NextInteger(min,max) instead of math.random. It doesn’t repeat the same numbers, if I’m correct.

1 Like

image
image

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
2 Likes

I fixed the code, it should work now.

1 Like

I would mark this as the soloution too if I could. Thanks everyone for the help!