定位 ffmpeg 文本,同时用换行符换行

定位 ffmpeg 文本,同时用换行符换行

如果文本太长,屏幕无法容纳,我想自动将文本换行。

我知道字幕选项但这不是我想要的。当生成包含数百条文本的长视频时,将所有 .srt 文件写入本地存储,然后再删除它们,这实在是太过分了。

我目前尝试使用的是基于此评论。我使用了一种自定义方法,每 N 个字符后添加换行符。但是,在这种情况下,问题是我似乎失去了文本的居中定位,尽管 x、y 设置是正确的:

"-vf", f"drawtext=text='{sentence}':fontsize=24:fontcolor=white:x=(w-text_w)/2:y=(h-text_h)/2"

我的最小可重现示例是:

import subprocess
from pathlib import Path
from langvidgen import FONTS_FOLDER

CURRENT_DIR = Path(__file__).parent.absolute()

font_path = str(FONTS_FOLDER / "Montserrat-MediumItalic.ttf")
font_path = font_path.replace("\\", "\\\\").replace("c:", "c\:")

def split_txt_into_multi_lines(input_str: str, line_length: int):
    words = input_str.split(" ")
    line_count = 0
    split_input = ""
    for word in words:
        line_count += 1
        line_count += len(word)
        if line_count > line_length:
            split_input += "\n"
            line_count = len(word) + 1
            split_input += word
            split_input += " "
        else:
            split_input += word
            split_input += " "
    
    return split_input

sentence = 'This is a long text that won\u2019t fit in a single line. We need to automatically wrap it into multiple lines, depending on its length.'
sentence = split_txt_into_multi_lines(sentence, line_length=30)

ffmpeg_command = [
    "ffmpeg",
    "-y",
    "-f",
    "lavfi",
    "-i",
    "color=c=gray:s=640x480:d=4",
    "-vf",
    f"drawtext=text='{sentence}':fontsize=24:fontcolor=white:x=(w-text_w)/2:y=(h-text_h)/2:fontfile='{font_path}'",
    str(CURRENT_DIR / "output.mp4"),
]

subprocess.run(ffmpeg_command)

出现的内容如下: 在此处输入图片描述

相关内容