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 only supports 16 or 32 bits. The documentation for Python's own wave module doesn't specify what format of data it takes.
So is it possible to do this in Python?
Using the wave
module, the Wave_write.writeframes
function expects WAV data to be packed into a 3-byte string in little-endian format. The following code does the trick:
import wave
from contextlib import closing
import struct
def wavwrite_24(fname, fs, data):
data_as_bytes = (struct.pack('<i', int(samp*(2**23-1))) for samp in data)
with closing(wave.open(fname, 'wb')) as wavwriter:
wavwriter.setnchannels(1)
wavwriter.setsampwidth(3)
wavwriter.setframerate(fs)
for data_bytes in data_as_bytes:
wavwriter.writeframes(data_bytes[0:3])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With