Audio zone Script broken

I tried using roblox AI to help with this and it didnt help

local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")

local union = Workspace.Folders.Buildings["Dance Party"]["MusicPlayer Union"]
local musicSound = union:FindFirstChild("Music")
local hummingSound = union:FindFirstChild("Humming")

local LocalPlayer = Players.LocalPlayer

local function cloneSound(sound)
    local newSound = sound:Clone()
    newSound.Parent = LocalPlayer.Character
    return newSound
end

local playing = false
local musicClone, hummingClone

local function playAlternatingSounds()
    playing = true
    while playing do
        if musicClone and hummingClone then
            musicClone:Play()
            while musicClone.IsPlaying and playing do
                task.wait(0.1)
            end
            musicClone:Stop()
            if not playing then break end
            hummingClone:Play()
            while hummingClone.IsPlaying and playing do
                task.wait(0.1)
            end
            hummingClone:Stop()
        else
            break
        end
    end
end

local function onTouched(otherPart)
    local character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
    if otherPart:IsDescendantOf(character) and not playing then
        -- Clone sounds to character so only this player hears them
        musicClone = cloneSound(musicSound)
        hummingClone = cloneSound(hummingSound)
        playAlternatingSounds()
    end
end

local function onTouchEnded(otherPart)
    local character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
    if otherPart:IsDescendantOf(character) and playing then
        playing = false
        if musicClone then
            musicClone:Stop()
            musicClone:Destroy()
            musicClone = nil
        end
        if hummingClone then
            hummingClone:Stop()
            hummingClone:Destroy()
            hummingClone = nil
        end
    end
end

union.Touched:Connect(onTouched)
union.TouchEnded:Connect(onTouchEnded)

the script i gave for reference: 
local AreaSounds = Instance.new("Sound", script)
AreaSounds.Looped = true
local plr = script.Parent
local Presser = plr:WaitForChild("HumanoidRootPart")
local DifferentAreas = workspace:WaitForChild("Areas")
local CurrentArea = nil

game:GetService("RunService").Heartbeat:Connect(function()
 local raycast = Ray.new(Presser.Position, Presser.CFrame.UpVector * -1000)
 local part = workspace:FindPartOnRayWithWhitelist(raycast, {DifferentAreas})
 if part and part.Parent == DifferentAreas then
  if part ~= CurrentArea then
   CurrentArea = part
   AreaSounds.SoundId = CurrentArea.Sound.SoundId
   AreaSounds:Play()
  end 
 else
  CurrentArea = nil
  AreaSounds:Stop()
 end
end)

What is supposed to happen is that when the player enters the zone, two sounds should start playing one after the other, only for that player. When the player leaves the zone, the audio should stop. I made two parts into a union, and this is a LocalScript inside StarterCharacterScripts. I would really appreciate any help.

Right now, the audio plays as soon as you join the game and gets louder as you approach the area, but it does not play when the player is actually inside the zone.

asked it to use this script to fix the issue as reference which i added in the bottom of the block above

1 Like

What kind of script is this being ran in? Is it a server or a local script? And if it’s local, is it a LocalScript object or a Script with Local RunContext?

its a local script in characterscriptservieces

For sounds that come off of parts like for example the humming sound you should just parent sounds to the part and set RollOffMinDistance to 0, RollOffMaxDistance to however far you want it to play like 30 for example and RollOffMode to Linear.

However, for background music I recommend using my script.
Usage:

  • Create a folder in workspace called SoundRegions
  • Create a folder in soundservice called RegionSounds
  • To make your zone, create a Part, set the transparency to 1, cancollide to false, anchored to true, size to your zone and parent it to SoundRegions
  • Parent your zone sound to RegionSounds
  • Edit the table to your Zone’s name and sound’s name
local Players = game:GetService("Players")
local SoundService = game:GetService("SoundService")
local TweenService = game:GetService("TweenService")

local Player = Players.LocalPlayer

local SoundRegions = workspace:WaitForChild("SoundRegions")
local RegionSounds = SoundService:WaitForChild("RegionSounds")

local RegionNames = {
	["LobbyRegion"] = "Saferoom",
	["HallwayRegion"] = "Hallway Ambience",
	["ElevatorRegion"] = "Elevator"
}

local Tween = function (Object, Time, Style, Direction, Property)
	return TweenService:Create(Object, TweenInfo.new(Time, Enum.EasingStyle[Style], Enum.EasingDirection[Direction]), Property)
end

local Regions = {}
for key, x in next, RegionNames do
	Regions[key] = {
		Part = SoundRegions:WaitForChild(key),
		Sound = RegionSounds:WaitForChild(x)
	}
end

local OverlapParameters = OverlapParams.new()
OverlapParameters.FilterDescendantsInstances = {Player.Character}
OverlapParameters.FilterType = Enum.RaycastFilterType.Include
OverlapParameters.MaxParts = 1

while task.wait(1) do
	local InRegion = false

	if Player.Character ~= nil then
		OverlapParameters.FilterDescendantsInstances = {Player.Character}
	end

	for key, x in next, Regions do
		local Parts = workspace:GetPartsInPart(x.Part, OverlapParameters)

		if #Parts > 0 then
			InRegion = true
			if not x.Sound.IsPlaying then
				for _, Sound in next, RegionSounds:GetChildren() do
					if Sound ~= x.Sound and Sound.IsPlaying then
						task.spawn(function()
							local VolumeTween = Tween(Sound, 1, "Quad", "Out", {Volume = 0})
							VolumeTween:Play()
							VolumeTween.Completed:Wait()
							Sound:Stop()
						end)
					end
				end

				if x.Sound.Volume < 0.25 then
					local VolumeTween = Tween(x.Sound, 1, "Quad", "Out", {Volume = 0.25})
					VolumeTween:Play()
				end

				x.Sound:Play()
			end
		end
	end

	if not InRegion then
		for _, Sound in next, RegionSounds:GetChildren() do
			if Sound.IsPlaying then
				task.spawn(function()
					local VolumeTween = Tween(Sound, 1, "Quad", "Out", {Volume = 0})
					VolumeTween:Play()
					VolumeTween.Completed:Wait()
					Sound:Stop()
				end)
			end
		end
	end
end

1 Like



The background song starts playing when the player is in the zone; however, it doesn’t stop until the sound finishes after the player leaves the zone. Also how would I be able to add multiple songs play randomly in that zone? Thank you.**
the script is a local script in StarterCharacterScripts

Put it in replicatedfirst and to add multiple playing sounds just add the name of your zone part again with a different sound name. It’s fully zone based I’m going to make an edit to the script above so it doesn’t play when you’re not in a zone.

1 Like

Thank you, bro. I have a question. Why should it be placed in ReplicatedFirst instead of StarterCharacterScripts since it works in there too? And also, how did you get so good at scripting? Any tips?

1 Like

Well it doesn’t necessarily need to always auto update since it uses only the current Player.Character and I got good at scripting from years of practice with making my own scripts by learning from random videos or going through the devforum to find stuff and see if I could rescript it by scratch and it worked out well for me

1 Like

Also, in the code. It keeps only playing one audio. It doesn’t change to the other.

local Players = game:GetService("Players")
local SoundService = game:GetService("SoundService")
local TweenService = game:GetService("TweenService")

local Player = Players.LocalPlayer

local SoundRegions = workspace:WaitForChild("SoundRegions")
local RegionSounds = SoundService:WaitForChild("RegionSounds")

local RegionNames = {
	-- ["region name"] = "sound name"
	["MusicPlayer Union"] = "Humming5",
	["MusicPlayer Union"] = "Humming",
	["MusicPlayer Union"] = "Humming2",
	["MusicPlayer Union"] = "Humming4",
	["MusicPlayer Union"] = "Humming3"
}

local Tween = function (Object, Time, Style, Direction, Property)
	return TweenService:Create(Object, TweenInfo.new(Time, Enum.EasingStyle[Style], Enum.EasingDirection[Direction]), Property)
end

local Regions = {}
for key, x in next, RegionNames do
	Regions[key] = {
		Part = SoundRegions:WaitForChild(key),
		Sound = RegionSounds:WaitForChild(x)
	}
end

local OverlapParameters = OverlapParams.new()
OverlapParameters.FilterDescendantsInstances = {Player.Character}
OverlapParameters.FilterType = Enum.RaycastFilterType.Include
OverlapParameters.MaxParts = 1

while task.wait(1) do
	local InRegion = false

	for key, x in next, Regions do
		local Parts = workspace:GetPartsInPart(x.Part, OverlapParameters)

		if #Parts > 0 then
			InRegion = true
			if not x.Sound.IsPlaying then
				for _, Sound in next, RegionSounds:GetChildren() do
					if Sound ~= x.Sound and Sound.IsPlaying then
						task.spawn(function()
							local VolumeTween = Tween(Sound, 1, "Quad", "Out", {Volume = 0})
							VolumeTween:Play()
							VolumeTween.Completed:Wait()
							Sound:Stop()
						end)
					end
				end

				if x.Sound.Volume < 0.25 then
					local VolumeTween = Tween(x.Sound, 1, "Quad", "Out", {Volume = 0.25})
					VolumeTween:Play()
				end

				x.Sound:Play()
			end
		end
	end

	if not InRegion then
		for _, Sound in next, RegionSounds:GetChildren() do
			if Sound.IsPlaying then
				task.spawn(function()
					local VolumeTween = Tween(Sound, 1, "Quad", "Out", {Volume = 0})
					VolumeTween:Play()
					VolumeTween.Completed:Wait()
					Sound:Stop()
				end)
			end
		end
	end
end

Only one audio plays from here. What should I tweak?

Update asked ChatGPT to help and it gave me this:

local Players = game:GetService("Players")
local SoundService = game:GetService("SoundService")
local TweenService = game:GetService("TweenService")

local Player = Players.LocalPlayer

local SoundRegions = workspace:WaitForChild("SoundRegions")
local RegionSounds = SoundService:WaitForChild("RegionSounds")

-- FIX: Each region gets a LIST of sounds
local RegionNames = {
	["MusicPlayer Union"] = {
		"Humming",
		"Humming2",
		"Humming3",
		"Humming4",
		"Humming5"
	}
}

local Tween = function(Object, Time, Style, Direction, Property)
	return TweenService:Create(
		Object,
		TweenInfo.new(Time, Enum.EasingStyle[Style], Enum.EasingDirection[Direction]),
		Property
	)
end

-- Convert region names + sound lists into usable data
local Regions = {}
for regionName, soundList in next, RegionNames do
	Regions[regionName] = {
		Part = SoundRegions:WaitForChild(regionName),
		Sounds = {}
	}

	for _, soundName in ipairs(soundList) do
		table.insert(Regions[regionName].Sounds, RegionSounds:WaitForChild(soundName))
	end
end

local OverlapParameters = OverlapParams.new()
OverlapParameters.FilterDescendantsInstances = {Player.Character}
OverlapParameters.FilterType = Enum.RaycastFilterType.Include
OverlapParameters.MaxParts = 1

local currentSound = nil

while task.wait(1) do
	local inRegion = false

	for regionName, regionData in next, Regions do
		local parts = workspace:GetPartsInPart(regionData.Part, OverlapParameters)

		if #parts > 0 then
			inRegion = true

			-- pick a random sound if none is active
			if not currentSound or not currentSound.IsPlaying then
				local randomSound = regionData.Sounds[math.random(1, #regionData.Sounds)]
				currentSound = randomSound

				-- stop all other sounds
				for _, s in next, regionData.Sounds do
					if s ~= currentSound and s.IsPlaying then
						local tween = Tween(s, 1, "Quad", "Out", {Volume = 0})
						tween:Play()
						tween.Completed:Wait()
						s:Stop()
					end
				end

				-- fade in the new sound
				currentSound.Volume = 0
				currentSound:Play()
				Tween(currentSound, 1, "Quad", "Out", {Volume = 0.25}):Play()
			end
		end
	end

	if not inRegion then
		if currentSound then
			local tween = Tween(currentSound, 1, "Quad", "Out", {Volume = 0})
			tween:Play()
			tween.Completed:Wait()
			currentSound:Stop()
			currentSound = nil
		end
	end
end

Can you please tell me why the original one didn’t work?

Oh right, my bad, the original doesn’t work because of one single condition I set where it checks for more than one sound being played and if there is one then it just mutes all sounds to have only one play. Terribly sorry about that, this was a script meant for my game only :sob:

Alright, no problem bro. I really appreciate it. This was very helpful. Btw, I have the same limited. So W face & help.

1 Like

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