Skip to content

Instantly share code, notes, and snippets.

@riyad riyad/ffmpeg-cut
Last active Nov 17, 2018

Embed
What would you like to do?
Cut out a part of a media file within the given time stamps (without converting or reencoding!)
#!/bin/bash
#
# Author: Riyad Preukschas <riyad@informatik.uni-bremen.de>
# License: Mozilla Public License 2.0
#
# Cuts out a part of a media file within the given time stamps (without converting or reencoding!).
set -o nounset # complain when reading unset vars
# set -o xtrace # print every command as it's executed
usage() {
echo "Error: wrong number of arguments"
echo "Usage: $0 [--from <from_time>] [--to <to_time>] <input_file> [<output_file>]"
echo " will cut out a part of a media file within the given time stamps"
echo " (without converting or reencoding!)."
echo ""
echo "OPTIONS"
echo " --from <from_time>"
echo " --to <to_time>"
echo " specify the times from/to the file should be cut."
echo " (e.g. \"00:01:25\")"
}
parse_command_line_args() {
OPT_FROM_TIME=''
OPT_TO_TIME=''
OPT_INPUT_FILE=''
OPT_OUTPUT_FILE=''
if [[ $# -lt 3 || $# -gt 6 ]]; then
usage
exit 1
fi
while [[ $# -gt 2 ]]
do
case "$1" in
--from)
readonly OPT_FROM_TIME="$2"
shift
;;
--to)
readonly OPT_TO_TIME="$2"
shift
;;
*)
echo "Error: unknown argument \"$1\""
usage
exit 1
;;
esac
shift
done
readonly OPT_INPUT_FILE="$1"
shift
# if the input file doesn't exists ffmpeg will complain anyway
if [[ $# -gt 0 ]]; then
readonly OPT_OUTPUT_FILE="$1"
shift
else
local filename
filename=$(basename -- "$OPT_INPUT_FILE")
readonly OPT_OUTPUT_FILE="$(dirname "${OPT_INPUT_FILE}")/${filename%.*}.ffmpeg-cut.${filename##*.}"
fi
# if the output file exists ffmpeg will ask whether it should be overwritten
}
main() {
parse_command_line_args "$@"
local ffmpeg_options=()
if [[ ${OPT_FROM_TIME} ]]; then
ffmpeg_options+=(-ss "${OPT_FROM_TIME}")
fi
if [[ ${OPT_TO_TIME} ]]; then
ffmpeg_options+=(-to "${OPT_TO_TIME}")
fi
ffmpeg -i "${OPT_INPUT_FILE}" -c copy "${ffmpeg_options[@]}" "${OPT_OUTPUT_FILE}"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.