Skip to content

Instantly share code, notes, and snippets.

@mhartkorn
Last active November 24, 2020 17:53
Show Gist options
  • Save mhartkorn/6f0ad9b20623951f6aa0 to your computer and use it in GitHub Desktop.
Save mhartkorn/6f0ad9b20623951f6aa0 to your computer and use it in GitHub Desktop.
Downloads a YouTube video with youtube-dl in 1080p60 (or less if no higher resolution is available) and adds the audio track with ffmpeg. Format prioritization is: Video: 1080p60 VP9, 1080p60 H.264, 720p60 VP9, 720p60 H.264, 1080p30 VP9, 1080p30 H.264, 720p30 VP9, 720p30 H.264. Audio: Opus High, M4A High, M4A Medium
#!/usr/bin/bash
TMP_DIR="/tmp/youtube-dl"
STD_ARGS="--no-part --no-playlist -c"
VIDEO_FORMATS="299/303/302/298/248/137/247/136"
AUDIO_FORMATS="251/141/140"
DIST=$RANDOM
OLD_DIR="$PWD"
for video in "$@"
do
if [ ! -d "$TMP_DIR" ]; then
mkdir -p "$TMP_DIR"
fi
cd "$TMP_DIR"
# The s after the parentheses is required by Python
youtube-dl -f $VIDEO_FORMATS -o "video-%(id)s" $STD_ARGS "$video"
youtube-dl -f $AUDIO_FORMATS -o "audio-%(id)s" $STD_ARGS "$video"
ID=$(youtube-dl -f best $STD_ARGS -o "%(id)s" --get-filename "$video")
FILENAME=$(youtube-dl -f best $STD_ARGS -t --get-filename "$video")
ffmpeg -i "video-$ID" -i "audio-$ID" -c copy "$OLD_DIR/$FILENAME.mkv"
if [ $? -eq 0 ]; then
rm -f "$TMP_DIR/video-$ID"
rm -f "$TMP_DIR/audio-$ID"
else
echo "ffmpeg returned an error. Aborting...\n"
exit 1
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment