You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中为Google TextToSpeechClient传入API Key

Google TextToSpeechClient 直接传入API Key的方法

Google TextToSpeechClient支持直接传入API Key进行认证,但不能直接将Key字符串传给客户端构造函数,需要通过构建认证凭据对象的方式实现,具体步骤如下:

  • 导入Credentials类,用于基于API Key生成认证凭据
  • 传入你的API Key和Google OAuth2令牌端点,创建凭据对象
  • 将凭据对象传给TextToSpeechClient的credentials参数

修改后的示例代码:

def list_voices():
    from google.cloud import texttospeech
    from google.oauth2.credentials import Credentials

    # 替换为你的API Key
    api_key = "YOUR_API_KEY_HERE"
    # 创建凭据对象
    credentials = Credentials(
        None,
        api_key=api_key,
        token_uri="https://oauth2.googleapis.com/token"
    )
    # 传入凭据初始化客户端
    client = texttospeech.TextToSpeechClient(credentials=credentials)
    
    voices = client.list_voices()
    for voice in voices.voices:
        print(f"Name: {voice.name}")
        for language_code in voice.language_codes:
            print(f"Supported language: {language_code}")
        ssml_gender = texttospeech.SsmlVoiceGender(voice.ssml_gender)
        print(f"SSML Voice Gender: {ssml_gender.name}")
        print(f"Natural Sample Rate Hertz: {voice.natural_sample_rate_hertz}\n")

注意:官方更推荐使用服务账号JSON密钥文件进行认证(包含完整的身份信息),但如果你的场景只能使用API Key,上述方法完全可行。

内容的提问来源于stack exchange,提问作者Kiran S youtube channel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 05:07:04