Roblox Tutorial - How to create an automatic music system source code

Source code:

local Songs = {1837416036, 1837937289, 1837949703} --Allows us to get all the songs we need
local times = 0

local function PickRandomSong()
	return Songs[math.random(1, #Songs)] --Pick a random value from the table inbetween 1 and the amoun of values in the table
end

function LoadAudio(audioId) --Get the audio ready
	local NewAudio = Instance.new("Sound")
	times = times +1
	NewAudio.Name = "Sound" ..times
	NewAudio.Parent = game.Workspace.SoundSystem
	local audioInstance = game.Workspace.SoundSystem:WaitForChild("Sound" ..times) --Get the sound instance we just made
	audioInstance.SoundId = "rbxassetid://" .. audioId --We concatenate "rbxassetid://" with the audio id, this allows us to set the song we want the system to play
	return audioInstance
end  



local function PlayAudio() --Play audio 
	local SelectedSong = PickRandomSong() --Get a random song using our variable that will return the randomlly selected song
	local NewAudio = LoadAudio(SelectedSong) -- WE'll use the random song selected load it in
	NewAudio:Play()
	NewAudio.Volume = 1
	NewAudio.Ended:Connect(function() --Detect when song ends to play a new song
		NewAudio:Destroy()
		PlayAudio() --Play the audio.
	end)
end




PlayAudio()


--These comments are just notes. 

If you have any issues feel free to make a #scripting-support topic!

1 Like

This topic was automatically closed 1 minute after the last reply. New replies are no longer allowed.