Any way to generate an audio waveform in a UI?

I’m currently trying to generate an audio waveform using a for loop and PlaybackLoudness, however I’m stuck, as it just gives me useless values every time as can be seen below.

The blue lines are supposed to vary in height depending on the PlaybackLoudness fetched by my GetWaveformSamples function, which is scripted as follows:

local WaveformSamples = {}
local WaveformSampleCount = 256
local CurrentTime = 0

local function GetWaveformSamples()
	local interval = Deck1Sound.TimeLength / WaveformSampleCount
	local soundPart = Deck1Sound:Clone()
	local soundPosPart = Instance.new("Part")
	soundPosPart.Position = Vector3.new(6969,6969,6969)
	soundPart.Parent = soundPosPart
	soundPosPart.Parent = workspace
	soundPart:Play()
	for i = 1, WaveformSampleCount do
		soundPart.TimePosition = CurrentTime
		task.desynchronize()
		task.wait()
		local sample = soundPart.PlaybackLoudness / 500
		table.insert(WaveformSamples, sample)
		CurrentTime = CurrentTime + interval
		task.synchronize()
	end
	soundPart:Stop()
end

This code attempts to iterate 256 times (determined by WaveformSampleCount) and generate a number between 0 and 1 by using PlaybackLoudness / 500 after setting TimePosition (since most songs tested don’t exceed the PlaybackLoudness value of 500, and if they do, I can always clamp it later.)

This code seems to “work”, as in, no errors are printed into the console, but the problem is there’s no actual useful values associated with it, because with my bar graph drawing code, I don’t see any useful bars being rendered, as you saw above with the flat lines.

This is my DrawWaveform code, which also should work just fine.

local function DrawWaveform(parent: GuiObject, autosize: boolean, samples)
	for i,v in ipairs(samples) do
		local size = UDim2.fromScale(1 / WaveformSampleCount, v)
		local color = NeutralColor:Lerp(HighlightColor, v)
		
		local instance = Instance.new('Frame')
		if autosize then instance.AutomaticSize = Enum.AutomaticSize.X end
		instance.BackgroundColor3 = color
		instance.Size = size
		instance.Parent = parent
		if i % 8 == 0 then task.wait() end
	end
	TrackLoaded = true
end

Any help is appreciated with helping me make this finally work, thanks!

I don’t think PlaybackLoudness updates fast enough to be able to do this. It would have to update at the sample rate of the audio being played. Have you checked to see if this is the case?

1 Like

It’s not generating in realtime, rather, it’s only getting them once every x seconds by setting the TimePosition, to get x number of samples. It’s not trying to get them that quickly. I just want a couple of samples to use as a volume level reference. I could try adding some time to task.wait() and see if it needs a little longer to update

1 Like

Make sure you’re accessing PlaybackLoudness from a LocalScript, as it’s a client-side property. If that’s not the issue, please provide more information about the problem you’re facing.

1 Like