Making part pulse to beat with sound

Hello I am trying to make my part pulse to beat of my music in my game but I am having trouble with either the timing or the code itself. I want the part to mostly only change to the beat but with the code that I have, it just changes to everything. At first it seems like it is working to the beat but it just loops over and over again at the same timing and everything. Is it possible to achieve what I am trying to achieve??

task.wait(2)
print("STarTING")

local runService = game:GetService("RunService")
local sound = game.Workspace.Sound
local part = game.Workspace.Part

local loudnessValues = {}
local running = false
game:GetService("RunService").Heartbeat:Connect(function()
	local average = 0

	--visualizing code basted on isBeat etc.
	loudnessValues[#loudnessValues + 1] = sound.PlaybackLoudness
	
	for _,v in ipairs(loudnessValues) do
		average = average + v
	end

	average = average / #loudnessValues
	local isBeat = sound.PlaybackLoudness >= average
	local test = math.random(1,12)
	if isBeat then
		--if test == 6 then
			if running == false then
				running = true

				local loudness = sound.PlaybackLoudness
				local maxLoudness = 1000 -- You can adjust this value for the maximum loudness
				local percentLoud = loudness / maxLoudness
				local invertRes = 1 - percentLoud

				part.Transparency = invertRes
				print("ok")
				local tweenInfo = TweenInfo.new(
					1,  -- Duration of the tween in seconds
					Enum.EasingStyle.Quad,  -- Easing style for the tween (you can experiment with different styles)
					Enum.EasingDirection.Out  -- Easing direction for the tween
				)
				local test = game.TweenService:Create(part, tweenInfo, { Transparency = 1 })
				test:Play()
				test.Completed:Wait()
				task.wait()
				running = false
			end
		--end
	end
end)


sound:Play()



4 Likes

You might’ve overcomplicated this process; I tried this on my own workspace using a GUI Frame and it performed well.

Consider removing the tweens, RunService will update the part every frame meaning it’ll almost replicate the linear process of a tween.

local RunService = game:GetService("RunService")
local Sound: Sound = ... -- Your sound part.

local function Stepped(dt: number): boolean
	local PlaybackLoudness = Sound.PlaybackLoudness
	workspace.Part.Size = Vector3.new(1, PlaybackLoudness/100, 1)
	workspace.Part.Transparency = 1 - (PlaybackLoudness/1000)
	return true
end

RunService.Stepped:Connect(Stepped)
Sound:Play()

You can view this being demonstrated on this .RBXL file:

SoundDancePart.rbxl (43.5 KB)

1 Like

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