How do I write a 24-bit WAV file in Python?

前端 未结 7 2196
遇见更好的自我
遇见更好的自我 2020-12-11 02:05

I want to generate a 24-bit WAV-format audio file using Python 2.7 from an array of floating point values between -1 and 1. I can\'t use scipy.io.wavfile.write because it on

7条回答
  •  死守一世寂寞
    2020-12-11 02:15

    Try the wave module:

    In [1]: import wave
    
    In [2]: w = wave.open('foo.wav', 'w') # open for writing
    
    In [3]: w.setsampwidth(3) # 3 bytes/sample
    

    Python can only pack integers in 2 and 4 bite sizes. So you can use a numpy array with a dtype on int32, and use a list comprehension to get 3/4 of the bytes of each integer:

    In [14]: d = np.array([1,2,3,4], dtype=np.int32)
    
    In [15]: d
    Out[15]: array([1, 2, 3, 4], dtype=int32)
    
    In [16]: [d.data[i:i+3] for i in range(0,len(d)*d.dtype.itemsize, d.dtype.itemsize)]
    Out[16]: ['\x01\x00\x00', '\x02\x00\x00', '\x03\x00\x00', '\x04\x00\x00']
    

提交回复
热议问题