How to call Azure speech to text service in a streaming way


The following code shows how to call the microsoft Azure text to speech service in an continuous or streaming way.
The audio input is from default microphone.

import azure.cognitiveservices.speech as speechsdk

def from_mic_continuous():
speech_config = speechsdk.SpeechConfig(subscription="subscription_key", region="azure service region")
audio_config = speechsdk.audio.AudioConfig(use_default_microphone=True)
speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)

def recognized_handler(evt):
# This handler is for final results
if evt.result.reason == speechsdk.ResultReason.RecognizedSpeech:
print(f"Final result: {evt.result.text}")

def recognizing_handler(evt):
# This handler is for partial results
#print(evt.result)
if evt.result.reason == speechsdk.ResultReason.RecognizingSpeech:
print(f"Partial result: {evt.result.text}")

#speech_recognizer.recognizing.connect(recognizing_handler)
speech_recognizer.recognized.connect(recognized_handler)

# Start continuous speech recognition
speech_recognizer.start_continuous_recognition()
try:
while True:
# Keep the main thread alive while the background thread processes the speech recognition
pass
except KeyboardInterrupt:
# Stop recognition when Ctrl+C is pressed
speech_recognizer.stop_continuous_recognition()

from_mic_continuous()

Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC