7.2.1. Real Time Audio DisplayΒΆ

Reading a wav file has been done before in these notes. But this time we don’t read the entire file into a numpy array. Instead we will only open the wav file and determine the sound signal parameters. For this we use the standard Python Wave package.

import wave

wf = wave.open('testwave.wav', 'rb')
nchannels = wd.getnchannels() # 1: mono, 2: stereo
nbytesframe = wf.getsamplewidth() # 1: unsigned byte, 2: signed int
framerate = wf.getframerate() # no of samples per second

Given this initialization we can use the method readframes to read a specific number of frames from the stream. This method returns the raw stream of bytes as a string. It is up to the programmer to make this into useful numerical data.

if nbytesframe == 1:
       tp = dtype.uint8
else:
       tp = dtype.int16

x = np.fromstring(wf.readframes(N), tp)

if nchannels == 1:
       xleft = x
       xright = x
else:
       xleft = x[::2]
       xright = x[1::2]

In the above code we always return a stereo signal. In case the original signal was mono, the left and right signal are the same.