Search code examples
pythonwav

How to create multichannel .WAV file in Python?


The .WAV format looks like it should allow more than two channels (nChannels).

But unfortunately scipy.io.wavfile only writes 1 or 2.

I don't really want to manually write my own Python WAV-writer, but I can't find anything out there.

Is there any code out there that does the job?


Solution

  • It turns out the documentation for scipy.io.wavfile is incorrect.

    Looking at the source code, I can clearly see that it accepts an arbitrary number of channels.

    The following code works:

    import numpy as np
    from scipy.io import wavfile
    
    fs = 48000
    nsamps = fs * 10
    
    A, Csharp, E, G = 440.0, 554.365, 660.0, 783.991
    
    def sine(freqHz):
        τ = 2 * np.pi
        return np.sin( 
            np.linspace(0,  τ * freqHz * nsamps / fs,  nsamps,  endpoint=False)
        )
    
    A7_chord = np.array( [ sine(A), sine(Csharp), sine(E), sine(G) ] ).T
    
    wavfile.write("A7--4channel.wav", fs, A7_chord)