Windows环境下Python调用Azure TTS无输出问题求助
解决Azure Cognitive Speech TTS在Windows无输出的问题
核心原因
代码中使用了异步方法speak_text_async()但未等待任务完成,Windows进程会在异步任务结束前直接退出,导致音频文件无法生成;而Linux/macOS的进程生命周期机制不同,能默认等待异步任务完成。
修复步骤
- 等待异步任务完成:调用
speak_text_async()后必须用.get()方法阻塞进程,直到合成任务结束。 - 验证密钥与区域:替换代码中占位符
subscription="API"和region="asdasd"为实际有效的Azure订阅密钥和服务区域(如eastus),无效参数会导致无输出。 - 检查文件权限与路径:确保程序有当前目录的写入权限,或改用绝对路径指定输出文件位置。
- 添加错误排查逻辑:通过结果对象判断合成状态,快速定位问题。
修复后完整代码
import azure.cognitiveservices.speech as speechsdk from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer from azure.cognitiveservices.speech.audio import AudioOutputConfig close_file = "tes.wav" closer = "placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups." # 替换为你的Azure订阅密钥和服务区域 speech_config = SpeechConfig(subscription="你的Azure订阅密钥", region="你的服务区域") speech_config.speech_synthesis_voice_name = "en-US-GuyNeural" audio_config = AudioOutputConfig(filename=close_file) synthesizer = SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config) # 等待异步合成任务完成并检查结果 result = synthesizer.speak_text_async(closer).get() if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted: print(f"音频文件已生成:{close_file}") elif result.reason == speechsdk.ResultReason.Canceled: cancellation_details = result.cancellation_details print(f"合成任务被取消:{cancellation_details.reason}") if cancellation_details.reason == speechsdk.CancellationReason.Error: print(f"错误详情:{cancellation_details.error_details}")
内容的提问来源于stack exchange,提问作者J. Doe
相关产品推荐
相关产品推荐

