Skip to content

FFmpeg utils

Binding function to use FFmpeg.

This module provides Python binding functions to extract/insert subtitles to/from SRT files using FFmpeg.

extract_srt(video_path)

Use FFmpeg to extract subtitles in SRT format. Only the first subtitles track is extracted.

Parameters:

Name Type Description Default
video_path str

Path to the movie file

required

Returns:

Name Type Description
str str

Full subtitles in srt format

Source code in subtitles_translator/ffmpeg_utils.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def extract_srt(video_path: str) -> str:
    """Use FFmpeg to extract subtitles in SRT format. Only the first subtitles track is extracted.

    Args:
        video_path (str): Path to the movie file

    Returns:
        str: Full subtitles in srt format

    """

    # Use subprocess to call FFmpeg CLI
    out = sp.run(["ffmpeg", "-i", video_path, "-map", "s:0", "-f", "srt", "-"], capture_output=True, text=True)

    return out.stdout

insert_srt(video_path, output_path, srt_path)

Use FFmpeg to insert a new subtitles track.

Parameters:

Name Type Description Default
video_path str

Path to the source movie file

required
output_path str

Desired path to the output movie file with new subtitles

required
srt_path str

Path to the SRT subtitles file

required
Source code in subtitles_translator/ffmpeg_utils.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def insert_srt(video_path: str, output_path: str, srt_path: str) -> None:
    """Use FFmpeg to insert a new subtitles track.

    Args:
        video_path (str): Path to the source movie file
        output_path (str): Desired path to the output movie file with new subtitles
        srt_path (str): Path to the SRT subtitles file

    """

    # ffmpeg convert SRT (SubRip) to MP4-compliant subtitles with -c:s mov_text
    sp.run(
        [
            "ffmpeg",
            "-i",
            video_path,
            "-f",
            "srt",
            "-i",
            srt_path,
            "-map",
            "0:0",
            "-map",
            "0:1",
            "-map",
            "1:0",
            "-c:v",
            "copy",
            "-c",
            "copy",
            "-c:s",
            "mov_text",
            output_path,
        ]
    )