Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I make it so when the song ends it restarts?

So i've done a script so it plays music from a table and I just don't know how to make it choose again from the table when it ends

local songs = {160442087,705243700}

function playmusic()
    local sound = Instance.new("Sound", game:GetService("Workspace"))
	if sound then
	sound.SoundId = "rbxassetid://"..songs[math.random(1,#songs)]
	sound:Play()
	end
	end

playmusic()

2 comments

0

How many songs do you have?

0

Try the new script my edited script.

2 answers

✓ Accepted answer

Firstly, let's use an infinite loop (while true do ... end) to have the music system function indefinitely:

while true do
	-- ...
end

Now, we'll pick and play a random song at the beginning of the statement body. Instead of using math.random, we'll use the recommended Random object; the algorithm provides more randomised numbers. According to some developers, math.random has been updated to use this new algorithm anyway, but I cannot confirm this. We'll also refrain from using the second parent parameter of Instance.new, as it is deprecated:

local songs = {
	160442087,
	705243700,
}
local sound
-- Create a new Random.
local random = Random.new()

while true do
	-- Pick and play a random song.
	sound = Instance.new("Sound")
	sound.SoundId = "rbxassetid://" .. songs[random:NextInteger(1, #songs)]
	sound.Parent = workspace
	sound:Play()
end

Lastly, let's use the Sound.Ended event to wait until the song ends. Once it ends, we'll start again:

local songs = {
	160442087,
	705243700,
}
local sound
-- Create a new Random.
local random = Random.new()

while true do
	-- Pick and play a random song.
	sound = Instance.new("Sound")
	sound.SoundId = "rbxassetid://" .. songs[random:NextInteger(1, #songs)]
	sound.Parent = workspace
	sound:Play()
	-- Yield until the sound ends.
	sound.Ended:Wait()
end

7 comments

0

Wish I could upvote this! Thank you!

0

No worries! :) You can accept the answer if you think it answered your question to help me out instead

0

this is messy, no offence

0

Which part of it is messy?

0

How do I accept it?

0

Click "Accept Answer"

0

Haha couldnt see it , had to go on edge idk why

I have a script but this changes your table. Try using this script:

local songs = {160442087,705243700}


    local sound = Instance.new("Sound", game:GetService("Workspace"))
while true do
    if sound then
    sound.SoundId = "rbxassetid://"..songs[math.random(1,#songs)]
    sound:Play()
wait(sound.Timelength)
    end
    end



2 comments

0

Sound:Play does not yield

0

This also does not relate to his request

This discussion is preserved as it was. New answers, comments, and votes are closed.