const fs = require("fs");
const sdk = require("microsoft-cognitiveservices-speech-sdk");
// This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
const speechConfig = sdk.SpeechConfig.fromSubscription(process.env.SPEECH_KEY, process.env.SPEECH_REGION);
speechConfig.speechRecognitionLanguage = "en-US";
async function fromFile() {
let audioConfig = sdk.AudioConfig.fromWavFileInput(fs.readFileSync("YourAudioFile.wav"));
let speechRecognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig);
let outputText = "";
speechRecognizer.recognizeOnceAsync(result => {
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 = `CANCELED: ErrorDetails=${cancellation.errorDetails}`;
outputText = "CANCELED: Did you set the speech resource key and region values?";
}
break;
}
speechRecognizer.close();
});
return outputText;
}
let responseMsg = await fromFile();
console.log(responseMsg);
I'm trying to store the result from an async speechrecognizer method's callback. Inspite of adding async await keys, I'm unable to do that. The last console.log statements executes before the speechrecognizer method is completed.
I'm new to JS and I'm still in the learning phase for callbacks, promises,etc. Thank you for the help.
One solution is to use the async/await version instead of callback
async function fromFile() {
let audioConfig = sdk.AudioConfig.fromWavFileInput(fs.readFileSync("YourAudioFile.wav"));
let speechRecognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig);
let outputText = "";
const result = await recognize(speechRecognizer);
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 = `CANCELED: ErrorDetails=${cancellation.errorDetails}`;
outputText = "CANCELED: Did you set the speech resource key and region values?";
}
break;
}
speechRecognizer.close();
return outputText;
}
async function recognize(speechRecognizer) {
return new Promise(function(resolve, reject) {
speechRecognizer.recognizeOnceAsync(result => {
resolve(result);
}, err => {
reject(err);
});
})
}