Let's just say i was trying to learn how to better use ffmpeg, and started asking myself "What are the things i needed when working with video content?".
And this is one of the things that came to mind. A simple way to extract a clip from an starting point and length of a video file, and exporting that into another video file with minimal quality loss.
Here are some ways on how i managed to do exactly that.
Using ffmpeg
#!/usr/bin/env bash
INPUT_FILEPATH="${1}"
START_TIME="${2}"
CLIP_DURATION_TIME="${3}"
DEFAULT_OUTPUT_FILEPATH="$(dirname ${INPUT_FILEPATH})/Clip ${START_TIME//:/}-${CLIP_DURATION_TIME//:/} $(basename ${INPUT_FILEPATH})"
OUTPUT_FILEPATH="${4:-${DEFAULT_OUTPUT_FILEPATH}}"
ffmpeg \
-ss "${START_TIME}" \
-i "${INPUT_FILEPATH}" \
-t "${CLIP_DURATION_TIME}" \
-c copy \
"${OUTPUT_FILEPATH}"
The Bash script takes 4 arguments in total, with the last being optional:
- The 1. is the filepath to the video file.
- The 2. is the starting time, from which to extract the clip. The expected input format is
HH:MM:SS, meaning hours, minutes and seconds with exactly two digits. - The 3. is the duration of the clip. The expected input format is
HH:MM:SS, meaning hours, minutes and seconds with exactly two digits. - The 4. is the output filepath of the exported clip. If not set, will use the filename template
<inputfile parent directory path>/Clip <START_TIME without : character>-<CLIP_DURATION_TIME without : character> <filename>.
Using MoviePy
This approach uses the MoviePy Python3 library, which is pretty good for scripting general purpose video editing.
Adapt the Python v3 script to your needs.
#!./venv/bin/python3
from pathlib import Path
from moviepy import VideoFileClip
def cut_and_save_clip(input_filepath, start_time, end_time, clip_name = "new clip", save_thumbnail = False) -> None:
"""
API needs to be better thought out. But POC works good enough.
"""
input_filepath = Path(input_filepath)
clip_output_filepath = input_filepath.with_stem(clip_name)
with VideoFileClip(input_filepath) as source_clip:
new_clip = source_clip.subclipped(
start_time=start_time,
end_time=end_time,
)
if save_thumbnail:
new_clip.save_frame(clip_output_filepath.with_suffix(".png"), t=start_time)
new_clip.write_videofile(clip_output_filepath)
cut_and_save_clip(
input_filepath="./test.mp4",
start_time=(0, 11),
end_time=(0, 59),
clip_name="clip",
save_thumbnail=True,
)