Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mix audio files using python?

Tags:

python

audio

mp3

I would like to do basic audio mixing in python.

To give an example: I would like to take two mp3 files and add them together and return one mp3 file. Another example: I would like to take the first ten seconds of one mp3 file and add it to the beginning of another mp3 file.

What is the best way to accomplish these tasks? I would like to use built in python functions like audioop but can not find any good tutorials or sample code out there for using the built in functions.

I am going through the docs but I am pretty confused and cannot figure out how to do things like this. I am not even sure that the python libraries like mp3's. Most of the stuff I have looked at seem to refer to WAV files. So, if this is the case, I guess a follow up question would be is there an easy way to convert an mp3 to a WAV for manipulation and back again?

like image 911
user439299 Avatar asked Oct 02 '11 23:10

user439299


2 Answers

You can do this pretty easily using pydub:

from pydub import AudioSegment

sound1 = AudioSegment.from_mp3("/path/to/file1.mp3")
sound2 = AudioSegment.from_mp3("/path/to/file1.mp3")

# mix sound2 with sound1, starting at 5000ms into sound1)
output = sound1.overlay(sound2, position=5000)

# save the result
output.export("mixed_sounds.mp3", format="mp3")
like image 61
Jiaaro Avatar answered Nov 08 '22 07:11

Jiaaro


You could check out some of the code in the python audiotools project. It is a collection of command-line utilities which make use of a common python package. There is a utility included with audiotools (trackcat) which can con*cat*enate two or more audio tracks; another (tracksplit) can split an audio track (using a .cue file). These, as well as the numerous other included utilities, can work with audio files of various encodings, including mp3.

like image 41
intuited Avatar answered Nov 08 '22 06:11

intuited