Hello! I was trying to create a local music system the other day, and I was successful. Well, for the most part. Every now and then, 2 songs play at once. I don’t know why this is; the code looks perfectly fine to me. I was hoping someone could help me out!
I have a folder in ReplicatedStorage that contains all of the sounds which are to be played by this LocalScript in StarterGui:
local MusicFolder = game.ReplicatedStorage:WaitForChild("Music") -- music folder
local AvailableMusic = MusicFolder:GetChildren() -- the sounds
while true do
local randomTrack = AvailableMusic[math.random(1, #AvailableMusic)] -- gets a random sound
wait(2) -- delay before next song plays
randomTrack:Play() -- plays the selected sound
wait(randomTrack.TimeLength) -- waits for the sound to end (by waiting its TimeLength)
end
It works fine most of the time, as I said. I just need some quick help to debug it. Thanks!
If you forgot the issue, it was that sometimes 2 songs would play at once.
local MusicFolder = game.ReplicatedStorage:WaitForChild("Music")
local TimeBetweenTracks = 1.5
local AllowRepeats = false
local Debug = true
function dbgP(m)
if Debug then
print("DBG("..script.Name.."): "..m)
end
end
local LastSongId = ""
while true do
local Songs = MusicFolder:GetChildren()
math.randomseed(tick())
local Song = Songs[math.random(1,#Songs)]:Clone()
if Song.SoundId == LastSongId and not AllowRepeats then
dbgP("Repeated Song: "..Song.Name)
wait()
if #Songs <= 1 then
dbgP("#Songs <= 1 -> break")
break
end
continue
end
Song.Parent = workspace
if not Song.IsLoaded then
dbgP("Waiting for: "..Song.Name)
Song.Loaded:wait()
end
dbgP("Playing: "..Song.Name.." For: "..Song.TimeLength.." Seconds.")
Song:Play()
LastSongId = Song.SoundId
wait(Song.TimeLength)
Song:Destroy()
wait(TimeBetweenTracks)
end
The solution proposed by @AdjacentPhoenix is extremely effective, but I just ran into the problem again. The script is in StarterPlayer > StarterPlayerScripts. Any ideas as to why this may be still happening (even with rare circumstances)?
You can use .Ended:Wait() to pause the thread until the sound ending event is fired. I also fixed up some things in the script (see the comments). Hope this helps.
local ReplicatedStorage = game:GetService("ReplicatedStorage") --You should use GetService, it's a better development practice
local MusicFolder = ReplicatedStorage.Music --You don't need to use WaitForChild in ReplicatedStorage
local AvailableMusic = MusicFolder:GetChildren()
while true do
local randomTrack = AvailableMusic[math.random(1, #AvailableMusic)]
wait(2)
randomTrack:Play()
randomTrack.Ended:Wait()
end