from __future__ import annotations import subprocess import wave from pathlib import Path from typing import Any def resolve_audio_path(value: Any) -> Path: if value is None: raise ValueError("Es wurde keine Audiodatei übergeben.") path_attr = getattr(value, "path", None) if path_attr: return Path(str(path_attr)) if isinstance(value, dict) and value.get("path"): return Path(str(value["path"])) return Path(str(value)) def is_browser_wav(path: Path) -> bool: try: with wave.open(str(path), "rb") as wav_file: return wav_file.getsampwidth() == 2 and wav_file.getnchannels() in {1, 2} except wave.Error: return False def ensure_browser_wav(source: str | Path, destination: str | Path) -> Path: source_path = resolve_audio_path(source) dest_path = Path(destination) dest_path.parent.mkdir(parents=True, exist_ok=True) if not source_path.is_file(): raise ValueError("Die Audiodatei wurde nicht gefunden.") if source_path.resolve() == dest_path.resolve() and is_browser_wav(source_path): return dest_path if is_browser_wav(source_path) and source_path.suffix.casefold() == ".wav": dest_path.write_bytes(source_path.read_bytes()) return dest_path converted = subprocess.run( [ "ffmpeg", "-y", "-hide_banner", "-nostdin", "-i", str(source_path), "-ac", "2", "-ar", "48000", "-c:a", "pcm_s16le", str(dest_path), ], check=False, capture_output=True, timeout=120, ) if converted.returncode != 0 or not dest_path.is_file(): detail = converted.stderr.decode("utf-8", errors="replace")[-500:] raise ValueError(f"WAV konnte nicht browserfähig konvertiert werden: {detail}") return dest_path