如何在 Python 中使用 Google 的 Text-to-Speech API

Ren*_*dus 4 python api text-to-speech

我的钥匙已准备好提出请求并从 Google 的文本中获取语音。
我尝试了这些命令以及更多命令。
这些文档没有提供我发现的 Python 入门的直接解决方案。我不知道我的 API 密钥与 JSON 和 URL 一起去哪里了

他们的文档中的一种解决方案是针对 CURL。. 但是涉及在必须将请求发送回他们以获取文件之后下载txt。有没有办法在 Python 中做到这一点而不涉及我必须返回的 txt?我只希望我的字符串列表作为音频文件返回。

我的代码

(我把我的实际密钥放在上面的块中。我不打算在这里分享它。)

小智 7

为 JSON 文件配置 Python 应用程序并安装客户端库

  1. 创建服务帐户
  2. 使用此处的服务帐户创建服务帐户密钥
  3. JSON 文件下载并安全保存
  4. 在您的 Python 应用程序中包含 Google 应用程序凭据
  5. 安装库: pip install --upgrade google-cloud-texttospeech

使用 Google 的 Python 示例找到:https : //cloud.google.com/text-to-speech/docs/reference/libraries 注意:在 Google 的示例中,它没有正确包含 name 参数。和 https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/texttospeech/cloud-client/quickstart.py

以下是使用谷歌应用程序凭据和女性的 wavenet 语音从示例中修改的内容。

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/home/yourproject-12345.json"

from google.cloud import texttospeech

# Instantiates a client
client = texttospeech.TextToSpeechClient()

# Set the text input to be synthesized
synthesis_input = texttospeech.types.SynthesisInput(text="Do no evil!")

# Build the voice request, select the language code ("en-US") 
# ****** the NAME
# and the ssml voice gender ("neutral")
voice = texttospeech.types.VoiceSelectionParams(
    language_code='en-US',
    name='en-US-Wavenet-C',
    ssml_gender=texttospeech.enums.SsmlVoiceGender.FEMALE)

# Select the type of audio file you want returned
audio_config = texttospeech.types.AudioConfig(
    audio_encoding=texttospeech.enums.AudioEncoding.MP3)

# Perform the text-to-speech request on the text input with the selected
# voice parameters and audio file type
response = client.synthesize_speech(synthesis_input, voice, audio_config)

# The response's audio_content is binary.
with open('output.mp3', 'wb') as out:
    # Write the response to the output file.
    out.write(response.audio_content)
    print('Audio content written to file "output.mp3"')
Run Code Online (Sandbox Code Playgroud)

语音、姓名、语言代码、SSML 性别等

语音列表:https : //cloud.google.com/text-to-speech/docs/voices

在上面的代码示例中,我将 Google 示例代码中的语音更改为包含 name 参数并使用 Wavenet 语音(大大改进但更贵 16 美元/百万个字符)和 SSML Gender 为 FEMALE。

voice = texttospeech.types.VoiceSelectionParams(
        language_code='en-US',
        name='en-US-Wavenet-C',
        ssml_gender=texttospeech.enums.SsmlVoiceGender.FEMALE)
Run Code Online (Sandbox Code Playgroud)