Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

wav

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?

like image 988
detly Avatar asked May 27 '13 06:05

detly


Video Answer


1 Answers

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])
like image 59
detly Avatar answered Sep 21 '22 05:09

detly