CMJ
CMJ

Reputation: 131

Combine two audio files in Python

I have two audiofiles:

'Users/x/Songs/1.mp4'
'Users/x/Songs/2.mp4'

I would like to join these to one audio file, where the two files play right after each other:

'Users/x/Songs/combined.mp4'

I'm using PyCharm on my Macbook to achieve this. Is there a way to do it? I saw a solution is to use this code:

from glob import iglob
import shutil
import os

PATH = r'/Users/x/Songs'

destination = open('everything.mp4', 'wb')
for filename in iglob(os.path.join(PATH, '*.mp4')):
    shutil.copyfileobj(open(filename, 'rb'), destination)
destination.close()

But whenever I do this, I only get the last audio clip in the file called 'everything.mp4'.

Not sure what the code above does but found it as an answer to another question like the one I have.

Upvotes: 0

Views: 1066

Answers (1)

somebody32x2
somebody32x2

Reputation: 21

I am a little confused as to why you are using an mp4 (video) file for audio.

This stack overflow post about joining wav files might work in combination with the python AudioConverter module

It might look something like this:

import audioconverter
import audiolab, scipy
audioconvert convert wavfiledir/ outputdir/ --output-format .wav
a, fs, enc = audiolab.wavread('file1.wav')
b, fs, enc = audiolab.wavread('file2.wav')
c = scipy.vstack((a,b))
audiolab.wavwrite(c, 'file3.wav', fs, enc)

keep in mind you will need ffmpeg and with this solution you will lose any video (not audio) if you have any.

A couple other possible solutions https://www.codegrepper.com/code-examples/python/merge+all+mp4+video+files+into+one+file+python

https://pythonprogramming.altervista.org/join-all-mp4-with-python-and-ffmpeg/

https://gist.github.com/rohitrangan/3841212

Upvotes: 1

Related Questions