Convert text to speech in python

Here, In this tutorial you will be learning about how to convert text to speech in python.

Python provides many API’s to convert text to speech. One of the most famous API is gTTS API, it is a google text to speech API. It is very easy to use and user friendly. It also provides many built-in functions to convert the text to a mp3 file.

The gTTS API provides the facility to convert the text into different languages such as English, Hindi, Tamil and many more. It uses a offline library called pyttsx3.

Installation of gTTS API

To install the API use the following code

pip install gTTS

After installation use the following code to convert the text to speech

from gtts import gTTS
import os
text = "Hello, how are you today?"
language = 'en'
speech = gTTS(text=text, lang=language, slow=False)
speech.save("output.mp3")

The above code will convert the text to speech and saves it to the mp3 file and pays the audio file.

Offline API

To covert the text to speech offline you can use the library named pyttsx3. Python provides the pyttsx3 library, which looks for TTS engines pre-installed in our platform.

Example

import pyttsx3   
engine = pyttsx3.init()   
text = "Python is a great programming language"  
engine.say(text)  
engine.runAndWait()

In the above code, we have used the say() method and passed the text as an argument. , while the runAndWait() method runs the real event loop until all commands queued up. It also provides some additional properties that we can use based on our requirements.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top