Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine audio files in Python

Tags:

python

audio


How can I combined multiple audio files (wav) to one file in Python? I found this:

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])
output.writeframes(data[0][1])
output.writeframes(data[1][1])
output.close()

but this appends one audio file to the other. What I would like to have is code, that "stacks" the audio files (with volume controll please). Is this even possible in Python?

like image 561
CMinusMinus Avatar asked Apr 29 '20 10:04

CMinusMinus


People also ask

Can you combine two audio files?

When you need to merge several songs into a single composition, the easiest way is to use our Online Audio Joiner application. It works in a browser window and you can join MP3 and other format files without installing the software on your computer. Open Online Audio Joiner website.

Can you concatenate WAV files?

Combine WAV Files Online This audio merger is the handy tool that you need – consolidate them without getting a pesky audio watermark! The web tool works fast and is totally user-friendly. No need to download apps or programs, simply upload your files on the page – choose them from your PC, Google Drive, or Dropbox.


1 Answers

You can use the pydub module. It's one of the easiest ways to cut, edit, merge audio files using Python.

Here's an example of how to use it to combine audio files with volume control:

from pydub import AudioSegment
sound1 = AudioSegment.from_file("/path/to/sound.wav", format="wav")
sound2 = AudioSegment.from_file("/path/to/another_sound.wav", format="wav")

# sound1 6 dB louder
louder = sound1 + 6


# sound1, with sound2 appended (use louder instead of sound1 to append the louder version)
combined = sound1 + sound2

# simple export
file_handle = combined.export("/path/to/output.mp3", format="mp3")

To overlay sounds, try this:

from pydub import AudioSegment
sound1 = AudioSegment.from_file("1.wav", format="wav")
sound2 = AudioSegment.from_file("2.wav", format="wav")

# sound1 6 dB louder
louder = sound1 + 6

# Overlay sound2 over sound1 at position 0  (use louder instead of sound1 to use the louder version)
overlay = sound1.overlay(sound2, position=0)


# simple export
file_handle = overlay.export("output.mp3", format="mp3")

Full documentation here pydub API Documentation

like image 60
Thaer A Avatar answered Sep 30 '22 09:09

Thaer A