Hello. Using answers from previous questions, I attempted to fix a script that plays a sound. It originally worked (If you press play on the gui, the sound would be placed into workspace where everyone would hear it). However, if you kept pressing play, more instances would be added into the workspace and the sound would get spammed. Here is a snippet of the old script

function PlaySound(id)
	if id == nil then print("Invalid sound") return end
	local sound = Instance.new("Sound")
	sound.SoundId = "http://www.roblox.com/asset?id=" .. tostring(id)
	UpdateQueueSize()
	sound.Parent = game.Workspace
	WaitForSoundToLoad()
	sound:Play()
end

The script above works but does not delete duplicate instances. Below is my attempt at fixing it. However, when I click play on the GUI no sounds play.

function PlaySound(id)
	if id == nil then print("Invalid sound") return end
    if game.Workspace.sound1 ~= nil then
        print("Already Exists")
else

	local sound1 = Instance.new("Sound")
	sound1.Name = sound1
	sound1.SoundId = "http://www.roblox.com/asset?id=" .. tostring(id)
	UpdateQueueSize()
	sound1.Parent = game.Workspace
	WaitForSoundToLoad()
	sound1:Play()
    end

end

Can anyone spot the problem and point me in the right direction? Thank you. P.S: Here's the full script in which the snippet came from. That is the only thing that was changed

local ContentProvider = game:GetService("ContentProvider")

local totalWait = 20

local queueSize = ContentProvider.RequestQueueSize

function UpdateQueueSize()
	queueSize = ContentProvider.RequestQueueSize
end

function WaitForSoundToLoad()
	local start = tick()
	while (ContentProvider.RequestQueueSize > queueSize) and ((tick() - start) < totalWait ) do
		wait(0.1)
	end
	if (start - tick() > 1) then print("Took " .. tostring(start - tick()) " seconds to load") end
end

function PlaySound(id)
	if id == nil then print("Invalid sound") return end
    if game.Workspace.sound1 ~= nil then
        print("Already Exists")
else

	local sound1 = Instance.new("Sound")
	sound1.Name = sound1
	sound1.SoundId = "http://www.roblox.com/asset?id=" .. tostring(id)
	UpdateQueueSize()
	sound1.Parent = game.Workspace
	WaitForSoundToLoad()
	sound1:Play()
    end

end

local TextBox = script.Parent:WaitForChild("TextBox")
local TextButton = script.Parent:WaitForChild("TextButton")

TextBox.FocusLost:connect(function(enterPressed)
	Game:GetService("ContentProvider"):Preload(TextBox.Text)
end)

TextButton.MouseButton1Click:connect(function()
	PlaySound(tonumber(TextBox.Text))
end)


2 comments

0

UpdateQueueSize() and WaitForSoundToLoad() are not ROBLOX functions, they may be created in the script by the original maker, otherwise they'll do nothing so try to remove them. I also can't see where your PlaySound function is activated/called

0

I willedit it and post the whole script so you can see what's outside the snippet