23 lines
637 B
Python
23 lines
637 B
Python
"""In-memory PCM validation and conversion."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from array import array
|
|
import struct
|
|
|
|
MAX_PCM_BYTES = 5 * 60 * 16_000 * 2
|
|
|
|
|
|
class AudioError(ValueError):
|
|
pass
|
|
|
|
|
|
def pcm_s16le_to_floats(pcm: bytes, *, max_bytes: int = MAX_PCM_BYTES) -> array[float]:
|
|
"""Convert mono little-endian signed-16 PCM to a bounded float32 array."""
|
|
|
|
if len(pcm) > max_bytes:
|
|
raise AudioError("PCM exceeds the five-minute duration limit")
|
|
if len(pcm) % 2:
|
|
raise AudioError("PCM byte length must be even")
|
|
return array("f", (sample[0] / 32768.0 for sample in struct.iter_unpack("<h", pcm)))
|