This sets whether or not the
Sound repeats once it has finished when it is playing.
Looped sounds are suitable for a range of applications including music and background ambient sounds. The
Sound/DidLoop event can be used to track the number of times as sound has looped.
Whilst looping is most appropriate for longer tracks such as music or ambient sounds, this sample demonstrates sound looping by creating the Roblox death sound in every character’s head and looping it.
The Players.PlayerAdded and Player.CharacterAdded functions are used to detect new player characters. One a new character has been added a sound is created in their head. For demonstration purposes, the Sound.DidLoop function is used to show how the number of times a particular sound has looped can be tracked.
local Players = game:GetService("Players") Players.PlayerAdded:Connect(function(player) -- listen for new characters player.CharacterAdded:Connect(function(character) -- wait for the head to be added local head = character:WaitForChild("Head") -- create a sound local sound = Instance.new("Sound", head) sound.Name = "TestSound" sound.SoundId = "rbxasset://sounds/uuhhh.mp3" -- oof -- loop the sound sound.Looped = true -- listen for loops sound.DidLoop:Connect(function(soundId, numOfTimesLooped) print("oof! "..tostring(numOfTimesLooped)) end) -- play the sound sound:Play() end) end)
Loop a Number of Times
This code sample includes a function that will play a sound and allow it to loop for a given number of times before stopping it.
local function loopNTimes(sound, numberOfLoops) if not sound.IsPlaying then sound.Looped = true local connection = nil connection = sound.DidLoop:Connect(function(soundId, numOfTimesLooped) print(numOfTimesLooped) if numOfTimesLooped >= numberOfLoops then -- disconnect the connection connection:Disconnect() -- stop the sound sound:Stop() end end) sound:Play() end end