python - 如何在 Python 中使用 Google 的文本转语音 API

标签 python api text-to-speech

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

One solution in their docs here is for CURL. 。但涉及到在请求后下载一个 txt 文件,该请求必须发送回给他们才能获取文件。有没有一种方法可以在Python中执行此操作,而不涉及我必须返回的txt? 我只想将字符串列表作为音频文件返回。

My Code

(我将实际的 key 放在上面的 block 中。我只是不打算在这里分享它。)

最佳答案

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

  1. 创建服务帐户
  2. 使用服务帐户创建服务帐户 key here
  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 的示例中,它没有正确包含名称参数。 和 https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/texttospeech/cloud-client/quickstart.py

以下是使用 Google 应用凭据和女性 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"')
<小时/>

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

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

在上面的代码示例中,我更改了 Google 示例代码中的语音,以包含名称参数并使用 Wavenet 语音(经过很大改进,但更昂贵,每百万字符 16 美元),并将 SSML 性别更改为 FEMALE。

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

关于python - 如何在 Python 中使用 Google 的文本转语音 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54699541/

相关文章:

python - 将参数传递给 apscheduler 处理函数

api - Strava API - 如何获取路线图像

api - 是否有适用于列入黑名单的域的良好 API?

java - 是否有实用程序或 API 可以将 SMS 速记缩写转换为正确的句子?

Python-Matplotlib : normalize axis when plotting a Probability Density Function

python - 表达式中的变量赋值

python - 尝试从 nytimes.com 下载 .pdf .png 和 .jpg

api - 未找到类 'Google_Service'

c# - 从 C : fputc and fwrite in C#? 转换

android - 在 android 通话期间将铃声音量静音