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

Google Cloud Text-to-Speech API无法识别API密钥求助

解决Google Cloud Text-to-Speech API 403权限错误

核心问题:请求未携带API密钥

你当前的代码仅发送了请求体,但未在请求中包含API密钥。Google Cloud的REST API调用必须通过以下两种方式之一携带密钥:

方法1:在URL中追加API密钥

修改请求URL,直接拼接API密钥参数:

import requests

API_KEY = "你的实际API密钥"  # 替换为你的API密钥
r = requests.post(f'https://texttospeech.googleapis.com/v1beta1/text:synthesize?key={API_KEY}', json={
  "audioConfig": {
    "audioEncoding": "LINEAR16",
    "pitch": 0,
    "speakingRate": 1
  },
  "input": {
    "text": "Google Cloud Text-to-Speech enables developers to synthesize natural-sounding speech with 100+ voices, available in multiple languages and variants. It applies DeepMind’s groundbreaking research in WaveNet and Google’s powerful neural networks to deliver the highest fidelity possible. As an easy-to-use API, you can create lifelike interactions with your users, across many applications and devices."
  },
  "voice": {
    "languageCode": "en-US",
    "name": "en-US-Wavenet-D"
  }
})

print(r.json())

方法2:从环境变量读取密钥并放入请求头(推荐)

如果已将API密钥设置为环境变量(比如GOOGLE_API_KEY),可通过读取环境变量并在请求头中携带:

import requests
import os

API_KEY = os.getenv("GOOGLE_API_KEY")  # 读取环境变量中的密钥
headers = {"X-Goog-Api-Key": API_KEY}

r = requests.post('https://texttospeech.googleapis.com/v1beta1/text:synthesize', 
                  json={
                    "audioConfig": {
                      "audioEncoding": "LINEAR16",
                      "pitch": 0,
                      "speakingRate": 1
                    },
                    "input": {
                      "text": "Google Cloud Text-to-Speech enables developers to synthesize natural-sounding speech with 100+ voices, available in multiple languages and variants. It applies DeepMind’s groundbreaking research in WaveNet and Google’s powerful neural networks to deliver the highest fidelity possible. As an easy-to-use API, you can create lifelike interactions with your users, across many applications and devices."
                    },
                    "voice": {
                      "languageCode": "en-US",
                      "name": "en-US-Wavenet-D"
                    }
                  },
                  headers=headers)

print(r.json())

额外排查点

  • 验证环境变量是否生效:先打印os.getenv("GOOGLE_API_KEY"),确认能正确输出密钥
  • 检查API密钥权限:在Google Cloud控制台确认该密钥未被限制,且Text-to-Speech API已启用
  • 确认账号配额:如果账号配额耗尽,也可能触发类似错误,可在控制台查看配额使用情况

内容的提问来源于stack exchange,提问作者Kyle Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:45:49