scipy.io.wavfile中的
write函数要求输入数组具有形状(num_samples,num_channels).我怀疑你的阵列有形状(num_channels,num_samples).然后,写入尝试将num_samples放入写入WAV文件的结构中的16位字段中,但num_samples的值对于16位值而言太大. (请注意,如果num_samples足够小,则不会出现错误,但文件格式不正确.)
快速解决方法是编写数组的转置:
wavfile.write(outWaveFileName, 44100, stereoAudio.T)
例如,以下是一些演示错误的代码; x和y有形状(2,40000):
In [12]: x = (2*np.random.rand(2, 40000) - 1).astype(np.float32)
In [13]: y = (x*32767).astype('int16')
In [14]: from scipy.io import wavfile
In [15]: wavfile.write('foo.wav', 44100, y)
---------------------------------------------------------------------------
error Traceback (most recent call last)
in ()
----> 1 wavfile.write('foo.wav', 44100, y)
/Users/warren/anaconda/lib/python2.7/site-packages/scipy/io/wavfile.pyc in write(filename, rate, data)
351
352 fmt_chunk_data = struct.pack('
--> 353 bytes_per_second, block_align, bit_depth)
354 if not (dkind == 'i' or dkind == 'u'):
355 # add cbSize field for non-PCM files
error: ushort format requires 0 <= number <= USHRT_MAX
转置数组,以便wavfile.write的输入具有预期的形状:
In [16]: wavfile.write('foo.wav', 44100, y.T)
回读数据以验证它是否按预期工作:
In [22]: fs, z = wavfile.read('foo.wav')
In [23]: np.allclose(z, y.T)
Out[23]: True