Merging audio and video using ffmpeg in python

1.5k views Asked by At

I am trying to merge two files (.mp3 & .mp4) to a single .mp4

The videos and audio are located in the same folder as my main.py, and aren't corrupted

Here is the code that seems to create the error:

    if (haveAudio):
        infile1 = ffmpeg.input(title+"_video.mp4")
        infile2 = ffmpeg.input(title+"_audio.mp3")

        merged  = ffmpeg.concat(infile1, infile2, v=1, a=1)
        output  = ffmpeg.output(merged[0], merged[1], title+".mp4")

I am getting an error on the last line:

Traceback (most recent call last):
  File "C:\Users\...\projectName\main.py", line 67, in <module>
    output  = ffmpeg.output(merged[0], merged[1], title+".mp4")
  File "C:\Users\...\Python\Python39\lib\site-packages\ffmpeg\nodes.py", line 70, in __getitem__
    raise TypeError("Expected string index (e.g. 'a'); got {!r}".format(index))
TypeError: Expected string index (e.g. 'a'); got 0

My guess would be that an argument is missing when calling ffmpeg.output() but based on the documentation it seems correct.

1

There are 1 answers

3
Adrian Ang On BEST ANSWER

I learnt from this tutorial: https://github.com/JNYH/pytube/blob/master/pytube_sample_code.ipynb

I used below 2 ways and they both worked for me:

audio = ffmpeg.input('audio.mp3')
video = ffmpeg.input('video.mp4')

ffmpeg.output(audio, video, 'my_file.mp4').run()

or

ffmpeg.concat(video, audio, v=1, a=1).output('my_file.mp4').run(overwrite_output=True)