Reputation: 89
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
Reputation: 22396
sudo apt install sox
sudo apt install libsox-fmt-mp3
node-gtts
: npm install node-gtts
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}'`)
}
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
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
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