I would like to automatically wrap text in multiple lines if it is too long to fit on the screen.
I know about the subtitle option but it is not what I am seeking for. When generating a long video with hundreds of texts, it would be an overkill to have all those I/O operations of writing each of these .srt files to local storage, just to then have to remove them.
What I am currently attempting to use is based on this comment. I'm using a custom method that adds newlines after every N number of characters. The problem in this case, however, is that I seem to lose the centered positioning of my text, despite the x, y setting being correct:
"-vf", f"drawtext=text='{sentence}':fontsize=24:fontcolor=white:x=(w-text_w)/2:y=(h-text_h)/2"
My minimal reproducible example is:
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)