我在将2d numpy数组写为波形文件(音频)时遇到问题
根据文档我应该写一个2d int16 numpy数组
https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.io.wavfile.write.html
16-bit PCM -32768 +32767 int16
作为我在float32格式的范围(-1,1)中的numpy数组,我首先将其转换为16位int
stereoAudio = ((stereoAudio * bits16max)).astype('int16')
print "argmax : " + str(np.amax(stereoAudio))
print "argmin : " + str(np.amin(stereoAudio))
outWaveFileName = "out/file.wav"
print "writing " + outWaveFileName
wavfile.write(outWaveFileName,44100,stereoAudio)
我得到以下输出:
argmax : 4389
argmin : -4381
writing out/file.wav
Traceback (most recent call last):
File "/Users/me/file.py", line 132, in <module>
wavfile.write(outWaveFileName,44100,stereoAudio)
File "//anaconda/lib/python2.7/site-packages/scipy/io/wavfile.py", line 353, in write
bytes_per_second, block_align, bit_depth)
error: ushort format requires 0 <= number <= USHRT_MAX
因为我的值在1639格式之间介于-4391和4389之间,所以应该没问题。但我的数据看起来被解释为ushort
答案 0 :(得分:7)
scipy.io.wavfile
中的write
函数要求输入数组的形状为(num_samples, num_channels)
。我怀疑你的数组有(num_channels, num_samples)
的形状。然后write
尝试将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)
<ipython-input-15-36b8cd0e729c> in <module>()
----> 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('<HHIIHH', format_tag, channels, fs,
--> 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