| """16-bit PCM WAV writer (stdlib only, no soundfile dependency).""" | |
| from __future__ import annotations | |
| import wave | |
| from pathlib import Path | |
| import numpy as np | |
| def write_wav(path: str | Path, waveform: np.ndarray, sample_rate: int = 24000) -> Path: | |
| """Write float32 mono waveform in [-1, 1] as 16-bit PCM WAV.""" | |
| destination = Path(path) | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| pcm = np.clip(np.asarray(waveform, dtype=np.float32), -1.0, 1.0) | |
| pcm16 = (pcm * 32767.0).round().astype("<i2") | |
| with wave.open(str(destination), "wb") as handle: | |
| handle.setnchannels(1) | |
| handle.setsampwidth(2) | |
| handle.setframerate(sample_rate) | |
| handle.writeframes(pcm16.tobytes()) | |
| return destination | |