import os from azure.cognitiveservices.speech import SpeechConfig, AudioOutputConfig, SpeakerRecognitionResult from azure.cognitiveservices.speech.audio import AudioDataStream, AudioOutputStream, AudioOutputConfig from azure.cognitiveservices.speech.texttospeech import TextToSpeechClient, SynthesisOutputFormat
# Set your subscription key and region subscription_key = "<your-subscription-key>" region = "<your-region>"
# Set the text to be synthesized text = "通过自然语音为应用注入生命力"
# Initialize the text-to-speech client tts_client = TextToSpeechClient(subscription_key, region)
# Set the voice and synthesis output format voice_name = "zh-CN-XiaoxiaoNeural" synthesis_output_format = SynthesisOutputFormat.mp3
# Set the audio output configuration audio_config = AudioOutputConfig() audio_config.output_format = SynthesisOutputFormat.mp3
# Synthesize the text and write the output to a file result = tts_client.synthesize_speech(text, voice_name, synthesis_output_format, audio_config) withopen("output.mp3", "wb") asfile: file.write(result)
在上面的代码中,我们使用 Azure 语音 API 将文本转换为语音,然后将结果保存到文件中。请注意,您需要提供 Azure 订阅密钥和区域信息才能使用语音 API。 请注意,上面的代码仅是一个简单的例子,实际应用中可能需要进行更多的处理,如处理错误和异常、检查语音结果等。更多信息,可以参考 Azure 语音 API 的文档。