I need a script to cut off the last 6 seconds of multiple videos. The videos do all have different length.
I can‘t find anything helpful online.
Does anyone know
You have to use a roundabout way to achieve this,
ffmpeg -i file.mp4 -itsoffset 6 \
-i file.mp4 -c copy -map 0:a:0 -map 1 \
-shortest -f nut - | \
ffmpeg -y -i - -c copy -map 0 -map -0:0 -ss 6 trimmed.mp4
This runs two ffmpeg processes connected by a pipe, although you can do it with two ffmpeg commands run one after the another.
The first command ingests the file twice and offsets the 2nd input's timestamps by 6 seconds. It maps an audio stream from the first input and all streams from the second. The output of the first command is set to terminate with the shortest stream, which is the audio stream from the first input. The side-effect is that the last 6 seconds of the 2nd input are chopped off. In the 2nd process, all streams except the first audio stream are copied into a new container.
If you're unsure whether a file has audio, you can replace -map 0:a:0
with -map 0:0
A method that uses ffprobe
to get the input duration, bc
to calculate the desired output duration, and ffmpeg
to perform the cutting. This method does not require the inputs to contain an audio stream, but it requires two additional tools (ffprobe
and bc
) instead of just ffmpeg
.
Your preferred scripting language wasn't mentioned so I'll assume bash will do. In a script form as requested:
#!/bin/bash
for f in *.mp4; do
cut_duration=6
input_duration=$(ffprobe -v error -select_streams v:0 -show_entries stream=duration -of default=noprint_wrappers=1:nokey=1 "$f")
output_duration=$(bc <<< "$input_duration"-"$cut_duration")
ffmpeg -i "$f" -map 0 -c copy -t "$output_duration" output/"$f"
done
Or as a single line:
for f in *.mp4; do ffmpeg -i "$f" -map 0 -c copy -t "$(bc <<< "$(ffprobe -v error -select_streams v:0 -show_entries stream=duration -of default=noprint_wrappers=1:nokey=1 "$f")"-6)" output/"$f"; done
It is almost impossible to do this for windows batch files. Here is the script for the Powershell:
$ListsFiles = Get-ChildItem "D:\VIDEOS\1\" -Filter *.avi;
Foreach ($file in $ListsFiles){
$input_d = [math]::round((ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $file.Fullname));
$output_duration=$input_d-5;
$ArgumentList = '-i "{0}" -map 0 -c copy -t {1} "D:\VIDEOS\1\output\{2}"' -f $file.Fullname, $output_duration, $file;
Write-Host -ForegroundColor Green -Object $ArgumentList;
Start-Process -FilePath ffmpeg -ArgumentList $ArgumentList -Wait -NoNewWindow;
}