I recently began working on the background music for my game.
I have created this gorgeous background music play (sarcastic tone. Its actually quite normal)
But the problem is it only plays 1 song then never plays anymore songs?
Heres the code
local ReplicatedStorage = game:GetService("ReplicatedStorage") local SongPlaying = false local TatooineMusic1 = ReplicatedStorage.AudioStorage:WaitForChild("BackgroundMusicTatooine") local TatooineMusic2 = ReplicatedStorage.AudioStorage:WaitForChild("BackgroundMusicTatooine2") while true do local RandomSong = math.random(1,2) if RandomSong == 1 and SongPlaying == false then print(RandomSong) SongPlaying = true TatooineMusic1:Play() TatooineMusic1.Ended:connect(function() SongPlaying = false end) elseif RandomSong == 2 and SongPlaying == false then print(RandomSong) SongPlaying = true TatooineMusic2:Play() TatooineMusic2.Ended:connect(function() SongPlaying = false end) end wait() end
Yes it is a Star Wars game... Dont judge, Its actually pretty good in my opinion.
But anyways anyone have any ideas on how to fix it? Thank you for your time!
I didn't see an error but may I just show you how to make this loop not endlessly looping and checking the boolean but instead just waiting
local ReplicatedStorage = game:GetService("ReplicatedStorage") local songs = ReplicatedStorage.AudioStorage:GetChildren() while true do local random = Random.new() local song = songs[random:NextInteger(1, #songs)] song:Play() song.Ended:Wait() end
This is a much more simplified way of doing it, and it won't be endlessly looping (this will wait until the song is over)
Here, try this:
math.randomseed(tick()) local ReplicatedStorage = game:GetService("ReplicatedStorage") local TatooineMusic1 = ReplicatedStorage.AudioStorage:WaitForChild("BackgroundMusicTatooine") local TatooineMusic2 = ReplicatedStorage.AudioStorage:WaitForChild("BackgroundMusicTatooine2") while true do local RandomSong = math.random(1, 100) local WaitTime = 60 if RandomSong >= 1 and RandomSong <= 50 then print(RandomSong) TatooineMusic1:Play() WaitTime = TatooineMusic1.TimeLength elseif RandomSong > 50 and RandomSong <= 100 then print(RandomSong) TatooineMusic2:Play() WaitTime = TatooineMusic1.TimeLength end wait(WaitTime) end
Hope this helped!