Python使用azure语音合成接口
## 安装 ``` pip install azure-cognitiveservices-speech ``` ## 使用 ### 直接播放音频 ```python from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioDataStream from config import settings # 配置 speech_key = settings.speech_key service_region = settings.service_region reader = settings.reader # 配置 speech_config = SpeechConfig(subscription=speech_key, region=service_region) speech_config.speech_synthesis_voice_name = reader # 设置为True表示直接播放 audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=True) speech_synthesizer = SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config) # 播放 def getVoice(text): speech_synthesizer.speak_text_async(text).get() ``` ### 保存音频到指定文件 第一种方法是直接设置保存路径。 ```python from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioDataStream from config import settings # 配置 speech_key = settings.speech_key service_region = settings.service_region reader = settings.reader # 配置 speech_config = SpeechConfig(subscription=speech_key, region=service_region) speech_config.speech_synthesis_voice_name = reader # 设置为False表示不播放,如果设为True则即保存又播放 audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=False, filename="./hello.wav") speech_synthesizer = SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config) # 保存 def getVoice(text): speech_synthesizer.speak_text_async(text).get() ``` 第二种方法是先保存到数据流中,再保存到指定文件中,要将`audio_config`的属性值设为`None`,这样扬声器就不会输出音频。如果不设置为`None`,则会默认输出音频。 ```python from azure.cognitiveservices.speech import SpeechConfig, SpeechSynthesizer, AudioDataStream from config import settings # 配置 speech_key = settings.speech_key service_region = settings.service_region reader = settings.reader # 配置 speech_config = SpeechConfig(subscription=speech_key, region=service_region) speech_config.speech_synthesis_voice_name = reader speech_synthesizer = SpeechSynthesizer(speech_config=speech_config, audio_config=None) # 保存 def getVoice(text, filename): res = speech_synthesizer.speak_text_async(text).get() stream = AudioDataStream(res) stream.save_to_wav_file(filename) ```
创建时间:2024-01-22
|
最后修改:2024-01-22
|
©允许规范转载
酷酷番茄
首页
文章
友链