Song player plays like 4 billion songs at one time

Ok, so i made a song player, but it plays 4 trillion songs at one time.

Here is my code:

--[ VARIABLES ]--
local Playlist = script.Parent:WaitForChild("Playlist")
local SongIsCurrentlyPlaying = false

--[ PICK RANDOM MUSIC FUNCTION ]--
function PickRandomSong()
	local Songs = {}

	for _, Song in pairs(Playlist:GetChildren()) do
		table.insert(Songs, 1, Song)
	end

	local Song = Songs[math.random(1, #Songs)]
	return Song
end

function MusicUI(SongName)
	script.Parent.Parent.MusicNameUI.Enabled = true
	
	script.Parent.Parent.MusicNameUI.TextLabel.Text = SongName
	
	for i = 1, 100 do
		game:GetService("RunService").Heartbeat:Wait()
		script.Parent.Parent.MusicNameUI.TextLabel.TextTransparency -= 0.01
	end
	
	wait(2)
	
	for i = 1, 100 do
		game:GetService("RunService").Heartbeat:Wait()
		script.Parent.Parent.MusicNameUI.TextLabel.TextTransparency += 0.01
	end
end

while true do
	game:GetService("RunService").Heartbeat:Wait()

	if SongIsCurrentlyPlaying == false then
		SongIsCurrentlyPlaying = true
		local SongChosen = PickRandomSong()
		
		spawn(function()
			MusicUI(SongChosen.Name)
		end)
		
		SongChosen:Play()
		wait(SongChosen.TimeLength)
		SongIsCurrentlyPlaying = false
	end
end

Please help, thanks!

Are you preloading the songs? Might be completely wrong but my initial thought would be .TimeLength returning 0 because the Sound isn’t loaded when you first play it.

What is preloading? and how do i do it?

ContentProvier:PreLoadAsync
" This function takes an array of Instances as a parameter and yields until all of assets associated with those instances have loaded. This can be used to pause a script and not use content until it is certain that the content has been loaded into the game."

Assuming each child of Playlist is a soundtrack to play, do something like this towards the top.

local ContentProvider = game:GetService("ContentProvider")
ContentProvier:PreloadAsync(Playlist) --Yields until all assets preload

Instead of waiting timeLength, I would wait for the soundEnded trigger. (sound.Ended:Wait()). I think that would resolve your issue :slight_smile:

2 Likes

Where do I put this? when i use that it just print this:image

You’d need it after you’ve defined Playlist

(Just gonna yeet myself into this conversation here: I’m not sure if the preloading will work as it expects an array, but the “PlayList” variable refers to some kind of “folder” or at least a game object that contains several items if I’m not mistaken.) I might be wrong, though!

2 Likes

I think you’re correct, I usually use something like :GetChildren() instead but just read that it also acts upon all decendants of passed objects. The correct way I think to call it here though would probably be:

ContentProvier:PreloadAsync({Playlist})

I might still be wrong though.
The safe route would probably be:

ContentProvider:PreloadAsync(Playlist:GetChildren())

Still not sure if thatll resolve the problem though.

1 Like