如何使用ffmpeg和python向视频中添加文本

5
我一直在尝试使用ffmpeg向AVI视频添加文本,但似乎做不对。请帮忙解决:

import subprocess

ffmpeg = "C:\\ffmpeg_10_6_11.exe"
inVid = "C:\\test_in.avi"
outVid = "C:\\test_out.avi"

proc = subprocess.Popen(ffmpeg + " -i " + inVid + " -vf drawtext=fontfile='arial.ttf'|text='test' -y " + outVid , shell=True, stderr=subprocess.PIPE)
proc.wait()
print proc.stderr.read()

那就是错误信息? - Stu Thompson
我最接近让它工作的一次尝试是出现了一个错误消息,说它无法打开字体文件。 - Jay
2个回答

6

在指定 drawtext 参数时,冒号 ":" 和反斜杠 "\" 具有特殊含义。因此,您可以通过将 ":" 转换为 "\:",并将 "\" 转换为 "\\" 来转义它们。 此外,如果字体文件路径中包含空格,则可以用单引号将其括起来。

因此,您将会得到:

ffmpeg -i C:\Test\rec\vid_1321909320.avi -vf drawtext=fontfile='C\:\\Windows\\Fonts\\arial.ttf':text=test vid_1321909320.flv

5

HA

原来在C:\Windows\Fonts等路径中的双冒号":"起到了分割作用,因此当我输入字体的完整路径时,ffmpeg会按照以下方式读取我的命令:

原始命令

" -vf drawtext=fontfile='C:\\Windows\\fonts\\arial.ttf'|text='test' "

ffmpeg's interpretation

-vf drawtext=  # command

fontfile='C    # C is the font file because the : comes after it signalling the next key

arial.ttf'     # is the next key after fontfile = C (because the C is followed by a : signalling the next key)

:text          # is the value the key "arial.tff" is pointing to

='test'        # is some arb piece of information put in by that silly user

所以要解决这个问题,您需要在字体文件路径中去掉“:”。

最终的工作代码:

import subprocess

ffmpeg = "C:\\ffmpeg_10_6_11.exe"
inVid = "C:\\test_in.avi"
outVid = "C:\\test_out.avi"

subprocess.Popen(ffmpeg + " -i " + inVid + ''' -vf drawtext=fontfile=/Windows/Fonts/arial.ttf:text=test ''' + outVid , shell=True)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接