Node.js Google Cloud Text to Speech API Converter and Downloads it as MP3 File Using Javascript on Command Line Full Project For Beginners

 

 

 

 

 

 

npm init -y

 

 

npm i dotenv

 

 

npm i @google-cloud/text-to-speech

 

 

 

index.js

 

 

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

// 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 = 'JOHN WILLIAMSON LATHAM IS THE CAPTAIN OF NEW ZEALAND.';

  // 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()

 

 

Now before running the node app you need to set the serviceaccount.json file as the environment variable. Just create the .env file and set the path of file

See also  JavaScript Program to Merge Property of Two Objects Using Spread Operator Full Project For Beginners

 

 

.env

 

 

GOOGLE_APPLICATION_CREDENTIALS="serviceaccount.json"

 

 

 

node index.js

 

 

 

Leave a Reply