Skip to content

Instantly share code, notes, and snippets.

@fonic
Last active July 18, 2024 08:30
Show Gist options
  • Save fonic/77c8a82ea6b502600c5af1c735476225 to your computer and use it in GitHub Desktop.
Save fonic/77c8a82ea6b502600c5af1c735476225 to your computer and use it in GitHub Desktop.
Extract clip from video using FFmpeg
#!/usr/bin/env bash
# ------------------------------------------------------------------------------
# -
# Extract clip from video -
# -
# Created by Fonic <https://github.com/fonic> -
# Date: 04/21/24 - 04/21/24 -
# -
# Source: -
# https://gist.github.com/fonic/77c8a82ea6b502600c5af1c735476225 -
# -
# Based on: -
# https://superuser.com/a/1752195/1108818 -
# -
# ------------------------------------------------------------------------------
# Set up error handling
set -ue; trap "echo -e \"\e[1;31mError: an unhandled error occurred on line \${LINENO}, aborting.\e[0m\"; exit 1" ERR
# Process command line
if (( $# != 4 )); then
echo
echo -e "\e[1mUsage:\e[0m ${0##*/} INFILE START DURATION OUTFILE"
echo
echo -e "\e[1mNote:\e[0m"
echo "Two formats are supported for arguments START and DURATION:"
echo "Format 1: 'HH:MM:SS[.MS]' -> hours + minutes + seconds [+ optional fraction]"
echo " (e.g. '00:07:38.123', '01:02:03')"
echo "Format 2: 'XX[.F][s|ms|us]' -> secs, millisecs or microsecs [+ optional fraction]"
echo " (e.g. '7.2s', '800ms', '123.6us')"
echo
exit 2
fi
INFILE="$1"
START="$2"
DURATION="$3"
OUTFILE="$4"
# Extract clip from video (NOTE: first line DISCARDS original metadata, second
# line KEEPS original metadata)
#ffmpeg -i "${INFILE}" -ss "${START}" -t "${DURATION}" -c copy "${OUTFILE}" || echo -e "\e[1;31mError: failed to extract clip from '${INFILE}'\e[0m"
ffmpeg -i "${INFILE}" -ss "${START}" -t "${DURATION}" -c copy -movflags use_metadata_tags -map_metadata 0 "${OUTFILE}" || echo -e "\e[1;31mError: failed to extract clip from '${INFILE}'\e[0m"
@fonic
Copy link
Author

fonic commented Apr 21, 2024

Usage:

Usage: extract-clip-from-video.sh INFILE START DURATION OUTFILE

Note:
Two formats are supported for arguments START and DURATION:
Format 1: 'HH:MM:SS[.MS]'    ->  hours + minutes + seconds [+ optional fraction]
                                 (e.g. '00:07:38.123', '01:02:03')
Format 2: 'XX[.F][s|ms|us]'  ->  secs, millisecs or microsecs [+ optional fraction]
                                 (e.g. '7.2s', '800ms', '123.6us')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment