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

如何通过AssemblyAI生成逐词同步的SRT字幕文件

生成逐词同步的SRT字幕(基于AssemblyAI)

要生成逐词拆分且与音频时间轴同步的SRT字幕,你需要直接利用AssemblyAI转录结果中每个单词的时间戳数据,而非使用默认的句子级字幕导出方法。以下是修改后的完整代码:

import assemblyai as aai
import colorama
from colorama import *
import time
import os

aai.settings.api_key = "(cant share)"

print('')
print('')
print(Fore.GREEN + 'Process 3: Creating subtitles...')
print('')
time.sleep(1)
print(Fore.YELLOW + '>> Creating subtitles...')
transcript = aai.Transcriber().transcribe("output/output-tts.mp3")

# 检查转录是否成功
if transcript.status != aai.TranscriptStatus.completed:
    print(Fore.RED + ">> Transcription failed!")
    exit()

# 定义毫秒转SRT时间格式的函数
def ms_to_srt_time(ms):
    seconds = ms // 1000
    milliseconds = ms % 1000
    minutes = seconds // 60
    seconds = seconds % 60
    hours = minutes // 60
    minutes = minutes % 60
    return f"{hours:02d}:{minutes:02d}:{seconds:02d},{milliseconds:03d}"

# 构建逐词SRT内容
subtitles = []
for idx, word in enumerate(transcript.words, start=1):
    start_time = ms_to_srt_time(word.start)
    end_time = ms_to_srt_time(word.end)
    subtitles.append(f"{idx}\n{start_time} --> {end_time}\n{word.text}\n")

# 合并成完整的SRT字符串
subtitles_content = "\n".join(subtitles)

print('>> Created subtitles!')

# 写入文件(用'w'模式覆盖,避免追加旧内容)
with open("subtitles.srt", "w", encoding="utf-8") as f:
    f.write(subtitles_content)

print('')
print('Program >> You are going to have to manually run the last python file [addsubtitles.py] because \n this program needs to close to write down the subtitles')
print('')
time.sleep(7)

关键修改说明

  • 利用单词时间戳:AssemblyAI返回的transcript.words列表包含每个单词的start(开始时间,毫秒)、end(结束时间,毫秒)和text(单词文本),这是生成逐词字幕的核心数据。
  • 时间格式转换:ms_to_srt_time函数将毫秒值转换为SRT标准的HH:MM:SS,mmm格式。
  • 字幕条目构建:遍历每个单词生成独立的字幕条目,编号从1开始递增。
  • 文件写入优化:使用with语句安全管理文件,并用w模式覆盖写入,避免多次运行时追加旧内容。

修改后生成的SRT示例

1
00:00:00,160 --> 00:00:00,320
Put

2
00:00:00,350 --> 00:00:00,410
a

3
00:00:00,440 --> 00:00:00,680
finger

4
00:00:00,710 --> 00:00:00,950
down
...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:22:55