以下是一个使用Google Text-to-Speech API播放从API检索到的音频数据的示例代码:
from google.cloud import texttospeech
from playsound import playsound
import os
# 设置Google Cloud凭证路径
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/to/credentials.json"
# 创建一个Text-to-Speech客户端
client = texttospeech.TextToSpeechClient()
# 设置文本输入
input_text = texttospeech.SynthesisInput(text="Hello, how are you?")
# 设置音频参数
voice = texttospeech.VoiceSelectionParams(
language_code="en-US", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL
)
audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)
# 调用API合成音频
response = client.synthesize_speech(
request={"input": input_text, "voice": voice, "audio_config": audio_config}
)
# 将音频数据保存到临时文件
output_file = "output.mp3"
with open(output_file, "wb") as out:
out.write(response.audio_content)
# 播放音频文件
playsound(output_file)
# 删除临时文件
os.remove(output_file)
在上述代码中,需要注意以下几点:
GOOGLE_APPLICATION_CREDENTIALS
环境变量应设置为具有Google Cloud凭证的JSON文件的路径。google-cloud-texttospeech
和playsound
库来使用Google Cloud Text-to-Speech API和播放音频文件的功能。synthesize_speech
方法用于调用API合成音频,其中input_text
变量设置为要合成的文本,voice
变量设置为声音参数,audio_config
变量设置为音频参数。open
函数将音频数据写入临时文件output_file
。playsound
库播放音频文件。os.remove
函数删除临时文件。请确保替换代码中的path/to/credentials.json
为您的Google Cloud凭证的实际路径。