Skip to content

Instantly share code, notes, and snippets.

@wrigby wrigby/24bitwav.py
Created Dec 22, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.