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?
I already submitted an answer to this question 2 years ago, where I recommended scikits.audiolab.
In the meantime, the situation has changed and now there is a library available which is much easier to use and much easier to install, it even comes with its own copy of the libsndfile library for Windows and OSX (on Linux it's easy to install anyway): PySoundFile!
If you have CFFI and NumPy installed, you can install PySoundFile simply by running
Writing a 24-bit WAV file is easy:
In this example,
my_audio_data
has to be a NumPy array withdtype
'float64'
,'float32'
,'int32'
or'int16'
.BTW, I made an overview page where I tried to compare many available Python libraries for reading/writing sound files.
You should try scikits.audiolab:
And to read it again:
scikits.audiolab
uses libsndfile, so in addition to WAV files, you can also use FLAC, OGG and some more file formats.Another option is available in
wavio
(also on PyPI: https://pypi.python.org/pypi/wavio), a small module I created as a work-around to the problem of scipy not yet supporting 24 bit WAV files. The filewavio.py
contains the functionwrite
, which writes a numpy array to a WAV file. To write a 24-bit file, use the argumentsampwidth=3
. The only dependency ofwavio
is numpy;wavio
uses the standard librarywave
to deal with the WAV file format.For example,
Try the
wave
module: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:
Using the
wave
module, theWave_write.writeframes
function expects WAV data to be packed into a 3-byte string in little-endian format. The following code does the trick:Here is an updated version of
scipy.io.wavfile
that adds:wavfile.py (enhanced)