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

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 file wavio.py contains the function write, which writes a numpy array to a WAV file. To write a 24-bit file, use the argument sampwidth=3. The only dependency of wavio is numpy; wavio uses the standard library wave to deal with the WAV file format.

For example,

In [21]: import numpy as np

In [22]: import wavio

In [23]: rate = 22050             # samples per second

In [24]: T = 3                    # sample duration (seconds)

In [25]: f = 440.0                # sound frequency (Hz)

In [26]: t = np.linspace(0, T, T*rate, endpoint=False)

In [27]: sig = np.sin(2 * np.pi * f * t)

In [28]: wavio.write("sine24.wav", sig, rate, sampwidth=3)

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])

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

pip install soundfile --user

Writing a 24-bit WAV file is easy:

import soundfile as sf
sf.write('my_24bit_file.wav', my_audio_data, 44100, 'PCM_24')

In this example, my_audio_data has to be a NumPy array with dtype '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.

Tags:

Python

Wav