How to Trim the First and Last 2 Seconds of an MP4 Video Using ffmpeg on Linux
To trim the video, it provides a command:
ffmpeg -i input.mp4 -ss 2 -t $(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 input.mp4 | awk '{print $1 - 4}') -c copy output.mp4
Here's a breakdown:
-i input.mp4
: Specifies the input file.-ss 2
: Trims starting from 2 seconds into the video.-t $(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 input.mp4 | awk '{print $1 - 4}')
: Specifies the duration to trim. It uses ffprobe to determine the video's duration and subtracts 4 seconds (2 from the start and 2 from the end) using awk.-c copy
: Copies video and audio codecs without re-encoding to preserve original quality and speed up the process.output.mp4
: Specifies the output file.
Trim a video inbetween certain timestamps. For example trim a video called twentytwoseconds.mp4
which is 22 seconds long and you want to cut off the first 5 seconds and the last 3 seconds:
ffmpeg -i twnty.mp4 -ss 00:00:05 -to 00:00:22 -c:v copy -c:a copy output.mp4
-i twnty.mp4
: Specifies the input file.-ss 00:00:05
: Specifies the start time to trim.-to 00:00:22
: Specifies the end time to trim.-c:v copy -c:a copy
: Copies video and audio codecs without re-encoding to preserve original quality and speed up the process.output.mp4
: Specifies the output file.
Leaving you with a video that is 14 seconds long.
To create a blank mp4 file to test this with you can run
ffmpeg -f lavfi -i color=c=black:s=1280x720:r=30:d=22 -c:v libx264 -preset ultrafast -tune stillimage -pix_fmt yuv420p twentytwo.mp4
where d=22
is the duration of the video in seconds.
twntytwo.mp4 is the filename
1280x720 is the resolution of the video