How to convert a video with Python and FFMpeg

The FFMpeg multimedia framework offers many builtin utilities which can be used to process different types of media files, such as audio, images and videos. Having some practical experience with the ffmpeg tool which is being found in the FFMpeg framework, I can say that its commands are not easy to remember, especially for the beginner who has not any idea how stuff works under the hood.

Since I have some basic knowledge in the Python computer programming language, I have decided to automate some of the ffmpeg’s functionalities by making use of a module called subprocess. Based on my practical experience with the Python’s subprocess module, one can easily make use of it to spawn child processes in their own operating system.

Before going any further with this tutorial, make sure to launch a new Python interactive console in your own operating system. Once you have managed to do that, use the Python import statement to include the subprocess module in your interactive sessions. The command is being shown below.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

import subprocess

The Python’s subprocess module will help us to spawn the child process so we can make use of the ffmpeg tool through our code.

Now let’s define a function which is going to take as input a video for converting it. Make use of the piece of Python code being shown below.

def convert_video(video_input, video_output):
    pass

What we need now is the commands of ffmpeg which can help us to convert our video from one format to another. I highly recommend that you store them inside a list like shown below.

def convert_video(video_input, video_output):
    cmds = ['ffmpeg', '-i', video_input, video_output]

Now we need to add the last part to our function. The final code should look like shown below.

def convert_video(video_input, video_output):
    cmds = ['ffmpeg', '-i', video_input, video_output]
    subprocess.Popen(cmds)

Make use of the function

To make use of the function which we defined above is very easy. It is important that you provide the two arguments, a video_input and a video_output.

The command shown below converts my video test.mp4 to test.avi.

convert_video('test.mp4', 'test.avi')

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

3 thoughts on “How to convert a video with Python and FFMpeg”

  1. Nice tutorial, you can also use this code to cut a video from time and stop time like this:
    ffmpeg -i input.mp4 -ss 00:00:01 -t 30 -c:a copy output.mp4

    Start time == -ss
    Duration == -t ( in seconds from start time)

Leave a Reply

Your email address will not be published. Required fields are marked *