"""Audio-Wiedergabe und Dekodierpruefungen.""" from __future__ import annotations import shutil import subprocess from pathlib import Path from .metadata import AudioMetadataError, read_metadata class PlaybackError(RuntimeError): """Wiedergabe nicht moeglich.""" def find_player() -> str | None: """Sucht einen installierten Player (bevorzugt ffplay).""" for candidate in ("ffplay", "mpv", "vlc"): executable = shutil.which(candidate) if executable: return executable return None def build_play_command(path: str | Path, start_time: float = 0.0) -> list[str]: """Baut den Kommandozeilenaufruf zum Abspielen ab einer Zeitposition.""" player = find_player() if player is None: raise PlaybackError( "Kein Player gefunden. Installiere ffmpeg (ffplay), mpv oder vlc." ) name = Path(player).name start = max(0.0, float(start_time)) if name.startswith("ffplay"): # -nodisp: reine Audiowiedergabe ohne zusaetzliches Fenster. command = [player, "-nodisp", "-autoexit", "-loglevel", "error"] if start > 0: command += ["-ss", f"{start:.3f}"] command.append(str(path)) return command if name.startswith("mpv"): command = [player] if start > 0: command += [f"--start={start:.3f}"] command.append(str(path)) return command # vlc command = [player] if start > 0: command += [f"--start-time={start:.3f}"] command.append(str(path)) return command def play(path: str | Path, start_time: float = 0.0) -> None: """Startet die Wiedergabe und wartet, bis der Player beendet wird.""" file_path = Path(path) if not file_path.is_file(): raise PlaybackError(f"Audiodatei nicht gefunden: {file_path}") command = build_play_command(file_path, start_time) try: subprocess.run(command, check=False) except OSError as exc: raise PlaybackError(f"Player konnte nicht gestartet werden: {exc}") from exc def can_decode(path: str | Path) -> bool: """Prueft grob, ob die Datei als Audio dekodierbar ist.""" try: read_metadata(path) return True except AudioMetadataError: return False