如何在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
相关产品推荐
相关产品推荐

