Created
December 22, 2016 06:11
-
-
Save wrigby/001b65cb64a0a179fac7160ece8d8913 to your computer and use it in GitHub Desktop.
Reading a 24-bit wave file in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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