流程原理:ffmpeg对生成srt格式转ass格式,然后把ass文件嵌入视频中
def convert_srt_to_ass(srt_file, ass_file):
# Step 1: Generate intermediate ASS file from SRT
intermediate_ass_file = 'intermediate.ass'
command = f'ffmpeg -i "{srt_file}" "{intermediate_ass_file}"'
os.system(command)
# Step 2: Read the template ASS file and add subtitle events
with open('template.ass', 'r', encoding='utf-8') as template_file:
template_content = template_file.read()
# Read intermediate ASS file to get subtitle events
with open(intermediate_ass_file, 'r', encoding='utf-8') as intermediate_file:
events = []
events_started = False
for line in intermediate_file:
if events_started:
events.append(line.strip())
if '[Events]' in line:
events_started = True
# Create final ASS content
final_content = template_content + '\n' + '\n'.join(events)
# Write to the final ASS file
with open(ass_file, 'w', encoding='utf-8') as output_file:
output_file.write(final_content)
# Clean up intermediate file
os.remove(intermediate_ass_file)
ass_file = f"0.ass"
srt_text = "0.srt"
convert_srt_to_ass(srt_text, ass_file)
os.system(f'ffmpeg -i input.mp4 -vf ass={ass_file} output.mp4')
0.srt中的部分内容
1
00:00:00,000 --> 00:00:09,087
嗨大家好,今天我要和你们分享一些超级酷的摄影装备。不管你是专业摄影师还是摄影师,还是摄影爱好者,都一定会喜欢。
2
00:00:09,087 --> 00:00:15,921
首先给大家介绍这款最新的单反相机,它有着超高的像素和超快的对焦速度。
3
00:00:15,921 --> 00:00:19,959
拍出来的照片细节超清晰,色彩也非常真实。
4
00:00:19,959 --> 00:00:25,098
不管是拍风景,还是人物,都能轻松搞定,再来看看这个镜头。
template.ass中ass模板内容
[Script Info]
Title: Default ASS File
ScriptType: v4.00+
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,7,&H00FFFFFF,&H000000FF,&H00000000,&H64000000,-1,0,0,0,100,100,0,0,1,1,0,2,10,10,10,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text