How to Use FFmpeg xfade Filter for Video Crossfade
This article provides a straightforward guide on how to apply a
crossfade transition between two video files using the FFmpeg
xfade filter. You will learn how the filter works, how to
calculate the correct transition timing, and how to merge both the video
and audio tracks seamlessly.
Understanding the xfade Filter
The xfade filter merges two video streams using a
transition effect. Unlike the older method of using fade
filters with overlays, xfade is faster and much easier to
configure. To use it, you need to define two primary parameters: *
duration: The length of the transition in seconds. *
offset: The exact timestamp (in seconds) in the first
video where the transition should begin.
How to Calculate the Offset
To achieve a seamless transition, the second video must start fading in before the first video ends. Use this formula to calculate the offset:
\[\text{Offset} = \text{Duration of Video 1} - \text{Transition Duration}\]
For example, if your first video is 10 seconds long and you want a 1-second crossfade: \[\text{Offset} = 10 - 1 = 9\text{ seconds}\]
The FFmpeg Command for Video Crossfade
Here is the basic command to apply a 1-second crossfade between two 10-second videos:
ffmpeg -i input1.mp4 -i input2.mp4 -filter_complex "[0:v][1:v]xfade=transition=fade:duration=1:offset=9[v]" -map "[v]" output.mp4Command Breakdown:
-i input1.mp4 -i input2.mp4: Imports the two input videos.-filter_complex: Invokes the filtergraph.[0:v][1:v]: Takes the video streams of the first and second inputs.xfade=transition=fade:duration=1:offset=9: Applies the fade transition lasting 1 second, starting at the 9-second mark of the first video.[v]: Names the output video stream.-map "[v]": Tells FFmpeg to write the processed video stream to the output file.
Adding Audio Crossfade
The xfade filter only processes video. To prevent the
audio from cutting off abruptly, you must also transition the audio
tracks using the acrossfade filter.
Here is the complete command to crossfade both video and audio:
ffmpeg -i input1.mp4 -i input2.mp4 -filter_complex "[0:v][1:v]xfade=transition=fade:duration=1:offset=9[v];[0:a][1:a]acrossfade=d=1[a]" -map "[v]" -map "[a]" output.mp4Audio Parameters:
[0:a][1:a]acrossfade=d=1[a]: Takes the audio streams from both inputs and applies an audio crossfade with a duration (d) of 1 second.-map "[a]": Maps the processed audio stream to the output file.
Alternative Transition Effects
The xfade filter supports many transitions other than a
standard fade. To use a different style, change the
transition value in the command. Some popular alternatives
include:
wipeleft/wiperight/wipeup/wipedownslideleft/slideright/slideup/slidedowncircleopen/circleclosedissolve
Simply replace transition=fade with your preferred
style, such as transition=slideleft.