Photo by Jakob Owens on Unsplash

How to trim a video with Python ffmpeg

Jerry
2 min readApr 21, 2023

--

ffmpeg-python is a Python wrapper for FFmpeg, a powerful multimedia framework that allows us to convert, record, and stream audio and video files. ffmpeg-python provides a more convenient and Pythonic way to use FFmpeg in our Python scripts. In this tutorial, we’ll explore how to use ffmpeg-python to trim a video.

Installing ffmpeg-python

Before we can use ffmpeg-python in our Python scripts, we need to install it on our system. We can install ffmpeg-python using pip, the Python package manager. We can use the following command to install ffmpeg-python:

pip install ffmpeg-python

Once we have installed ffmpeg-python, we can verify that it’s installed correctly by running the following command in the Python shell:

import ffmpeg

If we don’t get any errors, it means that ffmpeg-python is installed correctly and we can start using it in our Python scripts.

Trimming a Video

To trim a video using ffmpeg-python, we need to specify the start and end times of the video segment that we want to keep. We can do this by using the trim filter in FFmpeg.

The following example shows how to use ffmpeg-python to trim a video:

import ffmpeg

input_file = ffmpeg.input('input.mp4')
output_file = ffmpeg.output(input_file.trim(start_frame=100, end_frame=200), 'output.mp4')
ffmpeg.run(output_file)

In this example, we create an input object by calling the ffmpeg.input function and passing the name of the input file. We then create an output object by calling the ffmpeg.output function and passing the trim filter as an argument. The trim filter takes two arguments, start_frame and end_frame, which specify the start and end times of the video segment that we want to keep.

Note that we use the start_frame and end_frame arguments instead of the start and end arguments. This is because the trim filter works with video frames rather than time units. We can convert time units to frame numbers by multiplying the time value by the frame rate of the video.

We then call the ffmpeg.run function and pass the output object to it.

Conclusion

In this tutorial, we’ve explored how to use ffmpeg-python to trim a video. ffmpeg-python provides a more convenient and Pythonic way to use FFmpeg in our Python scripts, allowing us to write Python code that is more readable and easier to maintain. We’ve covered an example of how to trim a video using the `trim` filter in FFmpeg. ffmpeg-python provides many more options and arguments that we can use to perform various multimedia processing tasks, and we can refer to the ffmpeg-python documentation for more information on how to use ffmpeg-python to perform specific tasks.

--

--