2016-11-26 74 views
2

我有一個問題寫一個2D numpy的數組作爲波形文件(音頻)scipy.io:不能寫wavfile

按照DOC我應該寫一個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的陣列I首先將它轉換爲16位詮釋

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 

我的值是16位和-4391之間4389格式化應該沒問題。但我的數據看起來解釋爲ushort

+0

您問題中的鏈接已死亡 –

回答

3

函數scipy.io.wavfile預計輸入數組的形狀爲(num_samples, num_channels)。我懷疑你的陣列有形狀(num_channels, num_samples)。然後write會嘗試將num_samples置於結構中的16位字段中,該結構會寫入WAV文件,但num_samples的值對於16位值而言太大。 (請注意,如果num_samples是足夠小,你不會得到一個錯誤,但文件不會有正確的格式。)

速戰速決是寫你的數組的轉置:

wavfile.write(outWaveFileName, 44100, stereoAudio.T) 

例如,下面是一些演示錯誤的代碼; xy具有形狀(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 
+0

謝謝,您是對的,我的數組是(num_channels,num_samples) –