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

React Native调用Google TTS API遇400错误:输入类型需为text或SSML

解决Google TTS API调用的400错误

问题根源

你的代码里没有将请求体序列化为JSON字符串。fetch API的body参数如果直接传入JavaScript对象,不会自动转换为JSON格式,导致服务器无法正确解析输入内容,因此返回"Input type has to be text or SSML"的错误。

修复后的代码

将body部分用JSON.stringify()包裹,确保请求体是符合要求的JSON格式:

const API_KEY = "...";
const API_URL = `https://texttospeech.googleapis.com/v1beta1/text:synthesize?key=${API_KEY}`;

const speak = async (text) => {
  try {
    console.log("sup");
    const response = await fetch(`${API_URL}`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        input: {
          text: "Hello world",
        },
        voice: {
          languageCode: "en-US",
          name: "en-US-Wavenet-A",
          ssmlGender: "MALE",
        },
        audioConfig: {
          audioEncoding: "MP3",
        },
      }),
    });
    const result = await response.json();
    console.log(result);
  } catch (error) {
    console.error("Error:", error);
  }
};

额外验证点

  • 确认你的API密钥已启用Cloud Text-to-Speech API权限
  • 如果后续要动态传入text参数,需确保参数不为空值

内容的提问来源于stack exchange,提问作者Nicholas Jankovic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:37:08