File size: 1,612 Bytes
5ff2cba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import azure.cognitiveservices.speech as speechsdk
from consts.locale import locales
import os
from dotenv import load_dotenv
load_dotenv()

def text_to_speech(text, lang, path):

    try: 
        speech_config = speechsdk.SpeechConfig(subscription=os.environ["SPEECH_ACCESS_TOKEN"], region=os.environ["SPEECH_REGION"])
        speech_config.speech_synthesis_language = locales[lang]["locale"]  # Set the language
        speech_config.speech_synthesis_voice_name = locales[lang]["short_name"]  # Set the voice
        audio_config = speechsdk.audio.AudioOutputConfig(filename=path)  # Specify the output file
        speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)
        result = speech_synthesizer.speak_text_async(text).get()
        
        # Check the result
        if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
            print("Speech synthesized for text [{}]".format(text))
            return True
        elif result.reason == speechsdk.ResultReason.Canceled:
            cancellation_details = result.cancellation_details
            print("Speech synthesis canceled: {}".format(cancellation_details.reason))
            if cancellation_details.reason == speechsdk.CancellationReason.Error:
                if cancellation_details.error_details:
                    print("Error details: {}".format(cancellation_details.error_details))
                print("Did you set the speech resource key and region correctly?")
            return False    

    except Exception as e:
        print(e)
        return False