Set the component state and check if there is valid token.
constructor(props) {super(props);this.state = { displayText:'INITIALIZED: ready to test speech...' } } async componentDidMount() {// check for valid speech key/regionconsttokenRes=awaitgetTokenOrRefresh();if (tokenRes.authToken ===null) {this.setState({ displayText:'FATAL_ERROR: '+tokenRes.error }); } }
Calling Speech-to-Text with the microphone stream data
Function to get stream from microphone and make a call for transcription. We call this function when the microphone click happens.
async sttFromMic() {consttokenObj=awaitgetTokenOrRefresh();constspeechConfig=speechsdk.SpeechConfig.fromAuthorizationToken(tokenObj.authToken,tokenObj.region);speechConfig.speechRecognitionLanguage ='en-US';constaudioConfig=speechsdk.AudioConfig.fromDefaultMicrophoneInput();constrecognizer=newspeechsdk.SpeechRecognizer(speechConfig, audioConfig);this.setState({ displayText:'speak into your microphone...' });recognizer.recognizeOnceAsync(result => {let displayText;if (result.reason ===ResultReason.RecognizedSpeech) { displayText =`RECOGNIZED: Text=${result.text}` } else { displayText = 'ERROR: Speech was cancelled or could not be recognized. Ensure your microphone is working properly.';
}this.setState({ displayText: displayText }); }); }