#!/usr/bin/env python3 """ YouTube Downloader mit MP3/MP4-Konvertierung. Nutzt yt-dlp zum Herunterladen von YouTube-Videos und ffmpeg zur Konvertierung. Usage: python youtube_downloader.py [--format mp3|mp4] [--output ] Beispiele: python youtube_downloader.py "https://www.youtube.com/watch?v=..." python youtube_downloader.py "https://www.youtube.com/watch?v=..." --format mp3 python youtube_downloader.py "https://www.youtube.com/watch?v=..." --format mp4 --output mein_video.mp4 MIT License — Copyright (c) 2026 Prof. Dr. Joern Fischer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import argparse import os import shutil import subprocess import sys import time from pathlib import Path def check_dependencies(): """Prüft, ob yt-dlp und ffmpeg installiert sind.""" missing = [] if not shutil.which("yt-dlp"): missing.append("yt-dlp") if not shutil.which("ffmpeg"): missing.append("ffmpeg") if missing: print(f"Fehler: Fehlende Abhängigkeiten: {', '.join(missing)}") print("Installiere mit:") for dep in missing: if dep == "yt-dlp": print(f" pip install {dep}") else: print(f" apt install {dep} # oder brew install {dep} auf macOS") sys.exit(1) # JS-Runtime (z.B. Deno) prüfen - wird von yt-dlp für YouTube-Extraktion benötigt. # Nicht fatal, aber ohne Runtime können Formate fehlen oder Extraktion fehlschlagen. if not shutil.which("deno"): print("⚠️ Kein JavaScript-Runtime (z.B. deno) gefunden.") print(" yt-dlp benötigt dies für zuverlässige YouTube-Extraktion.") print(" Installation: curl -fsSL https://deno.land/install.sh | sh") print(" (Fahre trotzdem fort, aber Fehler wie 'video not available' können auftreten)\n") def update_yt_dlp(): """Aktualisiert yt-dlp auf die neueste Version via pip.""" print("🔄 Prüfe auf yt-dlp-Updates...") try: result = subprocess.run( [sys.executable, "-m", "pip", "install", "-U", "yt-dlp"], capture_output=True, text=True ) if result.returncode == 0: # Zeige nur relevante Ausgabe (z.B. ob aktualisiert wurde oder bereits aktuell) for line in result.stdout.splitlines(): if "Successfully installed" in line or "already satisfied" in line: print(f" {line.strip()}") print("✅ yt-dlp ist aktuell.\n") else: print("⚠️ Update-Prüfung fehlgeschlagen, fahre mit aktueller Version fort.\n") except Exception as e: print(f"⚠️ Konnte yt-dlp nicht aktualisieren: {e}\n") def download_video(url, output_template=None): """ Lädt ein YouTube-Video mit yt-dlp herunter. Args: url: Die YouTube-URL des Videos. output_template: Optionaler Ausgabe-Pfad-Template für yt-dlp. Returns: Pfad zur heruntergeladenen Datei oder None bei Fehler. """ print(f"📥 Lade Video von: {url}") yt_dlp_args = [ "yt-dlp", "--no-playlist", # Nur einzelnes Video, keine Playlist "-f", "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]+bestaudio/best", # Beste Qualität ] if shutil.which("deno"): yt_dlp_args.extend(["--js-runtimes", "deno"]) if output_template: yt_dlp_args.extend(["-o", output_template]) else: yt_dlp_args.extend(["-o", "%(title)s.%(ext)s"]) try: result = subprocess.run( yt_dlp_args + [url], capture_output=False, text=True ) if result.returncode != 0: print(f"❌ Fehler beim Herunterladen (yt-dlp exit code {result.returncode})") return None # Finde die heruntergeladene Datei output_path = find_downloaded_file() if output_path: print(f"✅ Video heruntergeladen: {output_path}") return str(output_path) else: print("⚠️ yt-dlp lief ohne Fehler, konnte aber keine Ausgabedatei finden.") return None except FileNotFoundError: print("❌ yt-dlp nicht gefunden. Bitte installieren mit 'pip install yt-dlp'") sys.exit(1) def find_downloaded_file(): """Findet die neueste heruntergeladene Datei im aktuellen Verzeichnis.""" current_dir = Path(".") # Suche nach Video-Dateien, die kürzlich erstellt wurden (letzte 60 Sekunden) now = time.time() video_extensions = {'.mp4', '.mkv', '.webm', '.avi', '.mov'} candidates = [] for file_path in current_dir.iterdir(): if file_path.is_file() and file_path.suffix.lower() in video_extensions: # Prüfe, ob die Datei innerhalb der letzten 60 Sekunden erstellt wurde try: ctime = file_path.stat().st_ctime if now - ctime < 60: candidates.append(file_path) except OSError: pass if not candidates: # Fallback: Nimm die neueste Video-Datei im Verzeichnis for ext in video_extensions: files = list(current_dir.glob(f"*{ext}")) if files: candidates.extend(files) if candidates: return max(candidates, key=lambda p: p.stat().st_mtime) return None def convert_to_mp3(input_file, output_file=None): """ Konvertiert ein Video-File in MP3-Audio. Args: input_file: Pfad zur Eingabedatei (Video). output_file: Optionaler Ausgabepfad für die MP3-Datei. Returns: Pfad zur MP3-Datei oder None bei Fehler. """ if not output_file: base = Path(input_file).stem output_file = f"{base}.mp3" print(f"🎵 Konvertiere zu MP3: {input_file} -> {output_file}") try: result = subprocess.run( [ "ffmpeg", "-i", input_file, "-vn", # Kein Video "-acodec", "libmp3lame", "-q:a", "2", # Gute Qualität (VBR) "-y", # Überschreibe existierende Datei output_file ], capture_output=True, text=True ) if result.returncode != 0: print(f"❌ Fehler bei der Konvertierung:") print(result.stderr) return None mp3_path = Path(output_file) if mp3_path.exists(): file_size_mb = mp3_path.stat().st_size / (1024 * 1024) print(f"✅ MP3 erstellt: {output_file} ({file_size_mb:.2f} MB)") return str(mp3_path) else: print("❌ Konvertierung fehlgeschlagen - Ausgabedatei nicht gefunden.") return None except FileNotFoundError: print("❌ ffmpeg nicht gefunden. Bitte installieren mit 'apt install ffmpeg' oder 'brew install ffmpeg'.") sys.exit(1) def convert_to_mp4(input_file, output_file=None): """ Stellt sicher, dass das Video im MP4-Format vorliegt. Falls bereits MP4, wird es kopiert/umbenannt. Args: input_file: Pfad zur Eingabedatei (Video). output_file: Optionaler Ausgabepfad für die MP4-Datei. Returns: Pfad zur MP4-Datei oder None bei Fehler. """ if not output_file: base = Path(input_file).stem output_file = f"{base}.mp4" input_path = Path(input_file) output_path = Path(output_file) # Wenn bereits MP4, einfach umbenennen/kopieren (oder zurückgeben wenn gleich) if input_path.suffix.lower() == '.mp4': if input_path.resolve() == output_path.resolve(): print(f"✅ Video ist bereits MP4: {output_file}") return str(output_path) shutil.copy2(str(input_path), str(output_path)) print(f"✅ Video ist bereits MP4: {output_file}") return str(output_path) # Konvertiere zu MP4 print(f"🎬 Konvertiere zu MP4: {input_file} -> {output_file}") try: result = subprocess.run( [ "ffmpeg", "-i", input_file, "-c:v", "libx264", # Video-Codec H.264 "-preset", "medium", # Kompromiss zwischen Geschwindigkeit und Qualität "-crf", "23", # Gute Qualität (0-51, niedriger = besser) "-c:a", "aac", # Audio-Codec AAC "-b:a", "192k", # Audio-Bitrate "-movflags", "+faststart", # Für Web-Streaming optimieren "-y", # Überschreibe existierende Datei str(output_path) ], capture_output=True, text=True ) if result.returncode != 0: print(f"❌ Fehler bei der Konvertierung:") print(result.stderr) return None if output_path.exists(): file_size_mb = output_path.stat().st_size / (1024 * 1024) print(f"✅ MP4 erstellt: {output_file} ({file_size_mb:.2f} MB)") return str(output_path) else: print("❌ Konvertierung fehlgeschlagen - Ausgabedatei nicht gefunden.") return None except FileNotFoundError: print("❌ ffmpeg nicht gefunden. Bitte installieren mit 'apt install ffmpeg' oder 'brew install ffmpeg'.") sys.exit(1) def download_and_convert(url, fmt="mp4", output=None, skip_update=False): """ Hauptfunktion: Lädt ein Video herunter und konvertiert es optional. Args: url: YouTube-URL. fmt: Format ('mp3' oder 'mp4'). output: Optionaler Ausgabedateiname. skip_update: Wenn True, wird der automatische yt-dlp-Update-Check übersprungen. Returns: Pfad zur endgültigen Datei oder None bei Fehler. """ check_dependencies() if not skip_update: update_yt_dlp() # Schritt 1: Video herunterladen (als MP4) downloaded = download_video(url, output_template=output if output else "%(title)s.%(ext)s") if not downloaded: print("❌ Herunterladen fehlgeschlagen.") return None # Schritt 2: Konvertieren falls nötig if fmt == "mp3": result = convert_to_mp3(downloaded, output) elif fmt == "mp4": result = convert_to_mp4(downloaded, output) else: print(f"❌ Unbekanntes Format: {fmt}. Verwende 'mp3' oder 'mp4'.") return None # Original-Video löschen (optional - auskommentieren zum Behalten) original = Path(downloaded) if result and original.exists() and str(original) != str(result): try: original.unlink() print(f"🗑️ Original-Datei gelöscht: {original.name}") except OSError as e: print(f"⚠️ Konnte Original nicht löschen: {e}") return result def main(): parser = argparse.ArgumentParser( description="YouTube Downloader mit MP3/MP4-Konvertierung", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Beispiele: %(prog)s "https://www.youtube.com/watch?v=..." %(prog)s "https://www.youtube.com/watch?v=..." --format mp3 %(prog)s "https://www.youtube.com/watch?v=..." --format mp4 --output video.mp4 Hinweis: Benötigt yt-dlp und ffmpeg. """ ) parser.add_argument("url", help="YouTube-URL des Videos") parser.add_argument( "--format", "-f", choices=["mp3", "mp4"], default="mp4", help="Ausgabeformat (default: mp4)" ) parser.add_argument( "--output", "-o", default=None, help="Ausgabedateiname (optional)" ) parser.add_argument( "--no-update-check", action="store_true", help="Überspringt die automatische Aktualisierung von yt-dlp vor dem Download" ) args = parser.parse_args() print("=" * 60) print(" YouTube Downloader") print("=" * 60) result = download_and_convert( args.url, fmt=args.format, output=args.output, skip_update=args.no_update_check ) if result: print(f"\n{'='*60}") print(f"✅ Fertig! Datei gespeichert unter:") print(f" {result}") print(f"{'='*60}") else: print("\n❌ Download fehlgeschlagen.") sys.exit(1) if __name__ == "__main__": main()