Python Code to Download MP3 from a YouTube URL

Nerd Stuff

Wrote a Python program to take a YouTube URL, extract and convert the audio to a MP3 file. It has a minimalist GUI. It requires tkinter, youtube-dl (a Linux command line tool), and ffmpeg.

import os
import subprocess

import tkinter as tk
from tkinter import filedialog

# Create the GUI window
window = tk.Tk()
window.title("YouTube Downloader")

# Create a function to be called when the user clicks the "Download" button
def download_video():
  # Get the URL of the YouTube video from the user's input
  url = url_entry.get()
  # Download the video using youtube-dl
  subprocess.run(["youtube-dl", url])
  # Get the filename of the video from youtube-dl's output
  video_filename = subprocess.run(["youtube-dl", "--get-filename", url], capture_output=True).stdout.strip().decode("utf-8")
  # Prompt the user to select a location and filename for the MP3 file
  mp3_filename = filedialog.asksaveasfilename(defaultextension=".mp3")
  # Convert the video to an MP3 file using ffmpeg
  subprocess.run(["ffmpeg", "-i", video_filename, mp3_filename])

# Create a label and text entry field for the URL
url_label = tk.Label(text="Enter the URL of the YouTube video:")
url_entry = tk.Entry()

# Create a button to start the download
download_button = tk.Button(text="Download", command=download_video)

# Place the widgets in the GUI window
url_label.pack()
url_entry.pack()
download_button.pack()

# Run the GUI event loop
window.mainloop()

Comments are closed.