To get the same result. modify fromstring
in the first approach as
if w.getsampwidth() == 1:
data = np.fromstring(f, dtype=np.int8)
elif w.getsampwidth() == 2:
data = np.fromstring(f, dtype=np.int16)
elif w.getsampwidth() == 4:
data = np.fromstring(f, dtype=np.int32)
where w.getsampwidth()
has how many byte(s) used for representing samples
The np.fromstring
reads bytes as float64
then convert the values (not bytes) into int32
by astype('int32')
. So you need to read bytes corresponding type
among int8, 16 and 32
Second approach has no problem.
The wave file(maybe RIFF format) has 44 bytes header. So the last doesn't work properly.