Google text-to-speech nodejs

I am trying to code a nodejs application that uses google tts api what my problem is, it returns an url to an audio. I need to be able to hear the text automatically without going to link and playing the audio.

Upvotes: 2

Views: 3205

Answers (3)

toddmo
toddmo

Reputation: 22396

Play directly to speakers in nodejs

Install

  1. [Terminal] install play: sudo apt install sox
  2. [Terminal] install encoder: sudo apt install libsox-fmt-mp3
  3. [Terminal] install node-gtts: npm install node-gtts
  4. [IDE][speech.js] See code listing
const gtts = require('node-gtts')('en');
const {exec} = require("child_process");

function speak(text) {
    var mp3FileName = `/home/toddmo/${text}.mp3`
    gtts.save(mp3FileName, text)
    exec(`play '${mp3FileName}'`)
}

Notes

  • it would be better all in memory but the mp3 encoder lame is currently not installing on the current version of nodejs

If they get that fixed, then this code will work

var lame = require('lame');
const Speaker = require('speaker');

// Create the Speaker instance
const speaker = new Speaker({
  channels: 2,          // 2 channels
  bitDepth: 16,         // 16-bit samples
  sampleRate:44100,     // 44,100 Hz sample rate
  device: 'hw:2,0'
});

// create the Encoder instance
var encoder = new lame.Encoder({
  // input
  channels: 2,        // 2 channels (left and right)
  bitDepth: 16,       // 16-bit samples
  sampleRate: 44100,  // 44,100 Hz sample rate

  // output
  bitRate: 128,
  outSampleRate: 22050,
  mode: lame.STEREO // STEREO (default), JOINTSTEREO, DUALCHANNEL or MONO
});

// raw PCM data from stdin gets piped into the encoder
// the generated MP3 file gets piped to speaker                
gtts.stream(text).pipe(encoder).pipe(speaker);

Upvotes: 0

Onur Durmuş
Onur Durmuş

Reputation: 142

first, install mpv player then try this ==>

const googleTTS = require("google-tts-api");
let mpv = require('node-mpv');
let mpvPlayer = new mpv();
googleTTS("Hello world", "en",1).then(url => mpvPlayer.load(url));

Upvotes: 1

helb
helb

Reputation: 3234

Just take the url and "play it" – it's a link to audio file. Example using play-sound:

const googleTTS = require("google-tts-api");
const player = require("play-sound")();

googleTTS("Hello World", "en", 1).then(url => player.play(url));

The play-sound package works by executing an external player – see #options for a list. You can even specify another one with the player option. The player needs to support playing from https urls, obviously. I tried it with mpv and it works perfectly.

If you can't or don't want to use the external player, you'll need to fetch the audio, get the data buffer from response and play it somehow. So something along this way:

googleTTS("Hello World", "en", 1).then(url => {
  fetch(url)
    .then(response => response.buffer())
    .then(buffer => playWithSomething(buffer));
});

Upvotes: 1

Related Questions