How to Convert Text to Speech in Python?

PythonServer Side ProgrammingProgramming

Converting Text to Speech basically refers to a program where you give input as a text and the output you receive is the input text in the form of a speech.

Python offers the text to speech conversion with the help of APIs. One such API which serves this purpose is the Google Text to Speech API , known as gTTS. The gTTS enables to conversion the provided text into speech and save the output as audio.

Step 1 − Install gTTS

To use the gTTS Text to speech conversion tool, we need to install it first. Installing the gTTS is pretty easy.

Open the terminal and type the following −

pip install gTTS

The above command will install gTTS.

Steps 2 − Write program for text to speech conversion

  • Import gTTS .

  • Specify the text you want to convert.

  • Call the gTTS(). This takes three parameters −

    • text: The input text which you want to convert into speech.

    • language: The laguage in which you want the speech to be converted. The gTTS supports many languages which include English, Hindi, French,German etc.

    • slow or fast: This specifies the audio speeds. Two audio speeds are available, fast or slow. The parameter slow takes boolean value which specifies the desired audio speed among the two available options.

  • The output will be returned to the variable on calling the gTTS(). The output can be saved as a mp3 file.

  • If you want to play the output audio, we can do that using os.system(). We need to import os for this purpose. Pass the name of the saved audio in the os.system() to play the audio.

Example

from gtts import gTTS
myText="I want to learn Python"
speech=gTTS(text=myText,lang="en",slow=False)
speech.save("tts.mp3")
raja
Published on 11-Mar-2021 09:33:17
Advertisements