"""Audio IO helpers. Everything is mono float32 in [-1, 1].""" from __future__ import annotations from fractions import Fraction from pathlib import Path import numpy as np import soundfile as sf from scipy.signal import resample_poly AUDIO_EXTENSIONS = (".wav", ".flac", ".ogg", ".mp3", ".m4a", ".opus") def resample(wave: np.ndarray, sr_in: int, sr_out: int) -> np.ndarray: if sr_in == sr_out or len(wave) == 0: return wave.astype(np.float32, copy=False) ratio = Fraction(sr_out, sr_in).limit_denominator(1000) return resample_poly(wave, ratio.numerator, ratio.denominator).astype(np.float32) def info(path: str | Path) -> tuple[int, int]: """(sample_rate, num_frames) without decoding the file.""" try: meta = sf.info(str(path)) except Exception as e: raise RuntimeError(f"audio info failed: {path}: {type(e).__name__}") from None return meta.samplerate, meta.frames def load( path: str | Path, sample_rate: int, start: float = 0.0, duration: float | None = None, ) -> np.ndarray: """Read ``duration`` seconds from ``start`` seconds, downmix and resample.""" try: return _load(path, sample_rate, start, duration) except Exception as e: # name the failing file (libsndfile errors do not) raise RuntimeError(f"audio load failed: {path} start={start} dur={duration}: {type(e).__name__}") from None def _load(path, sample_rate, start, duration): with sf.SoundFile(str(path)) as f: sr = f.samplerate first = max(0, int(round(start * sr))) first = min(first, f.frames) frames = f.frames - first if duration is None else int(round(duration * sr)) f.seek(first) wave = f.read(max(0, min(frames, f.frames - first)), dtype="float32", always_2d=True) wave = wave.mean(axis=1) if wave.shape[1] > 1 else wave[:, 0] return resample(wave, sr, sample_rate) def save(path: str | Path, wave: np.ndarray, sample_rate: int) -> None: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) sf.write(str(path), np.clip(wave, -1.0, 1.0), sample_rate, subtype="PCM_16") def rms(wave: np.ndarray) -> float: return float(np.sqrt(np.mean(np.square(wave, dtype=np.float64)))) if len(wave) else 0.0 def db(value: float, floor: float = 1e-10) -> float: return 20.0 * float(np.log10(max(value, floor))) def active_region( wave: np.ndarray, sample_rate: int, top_db: float = 35.0, frame_ms: float = 20.0 ) -> tuple[int, int]: """Sample range that holds energy within ``top_db`` of the loudest frame. Used to find the spoken part of a TTS clip. Returns (0, len) for silence. """ frame = max(1, int(sample_rate * frame_ms / 1000.0)) n = len(wave) // frame if n == 0: return 0, len(wave) energy = np.sqrt(np.mean(wave[: n * frame].reshape(n, frame) ** 2, axis=1)) peak = float(energy.max()) if peak <= 0.0: return 0, len(wave) active = np.nonzero(energy >= peak * 10.0 ** (-top_db / 20.0))[0] return int(active[0]) * frame, min(len(wave), (int(active[-1]) + 1) * frame) def list_audio(root: str | Path) -> list[Path]: root = Path(root) if root.is_file(): return [root] return sorted(p for p in root.rglob("*") if p.suffix.lower() in AUDIO_EXTENSIONS)