NodeJS中如何等待Microsoft SpeechRecognizer异步函数并保存回调结果
问题解决:Microsoft Speech Recognizer 异步回调结果无法正确等待
问题场景
尝试在Microsoft SpeechRecognizer异步方法的回调中存储语音识别结果,即使添加了async/await关键字,最后一行console.log仍会在语音识别完成前执行,无法获取正确结果。
问题原因
recognizeOnceAsync是基于回调函数的异步API,并非Promise。你的fromFile函数虽然标记了async,但内部没有等待异步回调完成就直接返回了初始值outputText,导致await无法捕获异步操作的结果。
修改后的代码
const fs = require("fs"); const sdk = require("microsoft-cognitiveservices-speech-sdk"); // 需要设置环境变量 SPEECH_KEY 和 SPEECH_REGION const speechConfig = sdk.SpeechConfig.fromSubscription(process.env.SPEECH_KEY, process.env.SPEECH_REGION); speechConfig.speechRecognitionLanguage = "en-US"; function fromFile() { // 将基于回调的API包装成Promise return new Promise((resolve) => { let audioConfig = sdk.AudioConfig.fromWavFileInput(fs.readFileSync("YourAudioFile.wav")); let speechRecognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig); speechRecognizer.recognizeOnceAsync(result => { let outputText = ""; switch (result.reason) { case sdk.ResultReason.RecognizedSpeech: outputText = `RECOGNIZED: Text=${result.text}`; break; case sdk.ResultReason.NoMatch: outputText = "NOMATCH: Speech could not be recognized."; break; case sdk.ResultReason.Canceled: const cancellation = sdk.CancellationDetails.fromResult(result); outputText = `CANCELED: Reason=${cancellation.reason}`; if (cancellation.reason == sdk.CancellationReason.Error) { outputText = `CANCELED: ErrorCode=${cancellation.errorCode}`; outputText += `\nCANCELED: ErrorDetails=${cancellation.errorDetails}`; outputText += "\nCANCELED: Did you set the speech resource key and region values?"; } break; } speechRecognizer.close(); resolve(outputText); // 回调完成后返回结果 }); }); } // 用自执行async函数包裹,确保await正常运行 (async () => { let responseMsg = await fromFile(); console.log(responseMsg); })();
关键修改点
- 将
fromFile改为返回Promise对象,把异步回调逻辑包裹在Promise内部,让await能够等待异步操作完成 - 在
recognizeOnceAsync的回调中,通过resolve(outputText)将识别结果传递出去 - 修复了原代码中错误的
cancellation.ErrorCode(应为小写errorCode),并调整错误信息的拼接方式,避免内容被覆盖 - 用自执行async函数包裹调用逻辑,兼容不支持顶层
await的运行环境
内容的提问来源于stack exchange,提问作者Nicholas Drogo
相关产品推荐
相关产品推荐

