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

如何使用Python的Moviepy库为视频添加多个文本字幕?

Python 视频添加字幕实现代码

使用前请先安装依赖库moviepy,安装命令:pip install moviepy。

部分场景下我们需要为视频添加字幕,在处理视频描述、字幕生成相关需求时,以下代码可以直接实现对应功能,有需要的开发者可以直接调试使用。

单条字幕添加实现

适用于只需添加单条固定字幕的场景,可调整字体、字号、颜色、显示位置、时长等参数实现自定义效果。

import moviepy.editor as mp


my_video = mp.VideoFileClip("video.mp4") # 视频路径
w,h = moviesize = my_video.size
# TextClip参数可自定义调整字幕内容、字体、颜色、字号
my_text = mp.TextClip("A man and a women are sitting on a bench", font="Amiri-regular", color="white", fontsize=34)
txt_col = my_text.on_color(size=(my_video.w + my_text.w, my_text.h+5), color=(0,0,0), pos=(6,"center"), col_opacity=0.6)
txt_mov = txt_col.set_pos( lambda t: (max(w/30,int(w-0.5*w*t)),max(5*h/6,int(100*t))) )
final = mp.CompositeVideoClip([my_video,txt_mov])
# subclip参数为字幕生效的视频时间段,单位为秒
final.subclip(0,17).write_videofile("final.mp4",fps=24,codec="libx264")

批量多条字幕添加实现

适用于需要给视频不同时间段添加多条字幕的场景,支持从txt文件读取字幕内容批量生成:

"""单视频插入多条字幕"""

import moviepy.editor as mp


my_video = mp.VideoFileClip("/home/user/cap/video.mp4").subclip(0,10)
print(my_video.duration)
w,h = moviesize = my_video.size

texts = []
# 从txt文件逐行读取字幕内容
with open("/home/user/cap/caption.txt") as file:
    for line in file: 
        line = line.strip() # 可根据需求自行添加字幕预处理逻辑
        texts.append(line)

print(type(texts))

starts = [0,2,4,6,8,10,12,14,16,18,20] # 各字幕的开始显示时间,单位为秒,可自定义修改
durations = [2,2,2,2,2] # 各字幕的显示时长,单位为秒
t = 0
txt_clips = []
for text,t,duration in zip(texts, starts, durations):
  txt_clip = mp.TextClip(text,font="Amiri-regular", color="black", fontsize=29)
  txt_clip = txt_clip.set_start(t)
  txt_col = txt_clip.on_color(size=(my_video.w + txt_clip.w, txt_clip.h+5), color=(0,0,0), pos=(6,"center"), col_opacity=0.6)
  txt_clip = txt_clip.set_pos( lambda t: (max(w/30,int(w-0.5*w*t)),max(5*h/6,int(100*t))) ).set_duration(duration)
  txt_clips.append(txt_clip) 
  print(txt_clips)
  print(type(txt_clips))

   
final_video = mp.CompositeVideoClip([my_video, *txt_clips])

final_video.write_videofile("TEXT.mp4",fps=24)

内容的提问来源于stack exchange,提问作者Sumathi J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 09:09:02