Auto-splitting video file in equal chunks with ffmpeg and python

Recently I needed to upload a whole bunch of long video files. Maximum allowed length for each video was just few minutes, while the actual length of files I tried to upload were about an hour each. FFmpeg is really great for splitting the video files and Python is quite handy for automating the task. Combining two together in this handy little script(see below). The script below takes a video file and a chunk size in seconds and splits the video file into chunks using ffmpeg, so each chunk is self contained, playable video.

19 thoughts on “Auto-splitting video file in equal chunks with ffmpeg and python”

I found this blog entry to be just what i needed. I am currently trying to split a single video file into several pieces. However, after tinkering around with your script, i have a few questions that i need help with:

1. What video files is the script meant for? I tinkered with AVI, MOV, and WMV so far, and i’m not having much luck getting mov and wmv to split and play correctly.
2. Although my avi file does get split, i hit two problems:
___a. some of the split files aren’t the correct chunk size (ie. i had the split_size = 30 (seconds), yet some of the files were 60 or more
___b. the first split file played the video correctly, but the rest merely displayed a still image and audio continued. Know what is happening?
3. Could you point me in the right direction to learn more about ffmpeg btw?

Glad that you found this useful.
In regards to your questions:
1. This script is really just a convenience wrapper around FFmpeg, so you can use whatever formats your install of ffmpeg supports. To add support for more formats you may need to recompile ffmpeg. For mov and wmv you need to make sure you have appropriate codes. I think you need libx264 for mov. Not sure what you need to wmv. Try googling ffmpeg wmv or something like that

2. This might be a bug… or your ffmpeg missing some libs. Can you upload your avi file to something like http//ge.tt and give me a link to take a look at? Also what command line params did u use?

3. FFmpeg docs are pretty good – http://www.ffmpeg.org/ffmpeg-doc.html but might be a bit rigid. Just google for ffmpeg commands to get a bunch of articles about various handy things you can do with it

I know this is somewhat late from when this was originally posted, but for me this script raises an invalid range() argument exception – math.ceil() returns a float (at least for me in python 2.7.1 and all 2.x.x as far as I recall). Thus line 33 should read:

I put the int fix in and added -acodec copy but also changed ffmpeg instances to avconv. Worked on large mp4 videos.
Thanks very much for the script.
Now I can incorporate it all into a batch spilitter in bash.