I made a music script and I want it to the current song playing to pause when a player dies, and then resume when a player respawns. However, it pauses and then starts a new song when the player respawns. Some of it I used Chatgpt to make btw. Any help?
Here’s my local script:
local player = game.Players.LocalPlayer
-- RS handling
local rs = game:GetService("ReplicatedStorage")
local mscEvent = rs:WaitForChild("MusicEvent")
-- Gui Handling
local plrgui = player:WaitForChild("PlayerGui")
local MusicGui = plrgui:WaitForChild("MusicGui")
local MusicFrame = MusicGui:WaitForChild("MusicFrame")
local StopPlaybtn = MusicFrame:WaitForChild("StopPlayButton")
local mscName = MusicFrame:WaitForChild("MusicName")
local soundservice = game:GetService("SoundService")
local musicPlaylist = soundservice:WaitForChild("MusicPlaylist"):GetChildren()
local stop = false
local playingSong = nil
local lastSongTime = 0 -- To keep track of where the song left off
-- Function to toggle music play/pause
local function toggleMusic()
stop = not stop -- Toggle stop state
if stop and playingSong then
lastSongTime = playingSong.TimePosition
playingSong:Pause()
StopPlaybtn.Text = "Resume"
else
StopPlaybtn.Text = "Stop"
if playingSong then
playingSong.TimePosition = lastSongTime
playingSong:Play()
end
end
end
-- Toggle stop and play states on button click
StopPlaybtn.MouseButton1Click:Connect(toggleMusic)
-- Function to handle music playback
local function playMusic()
while true do
if #musicPlaylist > 0 then
if not stop then
playingSong = musicPlaylist[math.random(1, #musicPlaylist)]
playingSong.TimePosition = lastSongTime
playingSong:Play()
mscName.Text = "Now playing: " .. playingSong.Name -- Update GUI with current song name
playingSong.Ended:Wait()
lastSongTime = 0 -- Reset the time position after the song ends
else
-- Wait until the stop state is toggled back
repeat task.wait(0.1) until not stop
end
end
end
end
-- Function to handle player respawn
local function onCharacterAdded(character)
local humanoid = character:WaitForChild("Humanoid")
humanoid.Died:Connect(function()
print("paused")
if playingSong then
lastSongTime = playingSong.TimePosition
playingSong:Stop()
end
end)
-- Resume music on player respawn
humanoid.AncestryChanged:Connect(function(_, parent)
if not parent and playingSong then
playingSong.TimePosition = lastSongTime
playingSong:Resume()
end
end)
end
-- Connect character added and respawn handling
if player.Character then
onCharacterAdded(player.Character)
end
-- Start music playback loop
playMusic()
player.CharacterAdded:Connect(onCharacterAdded)