Concatenate mp4 videos of different size with Python and ffmpeg

With this code you can concatenate different videos (.mp4) of different sizes. You need to have ffmpeg installed (it’s free and very powerful). In this code we just use some ffmpeg commands, using Python to look in the actual directory, take all the mp4, transform them in  temporary files (.ts) that are then joined together in one file. I found it helpful and fast. If you need something very fast to concatenate mp4 video files without the need to modify them, this code is for you.

# Code to join different mp4 video files
import glob
import os

def concatenate():
	stringa = "ffmpeg -i \"concat:"
	elenco_video = glob.glob("*.mp4")
	elenco_file_temp = []
	for f in elenco_video:
		file = "temp" + str(elenco_video.index(f) + 1) + ".ts"
		os.system("ffmpeg -i " + f + " -c copy -bsf:v h264_mp4toannexb -f mpegts " + file)
		elenco_file_temp.append(file)
	print(elenco_file_temp)
	for f in elenco_file_temp:
		stringa += f
		if elenco_file_temp.index(f) != len(elenco_file_temp)-1:
			stringa += "|"
		else:
			stringa += "\" -c copy  -bsf:a aac_adtstoasc output.mp4"
	print(stringa)
	os.system(stringa)

concatenate()

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.