Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Text-to-speech fetch request - Error 400: "Input type has to be text or SSML"

Hi! I'm making a React Native app and want to fetch TTS data from the following endpoint: https://texttospeech.googleapis.com/v1beta1/text:synthesize

However, when I run my code, I get the following error: {"error": {"code": 400, "message": "Input type has to be text or SSML. Maybe the input is empty?", "status": "INVALID_ARGUMENT"}}

My code is below:

 

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: {
        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);
  }
};

 

As you can see, the input type is text. I've also tried changing the type to SSML, but with no luck (I get the same error). What can I do? Any help would be much appreciated!

 

0 1 1,679
1 REPLY 1

Good day @tourai,

Welcome to Google Cloud Community!

If you want to fetch a TTS data, you need to set up a Node.js Development Environment since fs package won't work on react native. Here is a sample script from the documentation https://cloud.google.com/text-to-speech/docs/libraries#use

// Imports the Google Cloud client library
const textToSpeech = require('@google-cloud/text-to-speech');

// Import other required libraries
const fs = require('fs');
const util = require('util');
// Creates a client
const client = new textToSpeech.TextToSpeechClient();
async function quickStart() {
  // The text to synthesize
  const text = 'hello, world!';

  // Construct the request
  const request = {
    input: {text: text},
    // Select the language and SSML voice gender (optional)
    voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
    // select the type of audio encoding
    audioConfig: {audioEncoding: 'MP3'},
  };

  // Performs the text-to-speech request
  const [response] = await client.synthesizeSpeech(request);
  // Write the binary audio content to a local file
  const writeFile = util.promisify(fs.writeFile);
  await writeFile('output.mp3', response.audioContent, 'binary');
  console.log('Audio content written to file: output.mp3');
}
quickStart();

 Hope this helps!