Python Wave byte data

Viewed 18031

I'm trying to read the data from a .wav file.

import wave
wr = wave.open("~/01 Road.wav", 'r')
# sample width is 2 bytes
# number of channels is 2
wave_data = wr.readframes(1)
print(wave_data)

This gives:

b'\x00\x00\x00\x00'

Which is the "first frame" of the song. These 4 bytes obviously correspond to the (2 channels * 2 byte sample width) bytes per frame, but what does each byte correspond to?

In particular, I'm trying to convert it to a mono amplitude signal.

4 Answers

Another way to convert 2 bytes into an int16, use numpy.fromstring(). Here's an example: audio_sample is from a wav file.

>>> audio_sample[0:8]
b'\x8b\xff\xe1\xff\x92\xffn\xff'

>>> x = np.fromstring(audio_sample, np.int16) 

>>> x[0:4]
array([-117,  -31, -110, -146], dtype=int16)

You can use np.tobytes to convert back to bytes

Related