Skip to content

Instantly share code, notes, and snippets.

@cocoabox
Last active September 12, 2022 05:31
Show Gist options
  • Save cocoabox/9a303450dc5ac5ed33080f02e7de0e51 to your computer and use it in GitHub Desktop.
Save cocoabox/9a303450dc5ac5ed33080f02e7de0e51 to your computer and use it in GitHub Desktop.
Download youtube music videos or playlist (with static album art) into m4a file with embedded album art. Requires ffmpeg, AtomicParsley, yt-dlp
#!/bin/bash
if [[ -z "$1" ]]; then
echo "usage : $0 [YOUTUBE_URL_OR_ID]" >&2
exit 1
fi
OK=1
ffmpeg >/dev/null 2>/dev/null
if [[ $? -eq 127 ]]; then
echo "ffmpeg is required : https://ffmpeg.org/download.html" >&2
OK=0
fi
AtomicParsley >/dev/null 2>/dev/null
if [[ $? -eq 127 ]]; then
echo "AtomicParsley is required : https://github.com/wez/atomicparsley#installation" >&2
OK=0
fi
yt-dlp --version >/dev/null 2>/dev/null
if [[ $? -eq 127 ]]; then
echo "yt-dlp is required : https://github.com/yt-dlp/yt-dlp#installation">&2
OK=0
fi
jq --version >/dev/null 2>/dev/null
if [[ $? -eq 127 ]]; then
echo "jq is required : https://stedolan.github.io/jq/download/" >&2
OK=0
fi
[[ $OK -eq 0 ]] && exit 1
set -e
WD="$PWD"
DIR=""
clean_up() {
set +e
ARG=$?
popd >/dev/null 2>/dev/null
rm -Rf "$DIR" 2>/dev/null
exit $ARG
}
trap clean_up EXIT
PLAYLIST="$1"
while [[ ! -z "$PLAYLIST" ]]; do
echo "==> `tput bold`$PLAYLIST`tput sgr0`" >&2
URLS=$(yt-dlp --dump-json "$PLAYLIST" | jq -r '.original_url' | jq -rR --slurp '. | split("\n") | join(" ")' )
for YOUTUBE in $URLS; do
echo "==> `tput setaf 2; tput setab 0; tput bold`$YOUTUBE`tput sgr0`" >&2
DIR=$(mktemp -d)
pushd "$DIR" >/dev/null
yt-dlp -f "bestaudio[ext=m4a]" "$YOUTUBE"
FILES_COUNT=$(ls -1 | wc | awk '{print $1}')
M4A=$(ls -1 | head -n1)
if [[ "$FILES_COUNT" -gt 1 ]]; then
echo "`tput setaf 1; tput setab 0`WARNING: more than one files downloaded. This script can only process one file at a time`tput sgr0`" >&2
echo "`tput bold`Processing : $M4A`tput sgr0`" >&2
fi
echo "==> getting JSON" >2
JSON=$(yt-dlp --dump-json "$YOUTUBE")
# album art (first frame)
echo -e "\r$(tput el)==> setting album metadata"
VID_TEMP="temp-vid.mp4"
ART="art.jpg"
yt-dlp -f "bestvideo[ext=mp4]" \
--embed-metadata \
--output "$VID_TEMP" "$YOUTUBE"
ffmpeg -loglevel error -i "$VID_TEMP" -vf "select=eq(n\,0)" -q:v 3 "$ART"
if [[ $? -ne 0 ]]; then
echo "==> failed to download art" >&2
ART=""
fi
ALBUM="$(echo "$JSON" | jq -r .album)"
ARTIST="$(echo "$JSON" | jq -r .artist)"
TITLE="$(echo "$JSON" | jq -r .title)"
AtomicParsley "$M4A" \
--artwork "$ART" \
--artist "$ARTIST" \
--title "$TITLE" \
--album "$ALBUM" \
--comment "$YOUTUBE" \
--overWrite
echo "" >&2
mv -v "$M4A" "$WD"
rm -Rf "$DIR"
popd >/dev/null
done
shift
PLAYLIST="$1"
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment