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



Remove dots in filename

Nerd Stuff

I wrote a Bash Script to remove excess periods in a filename. For example, if you had a file named “some.words.in.your.filename.txt”, this script will assist in renaming it to “some words in your filename.txt”. Of course, this only works in Linux. You need to save the file below as a .sh and make it executable via the chmod command. Click “Read More” to see the code.

Read more
#!/bin/bash

# Get the filename argument
filename="$1"

# Get the extension of the filename
extension="${filename##*.}"

# Remove the extension from the filename
filename="${filename%.*}"

# Replace all dots in the filename with spaces
new_filename="${filename//./ }.$extension"

# Print the suggested new filename
echo "Suggested new filename: $new_filename"

# Prompt the user for confirmation
read -p "Do you want to rename the file? (y/n) " choice

if [[ $choice == "y" || $choice == "Y" ]]; then
    # Rename the file
    mv "$1" "$new_filename"
    echo "File renamed to $new_filename"
else
    echo "File not renamed"
fi
Read more

Comments