Script that plays sound bugged out

Hello. I made a script that plays the songs in the table randomly. It also has a feature that prevents the same song from repeating.

Issue - Everything works but after it plays a couple songs it stops. Then 1 minute later it plays again but its only half of the song that plays.

local Songs = {5516201852,6484215125,6805470537,5048709195,784812709,6569662206}
local LastPlayed

local SoundPlayer = script.Parent:WaitForChild("Base"):WaitForChild("Sound")


while true do
	local SelectedSong = Songs[math.random(1,#Songs)]
	
	if SelectedSong ~= LastPlayed then
		LastPlayed = SelectedSong
		SoundPlayer.SoundId = "rbxassetid://"..SelectedSong
		SoundPlayer:Play()
	end
	
	repeat wait() until not SoundPlayer.IsPlaying
end

Here is the script. It displays no errors in the output aswell.

2 Likes

There is an event for this. Sound | Roblox Creator Documentation

Also if you need help there is a small article on the devHubthat has code of an audio player.

3 Likes

@lodebt
While I know your question has already been answered, I would also recommend trying my solution to the problem

local Songs = {5516201852,6484215125,6805470537,5048709195,784812709,6569662206}
local LastPlayed = nil

local Base = script.Parent:FindFirstChild(“Base”)
local SoundPlayer = Base:FindFirstChild(“Sound”)

while true do
local SelectedSong = Songs[math.random(#Songs)]
while SelectedSong == LastPlayed do
SelectedSong = Songs[math.random(#Songs)]
wait()
end
LastPlayed = SelectedSong
SoundPlayer.SoundId = “rbxassetid://” … SelectedSong
local Loaded = SoundPlayer.Loaded:Wait(5)
if Loaded then
SoundPlayer:Play()
end
SoundPlayer.Ended:Wait()
end

My solution both waits for the sound to load before continuing, avoiding any loading errors, and uses your current solution to wait till the sound has finished

2 Likes

Works just right! Thank you very much for taking your time and helping me out. :hugs:

2 Likes

Thank you! Just what I needed…

1 Like