如何用Python将Azure连续Speech to Text结果保存至文件?代码排查
连续语音识别结果无法写入文件的问题排查
核心问题:回调函数中的结果类型判断错误
你的recognized_cb函数错误地将speechsdk.ResultReason.RecognizingSpeech作为判断条件,但这个枚举值对应**实时中间识别事件(Recognizing)**的结果类型;而recognized事件触发时,成功识别的最终结果类型是speechsdk.ResultReason.RecognizedSpeech。这直接导致回调内的写入逻辑永远不会执行,最终文件内容为空。
修复后的代码
修正recognized_cb函数
def recognized_cb(evt : speechsdk.SpeechRecognitionEventArgs) : # 针对最终识别成功的结果执行写入 if speechsdk.ResultReason.RecognizedSpeech == evt.result.reason and len(evt.result.text) > 0 : print('RECOGNIZED:', evt.result.text) output_file.write(evt.result.text + '\n') # 添加换行符优化可读性 output_file.flush() # 可选:补充识别失败场景的日志 elif speechsdk.ResultReason.NoMatch == evt.result.reason: print(f'识别无匹配: {evt.result.no_match_details}') elif speechsdk.ResultReason.Canceled == evt.result.reason: print(f'识别被取消: {evt.result.cancellation_details}')
额外优化建议
- 用
with语句管理文件:避免因异常导致文件未正常关闭,替换原有的文件打开方式:
# 替换原文件打开代码,后续所有逻辑嵌套在with块内 with open(outputfile, "w") as output_file: done = False def stop_cb(evt): print('CLOSING on {}'.format(evt)) speech_recognizer.stop_continuous_recognition() print("Transcript saved in file:", outputfile) nonlocal done done = True def recognized_cb(evt : speechsdk.SpeechRecognitionEventArgs) : # 这里放修正后的识别逻辑 ... # 事件绑定、启动识别等逻辑都放在with块内 ...
使用with语句后,文件会在块结束后自动关闭,无需手动调用output_file.close()。
- 区分中间与最终结果:如果需要记录实时中间识别结果,可以保留
recognizing事件的回调,单独处理中间结果的写入(若有需求)。
验证步骤
- 运行修正后的代码,确认控制台
RECOGNIZED:日志正常打印。 - 识别完成后,检查输出文件是否有内容,且每个识别片段以换行分隔。
内容的提问来源于stack exchange,提问作者Wendy De Wit
相关产品推荐
相关产品推荐

