Last active
February 24, 2022 08:40
-
-
Save danthemango/a0857136f9b539301d0bda272a3ca3ad to your computer and use it in GitHub Desktop.
Bash script to dowload a video section by timestamp via youtube-dl and ffmpeg (works for youtube, twitch, etc.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
function printUsage() { | |
echo "usage: bash $0 -i <inurl> -ss <starttime> -t <duration> -o <outfile>" | |
echo ' other args are passed directly to youtube-dl; eg, -r 40K' | |
} | |
if [ "$#" -eq 0 ]; then | |
printUsage | |
exit | |
fi | |
# fetch command-line arguments | |
starttime= | |
duration= | |
inurl= | |
otherargs= | |
outfile= | |
copy="-c copy" | |
while [ $# -gt 0 ]; do | |
# echo "debug arg $1 $2" | |
if [ "$1" == "-h" ] || [ "$1" == "--h" ]; then | |
echo "Downloads a portion of a youtube video or twitch VOD" | |
printUsage | |
exit | |
elif [[ $1 == "-i" ]]; then | |
inurl="$2" | |
shift | |
shift | |
elif [[ $1 == "-ss" ]]; then | |
starttime="-ss $2" | |
shift | |
shift | |
elif [[ $1 == "-t" ]]; then | |
duration="-t $2" | |
shift | |
shift | |
elif [[ $1 == "-o" ]]; then | |
outfile="$2" | |
shift | |
shift | |
elif [[ $1 == "--reencode" ]]; then | |
copy="" | |
shift | |
else | |
otherargs+="$1" | |
shift | |
fi | |
done | |
# mandatory arg check | |
if [[ -z "${inurl// }" ]]; then | |
echo "Error: missing inurl" | |
printUsage | |
elif [[ -z "${outfile// }" ]]; then | |
echo "Error: missing outfile" | |
printUsage | |
fi | |
printf "Saving to: %s ...\n" "$outfile" | |
ydlcmd="youtube-dl -g $inurl $otherargs" | |
echo "=> $ydlcmd" | |
streamurl=$(eval $ydlcmd) | |
echo "<= $streamurl" | |
if [[ -z "${outfile// }" ]]; then | |
outfile="$(youtube-dl --get-outfile -f best $otherargs "$inurl")" | |
fi | |
tmp=IFS | |
IFS=" " | |
inputstr="" | |
sources=($(echo "$streamurl" | tr '\n' ' ')) | |
for source in "${sources[@]}" | |
do | |
inputstr+=" -i \"$source\" " | |
done | |
cmd="ffmpeg -loglevel warning -hide_banner -stats $starttime $inputstr $copy $duration \"$outfile\"" | |
echo "=> $cmd" | |
eval $cmd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment