How To Convert Text To Speech In node.js

    Apr 05, 2019       by Pankaj Kumar
text-to-voice-image.jpg

The speech synthesis is used to convert given text to speech. We can implement this feature in nodejs application with npm package available called 'say'.

 

Notes for Windows

The voice parameter and speed in the function say not available means it will use the default system voice, ignoring the voice and speed parameter.

 

Get Started

create a folder and type below command to create package.json file

npm init --yes

Once above code run successfully then install required packages.

npm install body-parser express say --save

 

After that, We will start the app and create the method to take text as input and convert it to speech. Now create a file server.js and put below code in it.

 

 
const express = require('express');
const app = express();
 
// require say moudle
const say = require('say');
 
// require body parser to hahlde the user inputs
const bodyParser = require('body-parser');
 
// useing body parser middlewares to handle the user intput streams.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
 
// API to change the text to voice over link http://localhost:3000/speak
app.post('/speak', (req, res)=> {
let text = req.body.text;
// below 1.0 is the speed which can be increased
say.speak(text, 'Alex', 1.0, (err)=> {
if (err) {
return res.json({ message: err, error: true });
}
return res.json({ message: 'Text spoken.', error: false });
});
});
 
app.listen(3000,()=>{
console.log('app is running over port:'+3000);
});
 

 

Now run  the application over terminal by entering node server.js

And text it over postman like below:

text to voice

 

You can use any tool you want to test this api.

 

NOTE:

While checking the API, if you are getting error like below over terminal:

Error: spawn festival ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:201:19)
    at onErrorNT (internal/child_process.js:379:16)
    at process._tickCallback (internal/process/next_tick.js:114:19)
 

 

Then install a dependency needed here with below command:

sudo apt-get install festival festvox-kallpc16k

 

That’s all for now. Thank you for reading and I hope this article will be very helpful to understand the text to speech in Node.js.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

 


WHAT'S NEW

Find other similar Articles here: