Last active
October 27, 2024 11:04
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had some problems with pytube them I shift to yt_dlp.