Created
September 21, 2012 07:25
-
-
Save rpls/3760188 to your computer and use it in GitHub Desktop.
Loading and norming WAV files 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
import wave | |
import numpy as np | |
def readwavefile(filename): | |
""" | |
Reads a WAV file and returns all the frames converted to floats and the framerate. | |
""" | |
assert os.path.exists(filename) and os.path.isfile(filename) | |
wavefile = wave.open(filename, 'r') | |
nframes = wavefile.getnframes() | |
framerate = wavefile.getframerate() | |
datatype = None | |
# Zero converter! | |
fconverter = lambda a : a | |
if wavefile.getsampwidth() == 1: | |
# 8-Bit format is unsigned. | |
datatype = np.uint8 | |
fconverter = lambda a : ((a / 255.0) - 0.5) * 2 | |
elif wavefile.getsampwidth() == 2: | |
# 16-Bit format is signed. | |
datatype = np.int16 | |
fconverter = lambda a : a / 32767.0 | |
# Read and convert to float array | |
frames = np.fromstring(wavefile.readframes(nframes), dtype = datatype) | |
frames = fconverter(np.asarray(frames, dtype = np.float64)) | |
wavefile.close() | |
# This shouldn't go wrong... | |
assert frames.shape[0] == nframes | |
return frames, framerate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
'import os' is missing