94 lines
2.7 KiB
Python
94 lines
2.7 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
YouTube Audio Downloader - Download audio from YouTube videos.
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import argparse
|
|
from loguru import logger
|
|
import yt_dlp
|
|
|
|
# Configure loguru logger
|
|
logger.remove()
|
|
logger.add(sys.stderr, format="<level>{level: <8}</level> {message}")
|
|
|
|
|
|
def download_youtube_audio(url, output_dir):
|
|
"""
|
|
Download audio from a YouTube video in the highest quality available as MP3.
|
|
|
|
Args:
|
|
url (str): YouTube video URL
|
|
output_dir (str): Directory to save the audio file
|
|
|
|
Returns:
|
|
str: Path to the downloaded audio file or None if download failed
|
|
"""
|
|
# Configure options for MP3 download
|
|
ydl_opts = {
|
|
'format': 'bestaudio/best',
|
|
'postprocessors': [{
|
|
'key': 'FFmpegExtractAudio',
|
|
'preferredcodec': 'mp3',
|
|
'preferredquality': '192',
|
|
}],
|
|
'outtmpl': os.path.join(output_dir, "%(title)s.%(ext)s"),
|
|
}
|
|
|
|
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
info = ydl.extract_info(url, download=True)
|
|
if info and 'title' in info:
|
|
filename = ydl.prepare_filename(info)
|
|
base, _ = os.path.splitext(filename)
|
|
audio_file = f"{base}.mp3"
|
|
|
|
if os.path.exists(audio_file):
|
|
logger.success(f"Downloaded: {os.path.basename(audio_file)}")
|
|
return audio_file
|
|
else:
|
|
logger.error(f"Failed to find downloaded file for: {url}")
|
|
sys.exit(1)
|
|
else:
|
|
logger.error(f"Failed to extract info from: {url}")
|
|
sys.exit(1)
|
|
|
|
|
|
def main():
|
|
# Create argument parser
|
|
parser = argparse.ArgumentParser(
|
|
description="📱 DOWNLOAD_AUDIOS - Download YouTube videos as MP3 audio files",
|
|
formatter_class=argparse.RawTextHelpFormatter
|
|
)
|
|
|
|
# Add arguments
|
|
parser.add_argument('urls', nargs='+', help='One or more YouTube URLs')
|
|
parser.add_argument('-o', '--output-dir', required=True,
|
|
help='Directory to save audio files (must exist)')
|
|
|
|
# Parse arguments
|
|
args = parser.parse_args()
|
|
|
|
# Check if output directory exists
|
|
if not os.path.isdir(args.output_dir):
|
|
logger.error(f"Output directory '{args.output_dir}' does not exist.")
|
|
sys.exit(1)
|
|
|
|
logger.info("📱 DOWNLOAD_AUDIOS")
|
|
logger.info("===================")
|
|
|
|
# Download each URL
|
|
successful = 0
|
|
for url in args.urls:
|
|
logger.info(f"▶ Processing: {url}")
|
|
result = download_youtube_audio(url, args.output_dir)
|
|
successful += 1
|
|
|
|
# Print summary
|
|
logger.info("===================")
|
|
logger.success(f"Successfully downloaded: {successful}")
|
|
logger.info(f"🔊 Audio files saved to: {args.output_dir}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |