To build a Text-to-Speech (TTS) app in Node.js and Express using the Google Text to Speech (GTTS) library, follow these steps:
Step 1: Set up a new Node.js project.
Create a new directory for your project, navigate to it in a terminal, and run the following commands:
npm init -y
npm i gtts express
Step 2: Create an Express server.
Create a new file named server.js
in the root directory of your project and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
const express = require('express'); const gtts = require('gtts'); const app = express(); app.get('/tts', (req, res) => { const { text } = req.query; if (!text) { return res.status(400).json({ error: 'Text parameter is missing' }); } const speech = gtts(text, 'en'); speech .stream() .pipe(res.contentType('audio/mp3')); }); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is running on port ${port}`); }); |
In the code above, we require the express
and gtts
modules. We create an Express server and define a single route for the TTS functionality.
The /tts
route expects a text
query parameter, which represents the text to be converted to speech. If the text
parameter is missing, the server will return a JSON error response with a status of 400.
When the text
parameter is present, we create a new instance of the gtts
object with the text and language code ('en'
for English). We then use the stream()
method to get a readable stream of the generated audio and pipe it to the response with the content type set to audio/mp3
.
Step 3: Start the server.
In the terminal, run the following command to start the server: