Why does my script about random music ID not work?

  1. What do you want to achieve? Make it so every time the music is ended, it is changed to a random ID and then re-starts playing with the new ID

  2. What is the issue? For some reason my script seems to make songs end prematurely and also nothing plays after one change of ID.

  3. What solutions have you tried so far? I tried putting the function in a loop like shown in the code but it did not work either.

Script in ServerScriptService

local ids = {"rbxassetid://1846009879","rbxassetid://1839906422","rbxassetid://1836289256","rbxassetid://1847223170"}
local music  = game:GetService("Workspace").Music

while true do 
	wait(4)
	music.Ended:Connect(function()
		print("song ended")
		music.SoundId = ids[math.random(1,#ids)]
		print("song changed")
		music:Play()
		print("new song played")
	end)
end
1 Like

You can connect multiple things to music.Ended, which is what is happening here due to being in a while true do loop. Every 4 seconds, it’ll create a new connection to music.Ended instead of checking if the music has ended. When the music does end, the code will fire again for every 4 seconds that has passed.

Instead, you should use music.Ended:Wait()

ex:

while true do
	wait(4)
	-- sometimes the music won't be playing
	-- this will occur when starting up or if a song stops before 4 seconds has passed.
	-- by checking if music is playing, it won't get stuck on waiting for it to end as it
	-- won't ever end if the music is not playing.
	if music.Playing then
		-- this will wait until the music has ended.
		music.Ended:Wait()
	end
	-- then select a random song and do music:Play()
end
1 Like