Segment video with ffmpeg
This article introduces how to use the ffmpeg
tool via the command line to segment videos. If you prefer a graphical interface, you can use tools like FileThings.
ffmpeg is a powerful multimedia processing tool that can handle videos, audios, and various other media files.
Segmenting Video by Specified Time Period
Command example: ffmpeg -i input.mp4 -ss start_time -to end_time -c copy output.mp4
Option explanations:
start_time
is the timestamp to start segmenting, in seconds, or in the format00:00:00.00
(hours:minutes:seconds.milliseconds).end_time
is the timestamp to end segmenting, in the same units as above.- The
-c copy
option means to directly copy the audio and video streams from the original video without re-encoding.
If specifying time in the
00:00:00.00
format, you can omit hours and minutes. For example,00:10
means the 10th second.
Or use the command ffmpeg -i in.mp4 -c copy -ss start_time -t duration out.mp4
That is, use the -t
option to specify the duration from the start time point, rather than the end time.
Evenly Segmenting Video by Specified Duration
Command example: ffmpeg -i input.mp4 -c copy -map 0 -segment_time 3 -f segment -reset_timestamps 1 output%03d.mp4
Option explanations:
-c copy
means to directly copy the audio and video streams from the original video without re-encoding.-map 0
means to map all streams, including audio, video, subtitles, etc.-segment_time 3
means each segment is 3 seconds long.-f segment
means to use segment mode, saving each segment as a separate file.-reset_timestamps 1
means to reset the timestamps of each segment, so the time in each segment file starts from 0.output%03d.mp4
specifies the format of the output file name, where%03d
is a placeholder that will be replaced by an incrementing number (e.g., output001.mp4).
Note: This mode cannot precisely segment the video by the specified duration (e.g., 3 seconds) because ffmpeg can only cut at keyframes. If there is no keyframe at the specified time point, the cut point will move forward or backward to the nearest keyframe, resulting in segments of inconsistent duration.
A possible solution is to re-encode the video and force keyframes at the specified time points to achieve precise segmentation. For example, use the -g
parameter to set the keyframe interval so that keyframes appear at the expected cut points.