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)
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)