Skip to content

Instantly share code, notes, and snippets.

@bozzmob
Forked from rohitrangan/JoinMP4.py
Created April 16, 2019 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bozzmob/d0d623d5ea146b9cf0bf7f1853ce1d37 to your computer and use it in GitHub Desktop.
Save bozzmob/d0d623d5ea146b9cf0bf7f1853ce1d37 to your computer and use it in GitHub Desktop.
Combining multiple mp4's to become a single mp4.

A program to convert any given number of mp4's to a single mp4

Requirements:

  • ffmpeg compiled with libx264 and libvorbis. Even ffmpeg without libx264 and libvorbis will do with minor changes to the source code.
  • Python 2.7 (Tested on Python 2.7.1, running on Mac OSX Lion)
  • A shell containing the 'cat' command. (Preferably the BASH Shell)

Precautions:

  • Make sure that you have ample free space on your drive as the conversion from mp4 to mpg increases the file size by a large factor.
  • It is discouraged to merge more than 3-4 mp4's at a time.

Instructions:

  • Copy the code into an empty text file and give it a name, say "JoinMP4.py"
  • Execute chmod u+x /PATH/TO/JoinMP4.py in the BASH shell, giving the path to the created JoinMP4.py.
  • Execute the python script by ./JoinMP4.py
#!/usr/bin/env python
import sys
import time
from subprocess import check_output
for i in range(1, len(sys.argv)):
print sys.argv[i],
fname = "Part" + str(i) + ".mpg"
print fname
check_output(["ffmpeg", "-i", sys.argv[i], "-sameq", fname])
print "Converted all mp4's to mpg's. Now combining them into a single file."
check_output("cat Part*.mpg > ./Final.mpg", shell=True)
print "Removing all the intermediate files..."
time.sleep(3)
check_output("rm Part*.mpg", shell=True)
print "Now converting mpg back to mp4."
print "The size may be smaller than the original mp4 files.",
print "This is because of a change in the audio and video codec."
time.sleep(3)
check_output(["ffmpeg", "-i", "Final.mpg", "-vcodec", "libx264", "-acodec", "libvorbis", "-sameq", "Final.mp4"])
time.sleep(3)
print "Removing the last remaining mpg file..."
check_output("rm Final.mpg", shell=True)
print "Finished merging the files. The output file is Final.mp4"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment