Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to make the music play order random?

I need help making this music script play the music randomly. I don't mean at random times. I mean the order at which they play.

local MarketPlaceService = game:GetService("MarketplaceService")

local Songs = {
	2985440580,
	396040845,
	5015230842,
	160442087,
	705243700,
	609738703,
	4665733376,
	647252174,
	971730478
}

local SongObject = script.Parent.Song
local SongLabel = script.Parent.SongLabel
local MuteButton = script.Parent.MuteButton

MuteButton.MouseButton1Click:Connect(function()
	if SongObject.Volume == 0.5 then
		SongObject.Volume = 0
	else
		SongObject.Volume = 0.5
	end
end)

while true do
	for i = 1, #Songs do
		local Song = Songs[i]
		local SongInfo = MarketPlaceService:GetProductInfo(Song)
		SongObject.SoundId = "rbxassetid://"..Song
		SongObject:Play()

		SongLabel.Visible = true
		SongLabel.Text = SongInfo.Name

		wait(3)
		for i = 0, 1, 0.1 do
			wait(0.1)
			script.Parent.SongLabel.Transparency = i
		end
		print("Finished")

		repeat wait() until SongObject.IsPlaying == false
	end
end

2 answers

while true do
	local song = math.random(1,#Songs)
	local chosenSong = Songs[song]--this will give you a random id from the list
	--rest of the code
end

1 comment

0

I may have done this wrong but it isn't working I think I may have put it in the wrong place

There are a few things you can consider here, and the obvious pick is math.random().

  1. math.random(min, max) returns a number between min and max and should be used for randomization. If, for whatever reason, you are getting the same result over and over again, you can set a randomization seed to use by using math.randomseed(). The (semi) best seed to use is os.time().

  2. Make sure the sound is somewhere it can be heard. If it is in a storage (i.e. ReplicatedStorage), players will not hear it.

  3. You're not properly checking if the ID is valid:

local SongInfo = MarketPlaceService:GetProductInfo(Song)

If the ID is invalid your entire script will fail. I recommend that you use pcall() and check if the function does not error out:

local SongInfo -- Blank variable to use for retrieving info; if this is put within the function the rest of the script will not see it
local success, fail = pcall(function()
	SongInfo = MarketPlaceService:GetProductInfo(Song)
end)
if success then
	-- other code
end

Now, in order to use math.random() you need to use Songs[index]. The randomly generated number should not be assigned to a variable. It should be directly within index because you want a random song every time. (I'm aware that you're using a loop, but don't use a variable anyway.)

This discussion is preserved as it was. New answers, comments, and votes are closed.