17


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?

1

1 Answer 1

43

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but that just appends the audio. What I want is, that the audio is layered, so one audio over the other
@ProgrammerJonas I've edited my answer to include an example for overlaying one sound on another. If you find it helpful, please mark the question as answered, otherwise please let us know what didn't work
thank you. but what if I had a streaming of pcm chunks to deliver as a mp3 streaming? how to stream without waiting for a complete mp3 but streaming while pcm chunks arrive?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.