如何将语音识别文本转换为标准.srt字幕并实现停顿分段?
实现带时间轴的SRT字幕生成
你当前的代码只能获取完整的识别文本,无法拿到语音停顿的时间戳,要生成标准SRT字幕,需要换用支持返回时间戳信息的语音识别工具,这里推荐使用OpenAI的Whisper模型——它本地即可运行,能返回词级或句子级的时间戳,完全满足需求。
步骤1:安装依赖
先安装Whisper和必要的音频处理库:
pip install openai-whisper ffmpeg-python
步骤2:带时间戳的语音识别与SRT生成
替换原有的识别代码,用Whisper完成转录并生成SRT文件:
import whisper from datetime import timedelta def format_time(seconds): """将秒数格式化为SRT要求的时间格式:HH:MM:SS,mmm""" td = timedelta(seconds=seconds) hours = td.seconds // 3600 minutes = (td.seconds % 3600) // 60 secs = td.seconds % 60 millis = td.microseconds // 1000 return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}" def generate_srt(audio_path, output_srt_path): # 加载Whisper模型(可选base/small/large等,越大精度越高) model = whisper.load_model("base") # 开启word_timestamps获取词级时间戳,方便分割字幕 result = model.transcribe(audio_path, word_timestamps=True) srt_content = [] subtitle_index = 1 current_start = None current_text = [] max_words_per_subtitle = 8 # 控制每个字幕的单词数,避免过长 for segment in result["segments"]: for word in segment["words"]: if current_start is None: current_start = word["start"] current_text.append(word["word"]) # 当达到指定单词数,或遇到标点结尾时,生成一个字幕片段 if len(current_text) >= max_words_per_subtitle or word["word"].strip()[-1] in ".!?": current_end = word["end"] # 格式化时间 start_time = format_time(current_start) end_time = format_time(current_end) # 拼接字幕内容 srt_content.append(f"{subtitle_index}") srt_content.append(f"{start_time} --> {end_time}") srt_content.append(" ".join(current_text).strip().capitalize()) srt_content.append("") # 空行分隔字幕 subtitle_index += 1 current_start = None current_text = [] # 处理最后一段剩余的文本 if current_text: current_end = segment["words"][-1]["end"] start_time = format_time(current_start) end_time = format_time(current_end) srt_content.append(f"{subtitle_index}") srt_content.append(f"{start_time} --> {end_time}") srt_content.append(" ".join(current_text).strip().capitalize()) srt_content.append("") # 写入SRT文件 with open(output_srt_path, "w", encoding="utf-8") as f: f.write("\n".join(srt_content)) # 调用函数生成SRT generate_srt("intro.wav", "intro.srt")
代码说明
format_time函数:将Whisper返回的秒数转换为SRT标准的时间格式(比如00:00:01,510)。- 字幕分割逻辑:通过控制每个字幕的单词数(
max_words_per_subtitle)和标点符号,自动识别语音停顿点,生成符合阅读习惯的字幕片段。 - Whisper模型选择:
base模型体积小、速度快,适合快速测试;如果需要更高精度(比如识别专业术语、口音),可以换成small或large模型。
生成的SRT示例
运行后生成的intro.srt内容会类似:
1 00:00:01,510 --> 00:00:05,860 This is chapter 1 of the flask mega tutorial welcome. 2 00:00:05,860 --> 00:00:11,270 Before we begin i want to spend a couple of minutes showing you how you can work.
内容的提问来源于stack exchange,提问作者Oliveira
相关产品推荐
相关产品推荐

