We use cookies on this site to enhance your user experience

Music Playing Part

Music Playing Part

Oct 01 2018, 2:27 AM PST

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.

-- create a part
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 = game.Workspace

-- create a sound
local sound = Instance.new("Sound", part)
sound.SoundId = "rbxassetid://301964312" 
sound.EmitterSize = 5 -- decrease the emitter size (for earlier volume drop off)
sound.Looped = true

-- create a click detector
local clickDetector = Instance.new("ClickDetector", part)
	-- toggle the sound playing / not playing
	if not sound.IsPlaying then
		part.BrickColor = BrickColor.new("Bright green")	
		part.BrickColor = BrickColor.new("Bright red")