-
-
Save NewProggie/3826062 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 pylab | |
import os | |
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 | |
if __name__ == '__main__': | |
frames, fps = readwavefile("hello.wav") | |
t = np.arange(0, frames.shape[0], 1) | |
pylab.plot(t, frames) | |
pylab.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment