Experiencing buggy audio behavior in music system

I am attempting to create a music system that just simply plays random sound ID from a list of music provided by a table.

-- all server-side
local soundInstance = Instance.new("Sound", workspace) -- I only parent so don't kill me for using second argument

local function playSong()
    local newSong = getRandomSong()
    soundInstance.SoundId = "rbxassetid://"..newSong.Id
    if not soundInstance.IsLoaded then
        soundInstance.Loaded:Wait()
    end
    
    print("Loaded "..newSong.Name)
    
    soundInstance:Play()
    
    print("Song "..newSong.Name.." now playing..")
end

coroutine.wrap(function()
    local players = game.Players
    while true do
        if #players:GetPlayers() == 0 then
            players.PlayerAdded:Wait()
        end
        
        playSong()
        soundInstance.Ended:Wait()
    end
end)()

I am having the sound randomly pause when it ends (doesn’t even fire Paused event) and sometimes a new song plays before the current ends then goes halfway in. getRandomSong() just gets a random sound ID so not really anything new to have by showing it.

This bug is consistent in ingame testing and Studio testing.


Test File used:

SongTest.rbxl (18.5 KB)

see if this works

-- all server-side
local soundInstance = Instance.new("Sound", workspace) -- I only parent so don't kill me for using second argument

local function playSong()
    local newSong = getRandomSong()
    soundInstance.SoundId = "rbxassetid://"..newSong.Id
    if not soundInstance.IsLoaded then
        soundInstance.Loaded:Wait()
    end
    
    print("Loaded "..newSong.Name)
    
    soundInstance:Play()
    
    print("Song "..newSong.Name.." now playing..")
end

coroutine.wrap(function()
    local players = game.Players
    while true do
        playSong()
        wait(soundInstance.TimeLength)
    end
end)()

That does not work either but it seems that pre-loading many sounds seems to work much better.

However, Ended:Wait() was the culprit here as it would no matter in any case, yield infinitely and was unreliable.

Thus, the solution was to really just create pre-loaded sounds first then wait the time length of the song.

Is the audio instance set to loop around when at the end? In that case, it doesn’t fire the .Ended signal.

I don’t think it’s looped, that code is the full code and I am making an entirely new Sound instance in the code to use.