Skip to content

Instantly share code, notes, and snippets.

@istupakov
Last active April 17, 2025 10:24
Show Gist options
  • Save istupakov/5ff1a1fa25d575543e8ce98da77bfd63 to your computer and use it in GitHub Desktop.
Save istupakov/5ff1a1fa25d575543e8ce98da77bfd63 to your computer and use it in GitHub Desktop.
Read PCM wav file with pure python and numpy
import wave
import numpy as np
import numpy.typing as npt
def read_wav(filename: str) -> tuple[npt.NDArray[np.float32], int]:
"""
Read PCM wav file
Support PCM_U8, PCM_16, PCM_24 and PCM_32 formats.
Parameters:
filename : Path to wav file
Returns
-------
waveform : (frames x channels) numpy array with samples [-1, +1]
sample_rate : sample rate
"""
with wave.open(filename, mode="rb") as f:
data = f.readframes(f.getnframes())
zero_value = 0
if f.getsampwidth() == 1:
buffer = np.frombuffer(data, dtype="u1")
zero_value = 1
elif f.getsampwidth() == 3:
buffer = np.zeros((len(data) // 3, 4), dtype="V1")
buffer[:, -3:] = np.frombuffer(data, dtype="V1").reshape(-1, f.getsampwidth())
buffer = buffer.view(dtype="<i4")
else:
buffer = np.frombuffer(data, dtype=f"<i{f.getsampwidth()}")
max_value = 2 ** (8 * buffer.itemsize - 1)
return buffer.reshape(f.getnframes(), f.getnchannels()).astype(np.float32) / max_value - zero_value, f.getframerate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment