Audio cuts off after making a bunch of parts with the same audio

Okay, so, I have this thing that creates a part with an audio every time I use it. For the first couple of times, it works perfectly fine, but after about 4 or 5 times, all audio in the game just stops working.

preview of part of script:

local part = Instance.new("Part")
local sound = Instance.new("Sound")
part.Parent = game.Workspace
sound.Parent = part
sound.SoundId = "rbxassetid://7244661974"
sound.Volume = 5
sound:Play()
sound.Ended:Connect(function()
	part:Destroy()
end)

I’m not exactly sure what the problem is here or what I could have done to make the audio like this, so please give a little help.
(also, I’m putting the sound inside of the part so that it plays at a certain location)

Make sure the sound is loaded before playing it like this:

if not sound.IsLoaded then
    sound.Loaded:Wait()
end

Final code should look like this:

local part = Instance.new("Part")
local sound = Instance.new("Sound")
part.Parent = game.Workspace
sound.Parent = part
sound.SoundId = "rbxassetid://7244661974"
sound.Volume = 5

if not sound.IsLoaded then
    sound.Loaded:Wait()
end

sound:Play()
sound.Ended:Connect(function()
	part:Destroy()
end)

Or alternatively connect a callback to the .Loaded event and then play the song inside that.

local part = Instance.new("Part")
local sound = Instance.new("Sound")
part.Parent = game.Workspace
sound.Parent = part
sound.SoundId = "rbxassetid://7244661974"
sound.Volume = 5

sound.Loaded:Connect(function()
	sound:Play()
end)

sound.Ended:Connect(function()
	part:Destroy()
end)

Don’t give me the solution mark, this was just an alternative to the previous post.

1 Like