How to join two wav files using python?

Python 3 solution:
We can do this with the standard library as shown by tom10 and eggbert's answers.
Below is a shorter version:

  1. Only write the parameters for the first wave file. We can test the wav_out file length to see if we haven't yet written to it. If we haven't write the wave parameters once only.
  2. Then write frames to the wav_out as they are read from the wav_in.

    with wave.open(outfile, 'wb') as wav_out:
        for wav_path in infiles:
            with wave.open(wav_path, 'rb') as wav_in:
                if not wav_out.getnframes():
                    wav_out.setparams(wav_in.getparams())
                wav_out.writeframes(wav_in.readframes(wav_in.getnframes()))
    

I'm the maintainer of pydub, which is designed to make this sort of thing easy.

from pydub import AudioSegment

sound1 = AudioSegment.from_wav("/path/to/file1.wav")
sound2 = AudioSegment.from_wav("/path/to/file2.wav")

combined_sounds = sound1 + sound2
combined_sounds.export("/output/path.wav", format="wav")

note: pydub is a light wrapper around audioop. So behind the scenes, it's doing essentially what Tom10 mentioned


Python ships with the wave module that will do what you need. The example below works when the details of the files (mono or stereo, frame rates, etc) are the same:

import wave

infiles = ["sound_1.wav", "sound_2.wav"]
outfile = "sounds.wav"

data= []
for infile in infiles:
    w = wave.open(infile, 'rb')
    data.append( [w.getparams(), w.readframes(w.getnframes())] )
    w.close()
    
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
for i in range(len(data)):
    output.writeframes(data[i][1])
output.close()

Tags:

Python

Audio

Wav