Skip to content

Instantly share code, notes, and snippets.

@engividal
Last active October 27, 2024 11:04
Show Gist options
  • Save engividal/11bd9af936286a500021a593da7b4a3d to your computer and use it in GitHub Desktop.
Save engividal/11bd9af936286a500021a593da7b4a3d to your computer and use it in GitHub Desktop.
This script allows you to download the audio from a YouTube video and convert it to MP3 format, saving the resulting file in the user's "Videos" folder on Windows. Dependencies include pytube, pydub, and ffmpeg.
import logging
from yt_dlp import YoutubeDL
from pydub import AudioSegment
import os
import sys
# Logger configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def download_youtube_video_as_mp3(url, output_path):
"""
Downloads audio from a YouTube video and converts it to MP3 using yt-dlp.
Parameters:
url (str): The URL of the YouTube video to be downloaded.
output_path (str): The path where the MP3 file will be saved.
Steps:
- Start the download process and log the initial message.
- Use yt-dlp to find and download the best available audio stream.
- Define output file name and convert audio to MP3 format.
- Log the completion of the download and conversion.
"""
try:
logging.info("Starting download process...")
# yt-dlp options for downloading best audio and converting to mp3
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': os.path.join(output_path, '%(title)s.%(ext)s'),
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
# Using yt-dlp to download and convert audio to MP3
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
mp3_file = ydl.prepare_filename(info).replace('.webm', '.mp3')
logging.info(f"Download and conversion completed: {mp3_file}")
except Exception as e:
logging.error(f"An error occurred: {e}")
if __name__ == "__main__":
if len(sys.argv) != 2:
logging.error("Usage: python download_mp3.py <YouTube video URL>")
sys.exit(1)
# Get the user's "Videos" folder path
user_profile = os.getenv("USERPROFILE") or os.path.expanduser("~")
videos_folder = os.path.join(user_profile, "Videos")
url = sys.argv[1]
download_youtube_video_as_mp3(url, videos_folder)
@engividal
Copy link
Author

I had some problems with pytube them I shift to yt_dlp.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment