Pause Music When WindowFocusReleased And Vice Versa

I’m trying to create a system which pauses all sounds in game when the window loses focus (Switching to other tab) and resume all sounds in game when the window focuses.

I tried to create the system but it didn’t work.

This is my script:

local UIS = game.UserInputService

UIS.WindowFocusReleased:Connect(function()
	for i, things in game:GetChildren() do
		if things:IsA("Sound") or things:IsA("SoundGroup") then
			things:SetAttribute("OriginalVolume", things.Volume)
			things.Volume = 0
			
			if things:IsA("Sound") then
				if things.IsPlaying then
					things:SetAttribute("WasPlaying", true)
					things:Pause()
				end
			elseif things:IsA("SoundGroup") then
				things.Volume = 0
			end
		end
	end
end)

UIS.WindowFocused:Connect(function()
	for i, things in game:GetChildren() do
		if things:IsA("Sound") or things:IsA("SoundGroup") then
			local OriginalVolume = things:GetAttribute("OriginalVolume")
			things.Volume = OriginalVolume
			
			if things:IsA("Sound") then
				if things:GetAttribute("WasPlaying") then
					things:Resume()
				end
			elseif things:IsA("SoundGroup") then
				things.Volume = OriginalVolume
			end
		end
	end
end)	

Can somebody help me to create this system?

Thank you,
XMLcard

its because you are using :GetChildren() wich are only services so I recommend :GetDescendants():

local UIS = game.UserInputService

UIS.WindowFocusReleased:Connect(function()
	for i, things in game:GetDescendants() do
		if things:IsA("Sound") or things:IsA("SoundGroup") then
			things:SetAttribute("OriginalVolume", things.Volume)
			things.Volume = 0
			
			if things:IsA("Sound") then
				if things.IsPlaying then
					things:SetAttribute("WasPlaying", true)
					things:Pause()
				end
			elseif things:IsA("SoundGroup") then
				things.Volume = 0
			end
		end
	end
end)

UIS.WindowFocused:Connect(function()
	for i, things in game:GetDescendants() do
		if things:IsA("Sound") or things:IsA("SoundGroup") then
			local OriginalVolume = things:GetAttribute("OriginalVolume")
			things.Volume = OriginalVolume
			
			if things:IsA("Sound") then
				if things:GetAttribute("WasPlaying") then
					things:Resume()
				end
			elseif things:IsA("SoundGroup") then
				things.Volume = OriginalVolume
			end
		end
	end
end)
2 Likes

Thank you for helping me you guys

1 Like

no problem, good luck with scripting

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.