Destroying sound after it is finished playing

So i’ve got this music script that randomly selects a song from the table given however i have a problem with destroying the sound instance after it is finished playing
This is my code, and the sound instance is not being destroyed, ive tried debrisservice and Destroy() to no avail. Any help on this issue would be very appreciated

local Music = script.Parent.Music

local DebrisService = game:GetService("Debris")

local AudioPart = script.Parent.AudioPart

local MusicTable = {}

local LastSong

for i , v in pairs(Music:GetChildren()) do
	
	if v:IsA("Sound") then
		
		table.insert(MusicTable , 1 , v)
		
	end
	
end

print(MusicTable)

while true do
	
	task.wait(5)
	
	
	local randomSongSelection = MusicTable[math.random(1 , #MusicTable)]
	
	
	local CloneSong = randomSongSelection:Clone()
	
	
	CloneSong.Parent = AudioPart
	
	CloneSong:Play()
	
	CloneSong.Ended:Wait()
		
	CloneSong.Ended:Connect(function()
		
		DebrisService:AddItem(CloneSong , 1)
		
	end)
		

	task.wait(4)
	
end

you can try

wait(CloneSong.TimeLength)	
--after it ends ↓
DebrisService:AddItem(CloneSong , 1)--just in case :)

I use it and everything works fine for me

1 Like

Look into Sound.Ended. This event fires when the sound has completed playback. You can connect a function to destroy the sound here.

2 Likes

tried this but it just deletes the song a second later and does not play the full song

Thanks i saw that you cannot connect a function to sound.ended, which is what i was attempting to do, and saw roblox provided an example on how a sound could be destroyed

You can connect to events like this:

-- Indirectly:
local function onEnded(soundId)
	-- code
end

Sound.Ended:Connect(onEnded)


-- Directly:
Sound.Ended:Connect(function(soundId)
	-- code
end)
1 Like

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