Picking a random music from ID

Of course, as by the title, I’m attempting to install a player for a game that sets up background music. For that, I’d like it to pick a random ID, but it seems not to work - what’s the current issue?

local ids = {601790165, 2800648159, 1125780619, 745290632}

local function music()
	local se = Instance.new("Sound")
	se.Name = "BackgroundMusic"
	se.Parent = game.Workspace
	se.Volume = .9
	repeat wait()
	local chosenid = ids[math.random(#ids, 1)]
	se.SoundId = chosenid
	until se.Ended:Wait()
end
music()

The error that I obtain is: ServerScriptService.Music:9: bad argument #2 (interval is empty)

math.random(1, #ids)
Would probably fix it.

You would simply do ids[math.random(#ids)], because math.random() returns a value between 1 and the first parameter, which is #ids in this case.

If you used a seconds parameter, then the second parameter needs to be lower than the first because the resulting random number would be returned as x, where n1 < x < n2 (n1 is the first parameter and n2 is the second). If n2 is less than n1, you can see that this is impossible.

1 Like