Client-side action before the player leave

So in my game, I want a small music to be played just before the player leave and also put his client in a strange state so he can still listen to the music until he join another game, maybe with a while true.

I tried with game.ChildRemoved, game.Players.PlayerRemoving, and game.Close to know if the client is leaving, all of them are working in Studio, but not in the normal Roblox client…

-- Musique haha.
game.Close:Connect(function()
	print("Yé.")
	script.MusiqueHaha.Playing = true
	local t = tick() + script.MusiqueHaha.TimeLength
	while tick() < t do end
end)

I need to know how to correctly detect when the client is leaving, how to make the client in the strange state described above, and if this is possible…

I don’t think you’d be able to do this. Instead have you considered doing this server sided?

When the game is closed, it’s closed, you can’t force a player to remain in your game if they end the task, it just doesn’t work like that. You could have them press on a fake X that does all that, but it won’t be the effect you’re looking for.

If I do it server-side, the client would have enough time to disconnect from the server, and I don’t want the other players on the server to listen to it while they are in the game.

You cannot use while true loops because roblox will automatically shut down the game after 30 seconds even if you use game.Close

But as a side not, do not use game.Close use game:BindToClose instead because game.Close is deprecated.

You can try with some admin scripts, they have a crash command, having the ability to crash a player (making them disconnect from the server and keep a local copy of the place, with the audio in it). This is also happening when the player get kicked from the server without any error message…
Your idea of a fake leave button was looking good but the players would think it’s an in-game feature instead of a leave game button.

I went looking at the documentation and BindToClose is only working server-side.

So you only want the player who left to hear the sound?

He wants to make a sound play after the user left. I have seen this in some horror games and it will continue to play the sound for a while after the game shutdown. Ive tried to lag myself to see if thats what it does but it only plays for a few seconds.

,PlayOnRemove

I already used that for all the tests and it didn’t work. Maybe the sound needs to be somewhere else ? It’s currently in the player.

It needs to be in the workspace

Ok, I tried, it’s still working in Studio but not in the Roblox client.

-- Musique haha.
local haha = script.MusiqueHaha
game.ChildRemoved:Connect(function()
	print("Yé.")
	haha.Playing = true
	local t = tick() + haha.TimeLength
	while tick() < t do end
end)
haha.Parent = workspace