from __future__ import annotations import json import math import subprocess import sys import wave from array import array from dataclasses import asdict, dataclass from pathlib import Path from typing import Any @dataclass(frozen=True, slots=True) class AudioAnalysis: duration_s: float sample_rate: int channels: int peak_dbfs: float rms_dbfs: float crest_db: float zero_crossing_rate: float character: str def as_dict(self) -> dict[str, Any]: return asdict(self) def _dbfs(amplitude: float) -> float: if amplitude <= 0: return -96.0 return max(-96.0, 20 * math.log10(amplitude / 32767.0)) def _describe_character(rms_dbfs: float, crest_db: float, zero_crossing_rate: float) -> str: density = "dicht" if rms_dbfs > -12 else "ausgewogen" if rms_dbfs > -20 else "dynamisch" tone = ( "brillant/perkussiv" if zero_crossing_rate > 0.14 else "warm/dunkel" if zero_crossing_rate < 0.055 else "tonal balanciert" ) transients = "kompakt" if crest_db < 7 else "transientenreich" if crest_db > 13 else "offen" return f"{density}, {tone}, {transients}" def _read_audio_as_pcm16(audio_path: Path) -> tuple[int, int, int, bytes]: try: with wave.open(str(audio_path), "rb") as wav_file: channels = wav_file.getnchannels() sample_width = wav_file.getsampwidth() sample_rate = wav_file.getframerate() frame_count = wav_file.getnframes() frames = wav_file.readframes(frame_count) if sample_width == 2: return channels, sample_rate, frame_count, frames except wave.Error: pass probe = subprocess.run( [ "ffprobe", "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=sample_rate,channels", "-of", "json", str(audio_path), ], check=False, capture_output=True, text=True, timeout=30, ) if probe.returncode != 0: raise ValueError(f"FFprobe konnte die WAV-Datei nicht lesen: {probe.stderr[-500:]}") payload = json.loads(probe.stdout) streams = payload.get("streams", []) if not streams: raise ValueError("Die WAV-Datei enthält keinen Audiostream.") channels = int(streams[0]["channels"]) sample_rate = int(streams[0]["sample_rate"]) decoded = subprocess.run( [ "ffmpeg", "-v", "error", "-nostdin", "-i", str(audio_path), "-f", "s16le", "-acodec", "pcm_s16le", "-", ], check=False, capture_output=True, timeout=120, ) if decoded.returncode != 0: detail = decoded.stderr.decode("utf-8", errors="replace")[-500:] raise ValueError(f"FFmpeg konnte die WAV-Datei nicht dekodieren: {detail}") frame_count = len(decoded.stdout) // (2 * channels) return channels, sample_rate, frame_count, decoded.stdout def analyze_wav(path: str | Path) -> AudioAnalysis: audio_path = Path(path) channels, sample_rate, frame_count, frames = _read_audio_as_pcm16(audio_path) if channels < 1 or sample_rate < 1 or frame_count < 1: raise ValueError("Die WAV-Datei enthält keine analysierbaren Audiodaten.") samples = array("h") samples.frombytes(frames) if sys.byteorder != "little": samples.byteswap() peak = max(abs(sample) for sample in samples) square_sum = sum(sample * sample for sample in samples) rms = math.sqrt(square_sum / len(samples)) mono_samples = samples[::channels] crossings = sum( 1 for previous, current in zip(mono_samples, mono_samples[1:], strict=False) if (previous < 0 <= current) or (previous >= 0 > current) ) zero_crossing_rate = crossings / max(1, len(mono_samples) - 1) peak_dbfs = _dbfs(float(peak)) rms_dbfs = _dbfs(rms) crest_db = max(0.0, peak_dbfs - rms_dbfs) return AudioAnalysis( duration_s=frame_count / sample_rate, sample_rate=sample_rate, channels=channels, peak_dbfs=round(peak_dbfs, 2), rms_dbfs=round(rms_dbfs, 2), crest_db=round(crest_db, 2), zero_crossing_rate=round(zero_crossing_rate, 4), character=_describe_character(rms_dbfs, crest_db, zero_crossing_rate), )