Dockerized yt-dlp to download and tag mp3 files
Music streaming services provide us access to huge libraries, which is great! Algorithms study what we like and offer useful recommendations or let us discover something entirely new.
However, we can only access what has been officially released. Some "live in ${city.name}" DVD release that you enjoy might not be available on a streaming service. Occasionally, artists and labels end up in legal battles, and the content that was released in the '80s and '90s suddenly can't be distributed anymore. Over time, I started to notice that a playlist with my favorite music lost at least a third of the tracks I liked to listen to! That makes other sources of obtaining music relevant again.
YouTube is one of them. The quality is not fantastic due to irreversible compression, but there are so many live recordings, obscure releases, and covers that I find it worth it. As I store music on my home server, I needed a solution that wouldn't pollute it with hundreds and hundreds of packages. Yes, I'm looking at you, ffmpeg! Probably most tools that can download and process videos from YouTube depend on ffmpeg.
So if you too want to utilize yt-dlp in an isolated environment, I can offer the following Dockerfile:
FROM debian:bookworm
WORKDIR /music
RUN apt-get update -y && \
apt-get install -y curl python3 ffmpeg id3v2 && \
apt-get clean
RUN curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp
RUN chmod +x /usr/local/bin/yt-dlp
RUN /usr/local/bin/yt-dlp --version
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
The entrypoint:
#!/bin/bash
if [ "$#" -ne 4 ]; then
echo "Usage: $0 <url> <artist> <title> <album>"
exit 1
fi
URL="$1"
ARTIST="$2"
TITLE="$3"
ALBUM="$4"
TEMP_DIR=$(mktemp -d)
if [ ! -d "$TEMP_DIR" ]; then
echo "Failed to create temp directory"
exit 1
fi
yt-dlp -x --audio-format mp3 -o "$TEMP_DIR/%(title)s.%(ext)s" "$URL" || exit 1
MP3_FILE=$(ls "$TEMP_DIR/"*.mp3) || exit 1
id3v2 -a "$ARTIST" -t "$TITLE" -A "$ALBUM" "$MP3_FILE"
mv "$MP3_FILE" .
echo "Downloaded: $MP3_FILE"
Then build it with:
docker build -t yt-dlp .
And run using this script:
#!/bin/bash
if [ "$#" -ne 4 ]; then
echo "Usage: $0 <url> <artist> <title> <album>"
exit 1
fi
URL="$1"
ARTIST="$2"
TITLE="$3"
ALBUM="$4"
docker run --rm -v "<PATH_TO_MUSIC_LIBRARY>":/music/ yt-dlp "$URL" "$ARTIST" "$TITLE" "$ALBUM" || exit 1
Usage:
chmod +x music.sh
./music.sh "https://www.youtube.com/watch?v=dQw4w9WgXcQ" "Rick Astley" "Never Gonna Give You Up" "Never Gonna Give You Up"
This will launch a Docker container, download the video, extract the audio track, set the metadata, and move it to <PATH_TO_MUSIC_LIBRARY>
on your host. Thanks to the --rm
flag, the container will be automatically removed after the execution. Great success!