Files
ai-short-video-generator-20…/core/subtitle.py
T

49 lines
1.4 KiB
Python

# -*- coding: utf-8 -*-
"""字幕生成模块
根据每段文本的时长估算字幕时间轴,生成 SRT 文件。
"""
import os
def _fmt_time(seconds: float) -> str:
"""将秒数转换为 SRT 时间格式 HH:MM:SS,mmm"""
ms = int((seconds - int(seconds)) * 1000)
s = int(seconds) % 60
m = int(seconds) // 60 % 60
h = int(seconds) // 3600
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
def build_srt(scenes: list, durations: list, out_path: str) -> str:
"""根据场景文本和每段时长生成 SRT 字幕。
Args:
scenes: [{"index":1,"text":"..."}, ...]
durations: 每段音频时长(秒),与 scenes 一一对应
out_path: 输出 .srt 路径
Returns:
str: 输出文件路径
"""
os.makedirs(os.path.dirname(out_path), exist_ok=True)
lines = []
cursor = 0.0
for i, (scene, dur) in enumerate(zip(scenes, durations), start=1):
start = cursor
end = cursor + dur
lines.append(str(i))
lines.append(f"{_fmt_time(start)} --> {_fmt_time(end)}")
lines.append(scene["text"])
lines.append("")
cursor = end
with open(out_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
return out_path
if __name__ == "__main__":
scenes = [{"index": 1, "text": "你好世界"}, {"index": 2, "text": "再见世界"}]
print(build_srt(scenes, [2.0, 3.0], "output/subtitle/demo.srt"))