Generating Text-to-Speech Audio Files Using Google Text-to-Speech API in Node.js

Generating Text-to-Speech Audio Files Using Google Text-to-Speech API in Node.js

In this text, we’ll discover methods to convert textual content into speech and reserve it as an audio file utilizing the Google Text-to-Speech (TTS) API in a Node.js setting. We’ll leverage the google-tts-api bundle together with Axios for making HTTP requests and fs for file system operations.

Before we start, be sure you have Node.js put in in your machine. You’ll additionally must arrange a brand new Node.js venture and set up the required packages:

npm init -y
npm set up google-tts-api axios

Let’s dive proper in

Diving

Now let’s break down the code you will add to your file

const fs = require('fs');
const tts = require('google-tts-api');
const axios = require('axios');

// Function to transform textual content to speech and save as an audio file
async perform textToSpeech(textual content, language, outputFile) {
  strive {
    const url = await tts.getAudioUrl(textual content,  'en',
      gradual: false,
      host: 'https://translate.google.com',
    );

    const response = await axios.get(url, { responseType: 'arraybuffer' });

    fs.writeFileSync(outputFile, Buffer.from(response.knowledge));
    console.log(`Audio file saved to: ${outputFile}`);
  } catch (error) {
    console.error('Error changing textual content to speech:', error);
  }
}

// Example utilization
const textToConvert = 'Hello, it is a check.'

const outputFileName = 'output.mp3';
const languageCode = 'en'; // Change this to the specified language code

textToSpeech(textToConvert, languageCode, outputFileName);
  • We import the mandatory modules: fs for file system operations, google-tts-api for accessing the Google TTS API, and axios for making HTTP requests.
  • The textToSpeech perform takes three parameters: the textual content to transform, the language code (defaulting to English if not supplied), and the output file title.
  • Inside the perform, we generate the audio URL utilizing tts.getAudioUrl, specifying language and velocity parameters.
  • We then use axios to fetch the audio knowledge from the generated URL and write it to the output file utilizing fs.writeFileSync.
  • Any errors that happen in the course of the course of are caught and logged.
  • This code snippet converts the textual content "Hello, it is a check." into speech and saves it as an MP3 file named "output.mp3" within the specified language.

Now run your code and your output.mp3 file ought to seem
Do not overlook to love and comply with

Bow

HI-FI News

through DEV Community https://dev.to

April 5, 2024 at 05:54PM