# SPDX-License-Identifier: MIT """Saved sound: the board's 16-bit stereo samples (Mikey.mix) written as a WAV file.""" from __future__ import annotations import struct from pathlib import Path def wav_bytes(samples, rate: int, channels: int = 2) -> bytes: """A PCM WAV (RIFF) image of interleaved signed 16-bit samples, little-endian.""" data = bytearray(len(samples) * 2) struct.pack_into(f"<{len(samples)}h", data, 0, *samples) header = struct.pack( "<4sI4s4sIHHIIHH4sI", b"RIFF", 36 + len(data), b"WAVE", b"fmt ", 16, 1, channels, rate, rate * channels * 2, channels * 2, 16, b"data", len(data), ) # fmt: skip return header + bytes(data) def write_wav(path: Path, samples, rate: int, channels: int = 2) -> None: path.write_bytes(wav_bytes(samples, rate, channels))