Music plays and overlaps?

So, I’m making a music script that plays after an event if fired from the client side. However, this script plays a song and then randomly in the middle of it, another song plays. Does anyone have any idea why??

Server Sided Script:

local button = script.Parent.Frame.MusicOn
local ss = game:GetService("SoundService")
local musicFolder = ss:WaitForChild("MusicFolder")
local music = musicFolder:GetChildren()

local rs = game:GetService("ReplicatedStorage")

local LoadedEvent = rs:WaitForChild("LoadedEvent")

local paused = false

local currentSong = nil

local nowplayingText = script.Parent.Frame.NowPlayingText


local function musicLoop()
	while true do
		local randomSong = music[math.random(1, #music)]
		currentSong = randomSong
		local name = currentSong.Name
		nowplayingText.Text = "Now Playing: "..name
		randomSong:Play()
		print(currentSong.Name)
		randomSong.Ended:Wait()
	end
end

local function buttonActivated()
	if paused then
		currentSong:Resume()
		button.Text = "Music: ON"
		nowplayingText.Text = "Now Playing: "..currentSong.Name
	else
		currentSong:Pause()
		nowplayingText.Text = "Now Playing: None"
		button.Text = "Music: OFF"
	end
	paused = not paused
end

LoadedEvent.OnServerEvent:Connect(function()
	task.defer(musicLoop) -- Wraps the musicLoop function in a coroutine, which stops it from yielding the thread
	button.MouseButton1Click:Connect(buttonActivated)
	
end)

I tried printing it, here’s what happened…
image

1 Like

bump the postjkaseoitjaroilgapogr

1 Like

instead of this try using

task.wait(randomSong.Length)

Also before you play the song make sure that the sound has been loaded

if not randomSong.IsLoaded then
randomSong.Loaded:Wait()
end
1 Like

Thanks for responding, however it still plays another song in the middle of it.
task.wait(randomSong.Length) gave me an error. I changed it to task.wait(randomSong.TimeLength)