Writing wav file in Python with wavfile.write from SciPy

JVE999 picture JVE999 · Sep 5, 2013 · Viewed 31k times · Source

I have this code:

import numpy as np
import scipy.io.wavfile
import math

rate, data = scipy.io.wavfile.read('xenencounter_23.wav')

data2 = []

for i in range(len(data)):
    data2.append([int(round(math.sin(data[i][0])*3000)), int(round(math.sin(data[i][1])*3000))])

data2 = np.asarray(data2)

print data2

scipy.io.wavfile.write('xenencounter_23sin3.wav',rate,data2)

This prints (truncated):

[[-2524  2728]
 [ -423 -2270]
 [ 2270   423]
 ..., 
 [-2524     0]
 [ 2524 -2728]
 [-2270   838]]

The wav file opens and plays in Windows Media Player, so at least its the proper format. However, when opening it with Audacity and looking at the individual samples, they're all 0, and concordantly the file plays no sound at all.

What I don't understand is how that numpy array listed above becomes all 0's. It should be below the maximum value for a sample (or above, if it's negative).

Answer

JVE999 picture JVE999 · Sep 6, 2013

I found that scipy.io.wavfile.write() writes in 16-bit integer, which explains the larger file sizes when trying to use a 32-bit integer (the default) instead. While I couldn't find a way to change this in wavfile.write, I did find that by changing:

data2 = np.asarray(data2)

to

data2 = np.asarray(data2, dtype=np.int16)

I could write a working file.