FFmpeg Modify Video Bitrate in Python: A Step Guide

By | December 17, 2024

It is easy to modify a video bitrate using ffmpeg. In this tutorial, we will use some examples to show you how to do.

Modify video bitrate

We can use ffmpeg command to change the bitrate of a video for compressing.

Here is a python example:

def runcmd(cmd):
    p1 = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)

    msg_content = ''
    for line in p1.stdout:
        print(line)
        l = line.decode(encoding="utf-8", errors="ignore")
        msg_content += l
    p1.wait()
    return msg_content
def compress(mp4_file_in, mp4_file_out, bitrate = "100k"):
    cmd = f'ffmpeg -i {mp4_file_in} -c:v libx264 -b:v {bitrate} -c:a copy {mp4_file_out}'
    print(cmd)
    runcmd(cmd)

In this example, we will use python subprocess.Popen() to run ffmpeg command to change the bitrate of a mp4 file.

How to get the bitrate of a video?

We can use ffprobe to extract the bitrate of a video. Here is an example:

def getbitrate(mp4_file_in):
    cmd = f'ffprobe -v error -show_entries stream=width,height,bit_rate,duration -of default=noprint_wrappers=1 {mp4_file_in}'
    ctx = runcmd(cmd)
    ts = ctx.split("\n")
    tag = "bit_rate="
    for t in ts:
        if tag in t:
            t = t.strip()
            t = t.replace(tag, "")
            bit_rate = int(t)
            print("bit_rate = ", bit_rate)
            return bit_rate
    return ""

In this example, we also run ffprobe command in python to get the bitrate information of a mp4 file.

FFmpeg Modify Video Bitrate in Python

Then we can change the value of the bitrate to compress a mp4 file.

bitrate = int(getbitrate(wave_in)*0.8)

Leave a Reply