File size: 751 Bytes
5eee449
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""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