Fading an audio of a specific time period

Hi - I’m working on a sound system for my game and I’ve ran into this pretty simple issue. How would I create a function that fades out an audio but over a specified time (say 2 seconds, for example)? All my sounds are all at different volumes too so that is what complicates it.

function fadeAudio(audio, fadeTime)
    local before = audio.Volume
    local timeVar = fadeTime * 1000
    for i = 0, timeVar, 1 do
        local y = before - (i / (timeVar / before))
        audio.Volume = y
        wait()
    end
    audio:Stop()
    audio.Volume = before
end

I created this function and it fades it smoothly but not over the time specified with the fadeTime variable.


Any help would be great!

Unless you explicitly have a reason for avoiding TweenService, I’d probably do something like this since it calculates the step interval needed to achieve a smooth transition. There should only be abrupt stops in the event that the sound ends while the tween is playing.

local TweenService = game:GetService("TweenService")

local Properties = {Volume = 0}

local function FadeOut(Sound, Duration)
	local Initial = Sound.Volume
	local Tween = TweenService:Create(Sound, TweenInfo.new(Duration), Properties)
	Tween:Play()
	
	Tween.Completed:Connect(function()
		Sound:Stop()
		Sound.Volume = Initial
	end)
end
3 Likes

Haha, I COMPLETELY forgot about TweenService (and I use it in my game all the time). Thanks a lot!

1 Like