You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现批量自动给多部电影嵌入字幕?

批量给MP4影片嵌入SRT字幕的Python脚本

这个脚本可以批量处理当前目录下的MP4视频,核心功能如下:

  • 自动遍历所有MP4格式文件,跳过已处理过(文件名含wsubs)的视频
  • 若找到对应同名的SRT字幕文件,先尝试将字幕编码转为UTF-8(解决非UTF-8字幕导致ffmpeg报错的问题)
  • 调用ffmpeg生成嵌入硬字幕的新视频,新文件命名为原文件名末尾加-wsubs.mp4,原始视频和字幕文件均会保留
import glob
import os

for filename in glob.glob("*.mp4"):
    print(str(filename))
    if 'wsubs' not in filename:
        for legenda in glob.glob(filename.replace(".mp4",".srt")):
            try:
                with open(legenda, 'r') as arquivo_orig:
                    conteudo = arquivo_orig.read()
                with open(legenda, 'w', encoding='utf-8') as novo_arquivo:
                    novo_arquivo.write(conteudo)
            except Exception as e:
                print("字幕已是UTF-8编码")
            print(str(legenda))
            os.system('ffmpeg -i "' + str(filename) + '" -vf subtitles="' + str(legenda) + '" -maxrate 2000000 -crf 20 "' + str(filename.replace('.mp4','-wsubs.mp4')) + '"')

关键细节说明:

  • 字幕编码转换:如果字幕原本就是UTF-8编码,读取时会触发异常,此时会打印提示并跳过转换步骤
  • ffmpeg参数解析:
    • -vf subtitles="xxx.srt":将指定字幕作为视频滤镜嵌入画面(硬字幕,无法后期移除)
    • -maxrate 2000000:限制视频最大码率为2Mbps,避免输出文件体积过大
    • -crf 20:恒定质量控制参数,数值越小视频质量越高,18-28是主流推荐范围,20属于高质量区间

内容的提问来源于stack exchange,提问作者Ricardo Madela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:52:45