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

