Python and FFmpeg Guide
FFmpeg is the leading multimedia framework, able to decode, encode, transcode, mux, demux, stream, filter and play pretty much anything that humans and machines have created. Python is often used to automate FFmpeg commands for batch processing video and audio.
Prerequisites
- Install FFmpeg: You must have the
ffmpegexecutable installed on your system and added to your PATH.- Windows: Download from ffmpeg.org or use
winget install ffmpeg. - macOS:
brew install ffmpeg. - Linux:
sudo apt install ffmpeg.
- Windows: Download from ffmpeg.org or use
Method 1: Using subprocess (Standard Library)
The most direct way to use FFmpeg is by calling the command line tool using Python's built-in subprocess module.
Basic Conversion
import subprocess
# Convert input.mp4 to output.avi
command = ['ffmpeg', '-i', 'input.mp4', 'output.avi']
subprocess.run(command)
Suppressing Output
FFmpeg is very verbose. You can suppress the output using subprocess.DEVNULL.
import subprocess
subprocess.run(['ffmpeg', '-i', 'input.mp4', 'output.mp3'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
Method 2: Using ffmpeg-python (Wrapper Library)
For complex filters and pipelines, constructing command line strings can be error-prone. The ffmpeg-python library provides a Pythonic interface.
Installation
pip install ffmpeg-python
Basic Usage
import ffmpeg
stream = ffmpeg.input('input.mp4')
stream = ffmpeg.output(stream, 'output.mp4')
ffmpeg.run(stream)
Complex Filters (Flip and Resize)
import ffmpeg
(
ffmpeg
.input('input.mp4')
.hflip() # Horizontal flip
.filter('scale', size='1280:720') # Resize
.output('output.mp4')
.run()
)
Common Tasks
Extract Audio from Video
import subprocess
# -vn disables video recording
cmd = ['ffmpeg', '-i', 'video.mp4', '-vn', 'audio.mp3']
subprocess.run(cmd)
Get Video Metadata (ffprobe)
You can use ffprobe to get JSON metadata about a file.
import ffmpeg
try:
probe = ffmpeg.probe('video.mp4')
video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
width = int(video_stream['width'])
height = int(video_stream['height'])
print(f"Resolution: {width}x{height}")
except ffmpeg.Error as e:
print(e.stderr)