Sound
*Este conteúdo é traduzido por IA (Beta) e pode conter erros. Para ver a página em inglês, clique aqui.
Sound é um objeto que emite som.Quando colocado em um BasePart ou em um Attachment, este objeto emitirá seu som da parte BasePart.Position ou do anexo Attachment.WorldPosition.Nesta colocação, um Sound exibe o efeito Doppler, significando que sua frequência e altura varia com a movimentação relativa de qualquer anexo ou peça a que está anexado.Além disso, seu volume será determinado pela distância entre o ouvinte de som do cliente (por padrão, a posição Camera ) e a posição do pai do som.Para mais informações, veja RollOffMode .
Um som é considerado "global" se ele não for filho de um ou de um ].Neste caso, o som será reproduzido com o mesmo volume em todo o local.
Amostras de código
The code in this sample demonstrates how a sound parented to a Part or Attachment will play locally and experience volume drop off the further the player's camera is away from the part.
A part is instanced, and a sound is instanced and parented to the part. A click detector is set up on the part that will check if the sound is playing, using Sound.IsPlaying and play or stop the sound depending.
local part = Instance.new("Part")
part.Anchored = true
part.Position = Vector3.new(0, 3, 0)
part.BrickColor = BrickColor.new("Bright red")
part.Name = "MusicBox"
part.Parent = workspace
-- create a sound
local sound = Instance.new("Sound", part)
sound.SoundId = "rbxassetid://9120386436"
sound.EmitterSize = 5 -- decrease the emitter size (for earlier volume drop off)
sound.Looped = true
sound.Parent = part
local clickDetector = Instance.new("ClickDetector")
clickDetector.Parent = part
-- toggle the sound playing / not playing
clickDetector.MouseClick:Connect(function()
if not sound.IsPlaying then
part.BrickColor = BrickColor.new("Bright green")
sound:Play()
else
part.BrickColor = BrickColor.new("Bright red")
sound:Stop()
end
end)
Resumo
Propriedades
Essa propriedade é true quando o Sound foi carregado dos servidores do Roblox e está pronto para jogar.
Propriedade apenas de leitura que retorna true quando o Sound não está tocando.
Propriedade apenas de leitura que retorna true quando o Sound estiver tocando.
Um alcance que denota um começo e fim de ciclo desejado dentro do PlaybackRegion, em segundos.
Define se o Sound repetirá ou não uma vez que terminar de tocar.
Quando true , o Sound será reproduzido quando for removido da experiência.
Um número entre 0 e 1000 indicando quão alto o Sound está tocando voltarmomento.
Um alcance que denota um começo e fim desejado dentro do TimeLength, em segundos.
Se true , esta propriedade dá acesso à sua propriedade Sound às propriedades PlaybackRegion e LoopRegion que podem controlar mais precisamente o seu toque.
Determina a velocidade em que um Sound jogar, com valores mais altos fazendo com que o som toque mais rápido e em um tom mais alto.
Indica se o Sound está tocando atualmente.
A distância máxima, em studs, o ouvinte de um cliente pode ser da origem do som e ainda ouvi-lo.Aplica-se apenas ao Sounds pai para um BasePart ou Attachment .
A distância mínima, em studs, na qual um Sound que é parentado a um BasePart ou Attachment começará a atenuar (diminuição de volume).
Controla como o volume de um Sound que é parented para um BasePart ou Attachment diminui (desaparece) à medida que a distância entre o ouvinte e o pai muda.
O SoundGroup que está ligado a este Sound .
ID de conteúdo do arquivo de som para associar ao Sound.
O comprimento do Sound em segundos.
Progresso do Sound em segundos. Pode ser alterado para mover a posição de reprodução do Sound antes e durante a reprodução.
O volume do Sound.
Métodos
Propriedades
ChannelCount
IsLoaded
Essa propriedade é true quando o Sound foi carregado dos servidores do Roblox e está pronto para jogar.Você pode usar essa propriedade e o evento Loaded para verificar se um som foi carregado antes de tocá-lo.
Amostras de código
This simple function will verify a Sound has loaded by checking the Sound.IsLoaded property. If Sound.IsLoaded is false it will wait for the Loaded event before resuming.
It is important to check Sound.IsLoaded before connecting to the Sound.Loaded event, as if the sound has already loaded the Sound.Loaded event will not fire and the function will yield indefinitely.
local sound = script.Parent.Sound
if not sound.IsLoaded then
sound.Loaded:Wait()
end
print("The sound has loaded!")
IsPaused
Essa propriedade de leitura exclusiva retorna true quando o Sound não está tocando.Observe que ele pode retornar true se um som foi pausado usando Pause() , se ele foi interrompido usando Stop() ou o som nunca foi tocado.
Como IsPaused é apenas de leitura, não pode ser usado para interromper o som; Stop() ou Pause() deve ser usado em vez disso.
Amostras de código
This code sample contains demonstrates when the Sound.IsPlaying and Sound.IsPaused properties will be true or false.
A sound is instanced in the Workspace and the Sound.IsLoaded property is checked to ensure it has loaded, if it has not the Sound.Loaded event is used to yield the script until the sound has.
As the sound is played, paused and stopped the Sound.IsPlaying and Sound.IsPaused properties are printed to demonstrate how they respond to each of these functions. Note Sound.IsPaused will always be true if even if the sound has been stopped rather than paused.
local sound = Instance.new("Sound")
sound.SoundId = "rbxassetid://9120386436"
sound.Looped = true
sound.Parent = workspace
if not sound.isLoaded then
sound.Loaded:Wait()
end
sound:Play()
print(sound.IsPlaying, sound.IsPaused) -- true, false
task.wait(2)
sound:Pause()
print(sound.IsPlaying, sound.IsPaused) -- false, true
task.wait(2)
sound:Play()
print(sound.IsPlaying, sound.IsPaused) -- true, false
task.wait(2)
sound:Stop()
print(sound.IsPlaying, sound.IsPaused) -- false, true
IsPlaying
Essa propriedade de leitura só retorna verdadeiro quando o Sound está tocando.
Como IsPlaying é apenas de leitura, não pode ser usado para tocar o som; Play() deve ser usado em vez disso.
Amostras de código
This code sample contains demonstrates when the Sound.IsPlaying and Sound.IsPaused properties will be true or false.
A sound is instanced in the Workspace and the Sound.IsLoaded property is checked to ensure it has loaded, if it has not the Sound.Loaded event is used to yield the script until the sound has.
As the sound is played, paused and stopped the Sound.IsPlaying and Sound.IsPaused properties are printed to demonstrate how they respond to each of these functions. Note Sound.IsPaused will always be true if even if the sound has been stopped rather than paused.
local sound = Instance.new("Sound")
sound.SoundId = "rbxassetid://9120386436"
sound.Looped = true
sound.Parent = workspace
if not sound.isLoaded then
sound.Loaded:Wait()
end
sound:Play()
print(sound.IsPlaying, sound.IsPaused) -- true, false
task.wait(2)
sound:Pause()
print(sound.IsPlaying, sound.IsPaused) -- false, true
task.wait(2)
sound:Play()
print(sound.IsPlaying, sound.IsPaused) -- true, false
task.wait(2)
sound:Stop()
print(sound.IsPlaying, sound.IsPaused) -- false, true
LoopRegion
Um alcance que denota um começo e fim de ciclo desejado dentro do PlaybackRegion, em segundos.
Se Class.Sound.LoopRegion|LoopRegion.Min``>``Class.Sound.PlaybackRegion|PlaybackRegion.Min , o ciclo começa a partir de LoopRegion.Min .
Se Class.Sound.LoopRegion|LoopRegion.Min``<``Class.Sound.PlaybackRegion|PlaybackRegion.Min , o ciclo começa a partir de PlaybackRegion.Min .
Se Class.Sound.LoopRegion|LoopRegion.Max``>``Class.Sound.PlaybackRegion|PlaybackRegion.Max , o ciclo começa em PlaybackRegion.Max .
Se Class.Sound.LoopRegion|LoopRegion.Max``<``Class.Sound.PlaybackRegion|PlaybackRegion.Max , o ciclo começa em exatamente naquele momento.
Se Class.Sound.LoopRegion|LoopRegion.Min``==``Class.Sound.LoopRegion|LoopRegion.Max , o Sound usa a propriedade PlaybackRegion em vez disso.
Looped
Isso define se o Sound repetirá ou não depois de terminar de tocar.Sons em loop são adequados para uma variedade de aplicações, incluindo música e sons ambientais de fundo.
O evento DidLoop pode ser usado para rastrear o número de vezes que o som se repetiu.
Amostras de código
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
local sound = Instance.new("Sound")
sound.SoundId = "rbxassetid://0"
loopNTimes(sound, 5)
PlayOnRemove
Quando true , o Sound vai tocar quando for removido da experiência ao acasalar o Sound ou um se seus ancestrais para nil .Isso significa que tudo o seguinte causará o som a tocar quando PlayOnRemove estiver true :
- sound:Destroy()
- sound.Parent = nil
- sound.Parent.Parent = nil
PlaybackLoudness
Um número entre 0 e 1000 indicando quão alto o Sound está tocando voltarmomento.Essa propriedade reflete a amplitude do toque do som na instância do tempo em que é ler.
Amostras de código
In this sample Sound.PlaybackLoudness is used to create an amplitude bar that shows the amplitude of a sound playing.
This code sample should be placed in StarterPlayerScripts.
A simple GUI is created, a frame holding that bar and a frame containing the bar. A Sound is then played and the size of the bar is set to reflect the Sound.PlaybackLoudness on a loop.
-- to be placed in StarterPlayer > StarterPlayerScripts
local Players = game:GetService("Players")
-- wait for local player PlayerGui
local LocalPlayer = Players.LocalPlayer
local playerGui = LocalPlayer:WaitForChild("PlayerGui")
-- create a ScreenGui
local screenGui = Instance.new("ScreenGui")
screenGui.Parent = playerGui
-- create a holder for our bar
local frame = Instance.new("Frame")
frame.AnchorPoint = Vector2.new(0.5, 0.5)
frame.Position = UDim2.new(0.5, 0, 0.5, 0)
frame.Size = UDim2.new(0.3, 0, 0.05, 0)
frame.Parent = screenGui
-- create a bar
local bar = Instance.new("Frame")
bar.Position = UDim2.new(0, 0, 0, 0)
bar.Size = UDim2.new(1, 0, 1, 0)
bar.BackgroundColor3 = Color3.new(0, 1, 0)
bar.Parent = frame
-- create a sound
local sound = Instance.new("Sound")
sound.SoundId = "rbxassetid://9120386436"
sound.Looped = true
sound.Parent = screenGui
sound:Play()
-- define a max loudness
local maxLoudness = 30
-- animate the amplitude bar
while true do
local amplitude = math.clamp(sound.PlaybackLoudness / maxLoudness, 0, 1)
bar.Size = UDim2.new(amplitude, 0, 1, 0)
wait(0.05)
end
PlaybackRegion
Um alcance que denota um começo e fim desejado dentro do TimeLength, em segundos.
Se PlaybackRegion.Min``>``0 , o som começa a tocar a partir do tempo PlaybackRegion.Min.
Se PlaybackRegion.Min``<``0 , o som começa a tocar a partir de 0 .
Se PlaybackRegion.Max``>``Class.Sound.TimeLength , o som para em Sound.TimeLength .
Se PlaybackRegion.Max``<``Class.Sound.TimeLength , o som para em exatamente naquele momento.
Se Class.Sound.PlaybackRegion|PlaybackRegion.Min``==``Class.Sound.PlaybackRegion|PlaybackRegion.Max , esta propriedade está inativo.
PlaybackRegionsEnabled
Se true , esta propriedade dá acesso à sua propriedade Sound às propriedades PlaybackRegion e LoopRegion que podem controlar mais precisamente o seu toque.
PlaybackSpeed
Determina a velocidade em que um Sound jogar, com valores mais altos fazendo com que o som toque mais rápido e em um tom mais alto.
Amostras de código
In this example a Sound is played in the Workspace. The PlaybackSpeed property is increased and decreased at intervals to demonstrate its impact on the playback of the Sound.
local sound = Instance.new("Sound")
sound.SoundId = "rbxassetid://9120386436"
sound.Looped = true
sound.Parent = workspace
sound:Play()
task.wait(10)
sound.PlaybackSpeed = 3 -- 3x faster
task.wait(5)
sound.PlaybackSpeed = 0.5 -- 2x slower
task.wait(5)
sound.PlaybackSpeed = 1 -- default
Playing
Indica se o Sound está tocando atualmente. Isso pode ser ativado e essa propriedade sempre se replicará.
Na janela Propriedades do Studio, enquanto estiver no modo Editar , ao alternar Playing``true, mas o som começará a tocar durante a tempo de execução.
Essa propriedade não deve ser confundida com IsPlaying que é uma propriedade apenas de leitura.
Observe que quando Playing é definido como false , a propriedade TimePosition do som não será redefinir, o que significa que, quando Playing for definido como true novamente, o áudio continuará a partir da posição de tempo em que estava quando foi interrompido.No entanto, se a função Play() for usada para retomar o som, a posição do tempo será redefinida para 0.
Amostras de código
This sample demonstrates how the Sound.Playing property can be used to start and stop playback of a sound.
A sound is instanced in the Workspace and playback is started by setting Sound.Playing to true. After ten seconds the playback is stopped by setting Sound.Playing to false. When the playback is again resumed using Sound.Playing it resumes at the previous Sound.TimePosition it was stopped at. This is demonstrated by printing the TimePosition property immediately after resuming the sound.
local sound = Instance.new("Sound")
sound.SoundId = "rbxassetid://9120386436"
sound.Looped = true
sound.Parent = workspace
print("playing sound")
sound.Playing = true
task.wait(10)
print("stopping sound")
sound.Playing = false
task.wait(5)
sound.Playing = true
local timePosition = sound.TimePosition
print("resumed at time position: " .. tostring(timePosition)) -- c. 10 seconds
RollOffMaxDistance
A distância máxima, em studs, o ouvinte de um cliente pode ser da origem do som e ainda ouvi-lo.Aplica-se apenas ao Sounds pai para um BasePart ou Attachment .
Como RollOffMaxDistance afeta a atenuação de um som (maneira pela qual desaparece) depende da propriedade RollOffMode.
RollOffMinDistance
A distância mínima, em studs, na qual um Sound que é parentado a um BasePart ou Attachment começará a atenuar (diminuição de volume).
Como RollOffMinDistance afeta a atenuação de um som (maneira pela qual desaparece) depende da propriedade RollOffMode.
RollOffMode
Essa propriedade controla como o volume de um Sound que é parented para um BasePart ou Attachment atenua (desaparece) à medida que a distância entre o ouvinte e o pai muda.
Para detalhes sobre os diferentes modos, veja Enum.RollOffMode .
SoundId
Esta propriedade é o ID do conteúdo do arquivo de som para associar ao Sound. Veja Recursos de Áudio para mais informações.
TimeLength
O comprimento do Sound em segundos. Se o Sound não for carregado, esse valor será 0 .
Essa propriedade é frequentemente usada em conjunto com PlaybackSpeed para ajustar a velocidade de um som para que dure por um período específico.
Amostras de código
This code sample includes a simple function that uses Sound.TimeLength and Sound.PlaybackSpeed to play a sound that'll take the given duration to complete. It achieves this by setting the PlaybackSpeed of the sound to be equal to the TimeLength of the sound divided by the desired duration.
Note that as TimeLength is equal to 0 when the sound has not loaded, the function will yield while it loads the sound.
local function playForDuration(sound, duration)
if not sound.IsLoaded then
sound.Loaded:wait()
end
local speed = sound.TimeLength / duration
sound.PlaybackSpeed = speed
sound:Play()
end
local sound = script.Parent
playForDuration(sound, 5)
TimePosition
Essa propriedade reflete o progresso do Sound em segundos.Pode ser alterado para mover a posição de reprodução do som antes e durante a reprodução.
Ao ser reproduzido como um Sound , TimePosition aumenta em uma taxa de PlaybackSpeed por segundo.Uma vez que TimePosition chegue a TimeLength, o som vai parar a menos que seja Looped.
Observe que definir TimePosition para um valor maior que o comprimento em uma faixa em loop não fará com que ela se enrole.Se esse comportamento for desejado, considere o seguinte trecho de código:
local newPosition = 1.5if newPosition >= sound.TimeLength thennewPosition = newPosition - sound.TimeLengthendsound.TimePosition = newPosition
Amostras de código
This sample demonstrates how Sound.TimePosition can be used to jump to particular points in an audio file both before and during Sound playback.
A Sound is created in the Workspace and set to start at 30 seconds in. During playback, it jumps forwards to 100 seconds and then back to the start (0 seconds).
local sound = Instance.new("Sound")
sound.SoundId = "rbxassetid://9120386436"
sound.Parent = workspace
sound.TimePosition = 30
sound:Play()
task.wait(5)
sound.TimePosition = 100
task.wait(5)
sound.TimePosition = 0
Volume
O volume do Sound . Pode ser definido entre 0 e 10 e padrão para 0.5 .
Observe que se o Sound for um membro de um SoundGroup, o volume de reprodução (mas não sua propriedade Volume) será influenciado pela propriedade do grupo SoundGroup.Volume.
Métodos
Pause
Este método pausa a reprodução do Sound se estiver tocando, definindo o Playing para false .Ao contrário de Stop(), ele não redefine TimePosition, o que significa que o som pode ser retomado usando Resume().
Devolução
Amostras de código
This sample gives a simple demonstration of what each of the Sound functions (Sound.Play, Sound.Stop, Sound.Pause and Sound.Resume) do to Sound.Playing and Sound.TimePosition.
-- create a sound
local sound = Instance.new("Sound", game.Workspace)
sound.SoundId = "rbxassetid://9120386436"
if not sound.IsLoaded then
sound.Loaded:Wait()
end
-- listen for events
sound.Played:Connect(function(_soundId)
print("Sound.Played event")
end)
sound.Paused:Connect(function(_soundId)
print("Sound.Paused event")
end)
sound.Resumed:Connect(function(_soundId)
print("Sound.Resumed event")
end)
sound.Stopped:Connect(function(_soundId)
print("Sound.Stopped event")
end)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
task.wait(10)
sound:Pause()
print("pause", sound.Playing, sound.TimePosition) -- pause false 10
task.wait(3)
sound:Resume()
print("play", sound.Playing, sound.TimePosition) -- play true 10
task.wait(3)
sound:Stop()
print("stop", sound.Playing, sound.TimePosition) -- stop false 0
task.wait(3)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
Play
Este método joga o Sound e define TimePosition para o último valor definido por um script (ou 0 se não tiver sido configurar), então define Playing para true.
Devolução
Amostras de código
This sample gives a simple demonstration of what each of the Sound functions (Sound.Play, Sound.Stop, Sound.Pause and Sound.Resume) do to Sound.Playing and Sound.TimePosition.
-- create a sound
local sound = Instance.new("Sound", game.Workspace)
sound.SoundId = "rbxassetid://9120386436"
if not sound.IsLoaded then
sound.Loaded:Wait()
end
-- listen for events
sound.Played:Connect(function(_soundId)
print("Sound.Played event")
end)
sound.Paused:Connect(function(_soundId)
print("Sound.Paused event")
end)
sound.Resumed:Connect(function(_soundId)
print("Sound.Resumed event")
end)
sound.Stopped:Connect(function(_soundId)
print("Sound.Stopped event")
end)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
task.wait(10)
sound:Pause()
print("pause", sound.Playing, sound.TimePosition) -- pause false 10
task.wait(3)
sound:Resume()
print("play", sound.Playing, sound.TimePosition) -- play true 10
task.wait(3)
sound:Stop()
print("stop", sound.Playing, sound.TimePosition) -- stop false 0
task.wait(3)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
Resume
Este método resume o Sound e define Playing para true .Não altera TimePosition e, portanto, pode ser usado para retomar a reprodução de um som pausado através de Pause() .
Devolução
Amostras de código
This sample gives a simple demonstration of what each of the Sound functions (Sound.Play, Sound.Stop, Sound.Pause and Sound.Resume) do to Sound.Playing and Sound.TimePosition.
-- create a sound
local sound = Instance.new("Sound", game.Workspace)
sound.SoundId = "rbxassetid://9120386436"
if not sound.IsLoaded then
sound.Loaded:Wait()
end
-- listen for events
sound.Played:Connect(function(_soundId)
print("Sound.Played event")
end)
sound.Paused:Connect(function(_soundId)
print("Sound.Paused event")
end)
sound.Resumed:Connect(function(_soundId)
print("Sound.Resumed event")
end)
sound.Stopped:Connect(function(_soundId)
print("Sound.Stopped event")
end)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
task.wait(10)
sound:Pause()
print("pause", sound.Playing, sound.TimePosition) -- pause false 10
task.wait(3)
sound:Resume()
print("play", sound.Playing, sound.TimePosition) -- play true 10
task.wait(3)
sound:Stop()
print("stop", sound.Playing, sound.TimePosition) -- stop false 0
task.wait(3)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
Stop
Este método interrompe o Sound e define Playing para false , então define TimePosition para 0.
Devolução
Amostras de código
This sample gives a simple demonstration of what each of the Sound functions (Sound.Play, Sound.Stop, Sound.Pause and Sound.Resume) do to Sound.Playing and Sound.TimePosition.
-- create a sound
local sound = Instance.new("Sound", game.Workspace)
sound.SoundId = "rbxassetid://9120386436"
if not sound.IsLoaded then
sound.Loaded:Wait()
end
-- listen for events
sound.Played:Connect(function(_soundId)
print("Sound.Played event")
end)
sound.Paused:Connect(function(_soundId)
print("Sound.Paused event")
end)
sound.Resumed:Connect(function(_soundId)
print("Sound.Resumed event")
end)
sound.Stopped:Connect(function(_soundId)
print("Sound.Stopped event")
end)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
task.wait(10)
sound:Pause()
print("pause", sound.Playing, sound.TimePosition) -- pause false 10
task.wait(3)
sound:Resume()
print("play", sound.Playing, sound.TimePosition) -- play true 10
task.wait(3)
sound:Stop()
print("stop", sound.Playing, sound.TimePosition) -- stop false 0
task.wait(3)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
Eventos
DidLoop
Incêndios sempre que os loops Sound forem executados.Retorna soundId e numOfTimesLooped, dando o ID do conteúdo do som e o número de vezes que foi repetido, respectivamente.
Quando o Sound é interrompido através de Stop() , o contador em loop é reiniciado, o que significa que o próximo evento DidLoop retornará 1 para numOfTimesLooped .
Parâmetros
Amostras de código
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
local sound = Instance.new("Sound")
sound.SoundId = "rbxassetid://0"
loopNTimes(sound, 5)
Ended
Incêndios quando o Sound concluiu a reprodução e parou. Este evento é frequentemente usado para destruir um som quando ele concluiu a reprodução:
sound:Play()sound.Ended:Wait()sound:Destroy()
Observe que este evento não não disparará por sons com setado para >, pois eles continuarão tocando ao chegar ao terminar/parar/sair.Este evento também não disparará quando o som for interrompido antes que a reprodução tenha concluído; para isso, use o evento Stopped.
Parâmetros
Loaded
Incêndios quando o Sound é carregado.
Como este evento só dispara no momento em que o som é carregado, é recomendado verificar a propriedade do som IsLoaded antes de se conectar a este evento.
Parâmetros
Amostras de código
This simple function will verify a Sound has loaded by checking the Sound.IsLoaded property. If Sound.IsLoaded is false it will wait for the Loaded event before resuming.
It is important to check Sound.IsLoaded before connecting to the Sound.Loaded event, as if the sound has already loaded the Sound.Loaded event will not fire and the function will yield indefinitely.
local sound = script.Parent.Sound
if not sound.IsLoaded then
sound.Loaded:Wait()
end
print("The sound has loaded!")
Paused
Incêndios sempre que o Sound é pausado usando Pause() .
Parâmetros
Amostras de código
This sample gives a simple demonstration of what each of the Sound functions (Sound.Play, Sound.Stop, Sound.Pause and Sound.Resume) do to Sound.Playing and Sound.TimePosition.
-- create a sound
local sound = Instance.new("Sound", game.Workspace)
sound.SoundId = "rbxassetid://9120386436"
if not sound.IsLoaded then
sound.Loaded:Wait()
end
-- listen for events
sound.Played:Connect(function(_soundId)
print("Sound.Played event")
end)
sound.Paused:Connect(function(_soundId)
print("Sound.Paused event")
end)
sound.Resumed:Connect(function(_soundId)
print("Sound.Resumed event")
end)
sound.Stopped:Connect(function(_soundId)
print("Sound.Stopped event")
end)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
task.wait(10)
sound:Pause()
print("pause", sound.Playing, sound.TimePosition) -- pause false 10
task.wait(3)
sound:Resume()
print("play", sound.Playing, sound.TimePosition) -- play true 10
task.wait(3)
sound:Stop()
print("stop", sound.Playing, sound.TimePosition) -- stop false 0
task.wait(3)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
Played
Incêndios sempre que o Sound é tocado usando Play() .Este evento não disparará se o for tocado devido ao ser definido como e o som ser destruído.
Parâmetros
Amostras de código
This sample gives a simple demonstration of what each of the Sound functions (Sound.Play, Sound.Stop, Sound.Pause and Sound.Resume) do to Sound.Playing and Sound.TimePosition.
-- create a sound
local sound = Instance.new("Sound", game.Workspace)
sound.SoundId = "rbxassetid://9120386436"
if not sound.IsLoaded then
sound.Loaded:Wait()
end
-- listen for events
sound.Played:Connect(function(_soundId)
print("Sound.Played event")
end)
sound.Paused:Connect(function(_soundId)
print("Sound.Paused event")
end)
sound.Resumed:Connect(function(_soundId)
print("Sound.Resumed event")
end)
sound.Stopped:Connect(function(_soundId)
print("Sound.Stopped event")
end)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
task.wait(10)
sound:Pause()
print("pause", sound.Playing, sound.TimePosition) -- pause false 10
task.wait(3)
sound:Resume()
print("play", sound.Playing, sound.TimePosition) -- play true 10
task.wait(3)
sound:Stop()
print("stop", sound.Playing, sound.TimePosition) -- stop false 0
task.wait(3)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
Resumed
Incêndios quando o Sound é retomado usando Resume() .
Parâmetros
Amostras de código
This sample gives a simple demonstration of what each of the Sound functions (Sound.Play, Sound.Stop, Sound.Pause and Sound.Resume) do to Sound.Playing and Sound.TimePosition.
-- create a sound
local sound = Instance.new("Sound", game.Workspace)
sound.SoundId = "rbxassetid://9120386436"
if not sound.IsLoaded then
sound.Loaded:Wait()
end
-- listen for events
sound.Played:Connect(function(_soundId)
print("Sound.Played event")
end)
sound.Paused:Connect(function(_soundId)
print("Sound.Paused event")
end)
sound.Resumed:Connect(function(_soundId)
print("Sound.Resumed event")
end)
sound.Stopped:Connect(function(_soundId)
print("Sound.Stopped event")
end)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
task.wait(10)
sound:Pause()
print("pause", sound.Playing, sound.TimePosition) -- pause false 10
task.wait(3)
sound:Resume()
print("play", sound.Playing, sound.TimePosition) -- play true 10
task.wait(3)
sound:Stop()
print("stop", sound.Playing, sound.TimePosition) -- stop false 0
task.wait(3)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
Stopped
Incêndios quando o Sound é interrompido ao usar Stop(). Destruir um som enquanto ele está tocando não fará com que esse evento seja Iniciar / executar.
Parâmetros
Amostras de código
This sample gives a simple demonstration of what each of the Sound functions (Sound.Play, Sound.Stop, Sound.Pause and Sound.Resume) do to Sound.Playing and Sound.TimePosition.
-- create a sound
local sound = Instance.new("Sound", game.Workspace)
sound.SoundId = "rbxassetid://9120386436"
if not sound.IsLoaded then
sound.Loaded:Wait()
end
-- listen for events
sound.Played:Connect(function(_soundId)
print("Sound.Played event")
end)
sound.Paused:Connect(function(_soundId)
print("Sound.Paused event")
end)
sound.Resumed:Connect(function(_soundId)
print("Sound.Resumed event")
end)
sound.Stopped:Connect(function(_soundId)
print("Sound.Stopped event")
end)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0
task.wait(10)
sound:Pause()
print("pause", sound.Playing, sound.TimePosition) -- pause false 10
task.wait(3)
sound:Resume()
print("play", sound.Playing, sound.TimePosition) -- play true 10
task.wait(3)
sound:Stop()
print("stop", sound.Playing, sound.TimePosition) -- stop false 0
task.wait(3)
sound:Play()
print("play", sound.Playing, sound.TimePosition) -- play true 0