Skip to content

Instantly share code, notes, and snippets.

@wrigby
Created December 22, 2016 06:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrigby/001b65cb64a0a179fac7160ece8d8913 to your computer and use it in GitHub Desktop.
Save wrigby/001b65cb64a0a179fac7160ece8d8913 to your computer and use it in GitHub Desktop.
Reading a 24-bit wave file in Python
def sign_extend(bits, value):
""" Sign-extend from http://stackoverflow.com/questions/32030412/twos-complement-sign-extension-python """
sign_bit = 1 << (bits - 1)
return (value & (sign_bit - 1)) - (value & sign_bit)
def get_samples(w):
w.rewind()
num_samples = w.getnframes()
sample_depth = w.getsampwidth()
raw_data = w.readframes(num_samples)
for i in range(0, num_samples * sample_depth, sample_depth):
yield sign_extend(
sample_depth * 8,
reduce(
lambda x, y: x<<8 | y,
reversed(raw_data[i:i+sample_depth])
))
""" Use it like this: """
samples = list(get_samples(wave.open("/path/to/file.wav", "r")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment