Combine WAV Files to One File Using Python – Python Tutorial

By | December 28, 2021

In this tutorial, we will introduce you how to combine several wav files to one big one by python. You can learn how to do by following our steps.

Preliminary

We will use python soundfile package to implement it, you can install it.

pip install SoundFile

There are two types of combining wav files: add or concatenate. We will introduce one by one.

Read wav file data

In order to combine wav files, we should read its data.

import random
import soundfile as sf
import numpy as np

s1 = '1.wav'
s2 = '2.wav'
s1_wav_data, _ = sf.read(s1, dtype='float32')
s2_wav_data, _ = sf.read(s2, dtype='float32')

In this example, s1 and s2 are two wav files, the sample rate of them are 8,000 and single channel.

You also can use scipy.io.wavfile.read() and librosa.load() to read a wav file, here is the tutorial:

The Difference Between scipy.io.wavfile.read() and librosa.load() in Python – Python Tutorial

Combine wav files by adding

We can add s1 and s2 to combine them.

For example, s1 is 60 seconds, s2 is also 60 seconds, the combined wav file s3 will also be 60 seconds.

s3_wav_data = s1_wav_data + s2_wav_data

However, if the length of them are different, we can cut the longer one.

s1_wav_len = s1_wav_data.shape[0]
s2_wav_len = s2_wav_data.shape[0]
       
min_length = min(s1_wav_len, s2_wav_len)

s1 and s2 are single channel audio files, we can use s1_wav_data.shape[0] and s2_wav_data.shape[0] to get their length.

Then, we can combine them by adding.

s3_wav_data = s1_wav_data + s2_wav_data

Save combined file

We can use code below to save combined wav file.

s3 = '3.wav'
sf.write(s3, s3_wav_data, 8000, 'PCM_16')

Combine wav files by concatenating

It is very easy, we will concatenate s1 and s2

s3_wav_data = np.concatenate([s1_wav_data, s2_wav_data])

Then we can save s3_wav_data.

Leave a Reply

Your email address will not be published. Required fields are marked *