Building your MP3 music collection from YouTube

Posted on: 2024-05-01

A lot of people pay for music streaming these days using a service like Spotify or Apple Music, but this is a foreign concept for me. For decades now, since before music streaming was even a thing, I've had my own personal curated MP3 music collection that has grown over the years to thousands of tracks. It contains every song I ever listened to and liked, and these days it still grows by several files each month. In this post I will show you how I built and self-host a small app that allows me to copy a YouTube URL to a shortcut on my iPhone or iPad, and the app automatically downloads the song and saves it to my collection.

First, we'll need to install dependencies:

pip3 install Flask Flask-Cors yt-dlp connix

Then we can create a Flask app that will accept POST API calls:

#!/usr/bin/python3
# Flask app to trigger yt-dlp

from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
import subprocess
import connix

app = Flask(__name__)
CORS(app)

@app.route('/music/', methods=['GET', 'POST'])
def index():
  # Convert YouTube video to MP3

  output = {
    'status': 1,
    'message': ""
  }

  if "url" not in request.form or "artist" not in request.form or "song" not in request.form:
    output['message'] = "URL, Artist or Song missing."
    return jsonify(output)

  outfile = "/Music/{} - {}.%(ext)s".format(
    connix.alphanum(request.form['artist'], spaces=True),
    connix.alphanum(request.form['song'], spaces=True)
  )

  cmd = subprocess.Popen([
    "/usr/local/bin/yt-dlp",
    "--no-mtime",
    "--embed-thumbnail",
    "--no-playlist",
    "--extract-audio",
    "--audio-format",
    "mp3",
    request.form['url'],
    "-o",
    outfile
  ])

  output['message'] = "Music pipeline started."
  output['status'] = 0

  return jsonify(output)

if __name__ == '__main__':
  app.run(host='0.0.0.0', port=8900, threaded=True)

This is a pretty simple Python script that launches a Flask web app, accepts connections on port 8900, takes POST arguments for the YouTube URL, the name of the artist and the name of the song, and then calls the yt-dlp command to download the YouTube video into an MP3 file and save it to the /Music folder.

After that, it's a simple matter of running the script and creating an iOS shortcut to send the proper parameters to the app. This is the shortcut I created:

That's it! This is what I've been using for years any time I find a new song I want to save to my playlist. From there, you can even expose your web app through Cloudflare, package the app as a container, and have automation to synchronize your music folder to cloud storage. The things you can do are limitless.