如何通过DaVinci Resolve Python API在指定视频轨道上插入Text+片段?
如何通过DaVinci Resolve Python API在指定视频轨道上插入Text+片段?
嘿,我来帮你搞定这个DaVinci Resolve脚本自动插入Text+的问题!刚好我之前也做过类似的对话视频自动化项目,给你一步步拆解怎么做,连代码示例都给你备好:
第一步:先搞定Resolve API的基础连接
首先得确保你的Python环境能访问Resolve的脚本模块,然后连接到当前打开的项目和时间线:
import DaVinciResolveScript as dvr_script # 初始化Resolve连接 resolve = dvr_script.scriptapp("Resolve") if not resolve: print("先打开DaVinci Resolve并加载项目啊老铁!") exit() # 获取当前项目和时间线 project_manager = resolve.GetProjectManager() current_project = project_manager.GetCurrentProject() current_timeline = current_project.GetCurrentTimeline() # 做个简单校验,避免空指针报错 if not current_project or not current_timeline: print("要么没打开项目,要么没创建时间线,先搞定这俩!") exit()
第二步:准备你的对话JSON数据
先把你没写完的JSON补全,比如加上每个台词的起始/结束帧(或者后续根据音频时长计算),示例如下:
假设你的
dialogue_data.json内容是这样:
[ { "sequence": 1, "response": "Hi", "start_frame": 10, "end_frame": 30, "speaker": "小明" }, { "sequence": 2, "response": "你好呀!", "start_frame": 35, "end_frame": 55, "speaker": "小红" } ]
第三步:核心逻辑——批量创建并插入Text+到指定轨道
接下来写核心代码,读取JSON里的台词,创建Text+片段,设置样式,再精准插入到你指定的视频轨道上:
import json # 读取对话数据 with open("dialogue_data.json", "r", encoding="utf-8") as f: dialogue_list = json.load(f) # 指定要插入的目标视频轨道(Resolve轨道索引从1开始,比如轨道2) target_track = 2 media_pool = current_project.GetMediaPool() for dialogue in dialogue_list: seq_num = dialogue["sequence"] text_content = dialogue["response"] start_frame = dialogue["start_frame"] end_frame = dialogue["end_frame"] speaker = dialogue.get("speaker", "") # 1. 创建Text+标题片段(会自动加到媒体池) text_clip = media_pool.CreateTitleClip("Text+") if not text_clip: print(f"第{seq_num}条对话的Text+创建失败,跳过!") continue # 2. 给Text+设置内容和样式 # 切到编辑页面,确保能操作检查器 resolve.OpenPage("edit") # 把刚创建的Text+加载到检查器 current_timeline.SetCurrentClip(text_clip) inspector = resolve.GetInspector() # 设置主台词文本 inspector.SetParamValue("Input.Text", text_content) # 如果有说话人,添加第二行文本并调整位置 if speaker: inspector.SetParamValue("Input.Text2", speaker) inspector.SetParamValue("Input.Position2", [0.5, 0.8]) # 放在主文本上方居中 # 自定义样式(字体、大小、颜色这些,按需改) inspector.SetParamValue("Input.Font", "微软雅黑") inspector.SetParamValue("Input.Size", 60) inspector.SetParamValue("Input.Color", [1, 1, 1, 1]) # 白色文本 # 3. 计算片段时长 clip_duration = end_frame - start_frame + 1 # 4. 精准插入到指定轨道的对应帧位置 current_timeline.InsertIntoTimeline({ "mediaPoolItem": text_clip, "startFrame": start_frame, "trackIndex": target_track, "duration": clip_duration }) print(f"第{seq_num}条对话的Text+已经乖乖躺在轨道{target_track}上啦!")
几个要注意的坑
- 轨道索引:Resolve的轨道是从1开始计数的,别写成0了!
- 参数名准确:如果要改更多Text+样式,比如描边、阴影,右键Resolve检查器里的参数名,选「Copy Parameter Name」就能拿到准确的键名,替换代码里的参数就行。
- 运行环境:要么在Resolve自带的脚本控制台(菜单>工作区>脚本控制台)运行,要么外部Python环境要配置好Resolve的脚本路径(Windows一般在
C:\Program Files\Blackmagic Design\DaVinci Resolve\fusionscript.dll,Mac在/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Scripting/Modules)。 - 音频同步:如果你的JSON里没有起始/结束帧,可以先把音频导入时间线,通过
current_timeline.GetItemListInTrack("audio", track_num)获取音频片段的起始帧和时长,再对应设置Text+的位置。
内容来源于stack exchange




