Skip to content

Instantly share code, notes, and snippets.

@goncalomb
Created September 20, 2018 11:07
Show Gist options
  • Save goncalomb/6553c2ac5d854aee25f12dfe3fff7f30 to your computer and use it in GitHub Desktop.
Save goncalomb/6553c2ac5d854aee25f12dfe3fff7f30 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Partial YouTube downloader (bash script for Windows).
# goncalomb (goncalomb.com), 2018
set -e
cd "$(dirname -- "$0")"
[ -f "youtube-dl.exe" ] || {
echo "Downloading youtube-dl..."
curl -ROL#C - "https://yt-dl.org/downloads/2018.09.18/youtube-dl.exe"
echo
}
[ -f "ffmpeg.exe" ] || {
echo "Downloading ffmpeg..."
curl -ROL#C - "https://ffmpeg.zeranoe.com/builds/win64/static/ffmpeg-20180917-bd10c1e-win64-static.zip"
unzip -jo ffmpeg-*.zip ffmpeg-20180917-bd10c1e-win64-static/bin/ffmpeg.exe
echo
}
format_time() { echo "$1s" | sed -e 's/\(.*\):/\1m/' -e 's/\(.*\):/\1h/'; }
if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then
echo "usage: $0 <youtube-url> <start> <duration> [-t]"
echo " -t transcode video for perfect slicing (slower)"
echo "start/duration format: 00:00:00 (h:m:s) or 00:00 (m:s) or 00 (s)"
exit
fi
DIR="videos"
mkdir -p "$DIR"
TRANSCODE=
CODEC="-c copy"
if [ "$4" == "-t" ]; then
TRANSCODE="-transcoded"
CODEC=""
else
echo "Not transcoding! Video slicing may not be perfect, use -t to enable transcoding (slower)."
fi
echo "Fetching video urls..."
URLS=$(./youtube-dl.exe -g "$1")
URL_VIDEO=$(echo "$URLS" | sed '1q;d')
URL_AUDIO=$(echo "$URLS" | sed '2q;d')
echo "Fetching video name..."
FILENAME=$(./youtube-dl.exe --get-filename "$1")
FILENAME="$DIR/${FILENAME%.*}-$(format_time "$2")($(format_time "$3"))$TRANSCODE.mkv"
echo "Saving to '$FILENAME'..."
./ffmpeg.exe -hide_banner -loglevel info -y -ss "$2" -i "$URL_VIDEO" -ss "$2" -i "$URL_AUDIO" -t "$3" $CODEC -map "0:v:0" -map "1:a:0" "$FILENAME"
echo
echo "Saved '$FILENAME'."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment