Apply Volume Envelope to Audio Using FFmpeg
This article provides a quick guide on how to apply a volume envelope
to an audio file using FFmpeg. You will learn how to use the
volume audio filter with time-based expressions to
dynamically adjust audio levels over time, allowing you to create custom
fades, ducking effects, and precise volume transitions.
To apply a volume envelope in FFmpeg, you must use the
volume filter paired with the eval=frame
option. By default, FFmpeg evaluates the volume expression only once at
the beginning of the file. Setting eval=frame forces FFmpeg
to re-evaluate the volume mathematical expression for every single audio
frame, enabling smooth volume changes over time using the variable
t (time in seconds).
Method 1: Linear Fade-In and Fade-Out
If you want to create a standard volume envelope that fades the audio in and out, you can use mathematical conditional statements.
To fade in the audio over the first 5 seconds:
ffmpeg -i input.mp3 -af "volume='if(lt(t,5),t/5,1)':eval=frame" output.mp3- How it works: If the current time
tis less than 5 seconds (lt(t,5)), the volume scales linearly from 0 to 1 (t/5). Otherwise, the volume remains at its original level (1).
To fade out the audio during the last 5 seconds of a known 30-second track:
ffmpeg -i input.mp3 -af "volume='if(gt(t,25),1-(t-25)/5,1)':eval=frame" output.mp3Method 2: Dynamic Volume Ducking
You can create a volume envelope that “ducks” (lowers) the audio level during a specific time range—for example, to make room for a voiceover between seconds 10 and 20.
ffmpeg -i input.mp3 -af "volume='if(between(t,10,20),0.2,1)':eval=frame" output.mp3- How it works: The
between(t,10,20)function checks if the current time is between 10 and 20 seconds. If true, the volume is reduced to 20% (0.2). If false, the volume remains at 100% (1).
Method 3: Smooth S-Curve (Sigmoid) Envelope
For a more natural-sounding volume transition than a linear fade, you can use trigonometric functions like cosine to create a smooth S-curve envelope.
To smoothly fade out audio from second 10 to second 15:
ffmpeg -i input.mp3 -af "volume='if(lt(t,10),1,if(gt(t,15),0,0.5*(1+cos(PI*(t-10)/5))))':eval=frame" output.mp3- How it works: Before 10 seconds, the volume is
1. After 15 seconds, the volume is0. Between 10 and 15 seconds, a cosine function calculates a smooth, non-linear decline from1to0.