-
Notifications
You must be signed in to change notification settings - Fork 0
/
cb_sample.py
49 lines (37 loc) · 1.94 KB
/
cb_sample.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
import azure.cognitiveservices.speech as speechsdk
speech_key, service_region = os.environ['SPEECH_KEY'], os.environ['SPEECH_REGION']
from_language, to_language = 'en-US', 'de'
def translate_speech_to_text():
translation_config = speechsdk.translation.SpeechTranslationConfig(
subscription=speech_key, region=service_region)
translation_config.speech_recognition_language = from_language
translation_config.add_target_language(to_language)
# See: https://aka.ms/speech/sdkregion#standard-and-neural-voices
translation_config.voice_name = "de-DE-Hedda"
translation_recognizer = speechsdk.translation.TranslationRecognizer(
translation_config=translation_config)
def synthesis_callback(evt):
size = len(evt.result.audio)
print(f'Audio synthesized: {size} byte(s) {"(COMPLETED)" if size == 0 else ""}')
if size > 0:
file = open('translation.wav', 'ab+')
file.write(evt.result.audio)
file.close()
translation_recognizer.synthesizing.connect(synthesis_callback)
print(f'Say something in "{from_language}" and we\'ll translate into "{to_language}".')
result = translation_recognizer.recognize_once()
print(result.reason)
print(result.translations)
print(get_result_text(reason=result.reason, result=result))
def get_result_text(reason, result):
reason_format = {
speechsdk.ResultReason.TranslatedSpeech:
f'Recognized "{from_language}": {result.text}\n' +
f'Translated into "{to_language}": {result.translations}',
speechsdk.ResultReason.RecognizedSpeech: f'Recognized: "{result.text}"',
speechsdk.ResultReason.NoMatch: f'No speech could be recognized: {result.no_match_details}',
speechsdk.ResultReason.Canceled: f'Speech Recognition canceled: {result.cancellation_details}'
}
return reason_format.get(reason, 'Unable to recognize speech')
translate_speech_to_text()