Create Audio Playlist in Roblox Studio
In this guide, we will show how to implement an audio playlist in Roblox Studio that will play background music in a loop in your Roblox game.
To create a looping music playlist, you will have to use a script.
First, prepare the audio tracks you wish to include in your playlist. To do so, go to our Music page, search for audio tracks, and build a playlist (audio list) with them. Then click the ‘Copy my audio list' button.
Next, open your game in Roblox Studio, and insert a script into 'ServerScriptService': in the Explorer window, right click 'ServerScriptService' >> select 'Insert Object' >> type 'Script' in the search field >> select Script.
Copy and paste the following code into your new script. This code will handle audio playback in a loop.
-- List of audio track IDs
local playlist = {
1843463175, -- Creepy Organ/Dungeon
1837849285, -- Upbeat Electronica
1848183670 -- Grandiose Fantasy
}
-- Variables
local currentTrackIndex = 1
local soundService = game:GetService("SoundService")
-- Function to play the next track
local function playNextTrack()
-- Stop the currently playing sound if there is one
if soundService:FindFirstChild("BackgroundMusic") then
soundService.BackgroundMusic:Stop()
end
-- Create a new Sound instance
local sound = Instance.new("Sound")
sound.Name = "BackgroundMusic"
sound.SoundId = "rbxassetid://" .. playlist[currentTrackIndex]
sound.Looped = false
sound.Parent = soundService
-- Play the sound
sound:Play()
-- Move to the next track in the playlist
currentTrackIndex = currentTrackIndex % #playlist + 1
end
-- Connect the function to the Sound's Ended event
soundService.ChildAdded:Connect(function(child)
if child:IsA("Sound") and child.Name == "BackgroundMusic" then
child.Ended:Connect(playNextTrack)
end
end)
-- Start the playlist
playNextTrack()
Explanation of the Script:
Playlist array: the playlist table contains the IDs of your audio tracks.
playNextTrack function: this function stops the current track, creates a new Sound instance, sets its SoundID to the current track and plays it. It also updates the index to the next track in the playlist.
soundService.ChildAdded Event: this listens for when a new Sound is added to the SoundService. When it detects the BackgroundMusic sound, it connects the Ended event to the playNextTrack function, ensuring that the next track plays when the current one ends.
Start Playlist: the script starts by playing the first track in the playlist.
Testing:
Click 'Play' button on the 'Script' tab and test your game. The music should play in loop indefinetely.
If you want, you can adjust the script according to your specific needs: add more tracks, etc.
Once finished testing, publish your game by going to 'File - Publish to Roblox'.