Question on sound script


local sound1 = 482593735
local sound2 = 463568113
local music = script.Parent

function Song()
	local song = math.random(1,2)
	if song == 1 then
		 music.SoundId = "rbxassetid://"..sound1
	if song == 2 then 
		music.SoundId = "rbxassetid://"..sound2
	end
end 
end

while true do
		wait()
		Song()
		wait(1)
		music:Play()
		music.Ended: wait()
		end

I tried changing the line where it automatically picks a random song, so I could add my third song, from 2 to 3. Unfortunately , that didn’t work. I would appreciate any help, as for I am quite new to this. Thanks.

1 Like

“math.random” function’s first parameter is the starting value, and the second parameter is the ending value. If you need to decide between three things using math.random, you need to do “math.random(1, 3)”.

Also in your code, I see that you are using the “if” statement over and over again. Prefer to use “elseif” and “else” under the “if” for checking on the same thing instead of a lot of "if"s.

local sound1 = 482593735
local sound2 = 463568113
local sound2 = 000000000 --Change this
local music = script.Parent

function Song()
	local song = math.random(1, 3)
	if song == 1 then
		 music.SoundId = "rbxassetid://"..sound1
	elseif song == 2 then 
		music.SoundId = "rbxassetid://"..sound2
    else
        music.SoundId = "rbxassetid://"..sound3
	end
end

while wait() do
    Song()
    wait(1)
	music:Play()
	music.Ended:wait()
end

Although this code would work just fine, it would require a lot of useless coding for more songs. Once you learn tables, be sure to put all soundIds on a table and then pick the soundId from there randomly. That way, your code would look a lot simpler.

You also might wanna use a “repeat” loop while picking the random song to prevent the same song from playing over and over again.

Another quick correction, there are a few minor syntax/indentation errors in your code.

Number 1: If you look at line 13, there is an extra end. This end should not be there.

Number 2: The indentation on the final line (so the end) should be inline with where you create the function.

I’m not sure if these are copying errors, but your code should follow the indentation and syntax standards where possible.

Here is a version that uses tables that I mentioned in my reply:

local Songs = {482593735, 463568113} --Add more songs using commas
local Sound = script.Parent
local Prefix = "rbxassetid://" 
local Previous --We don't want the same track to play over and over again

while true do
    local RandomId
    repeat RandomId = Songs[math.random(1, #Songs)] until RandomId ~= Previous
    Previous = RandomId
    Sound.SoundId = Prefix .. RandomId
    Sound:Play()
    Sound.Ended:Wait()
end
3 Likes