Convert Text to Speech in Python

Imagine having the power to transform text into spoken words with just a few lines of Python code! Well, you can, thanks to various text-to-speech APIs available in Python. One of the most user-friendly options is the Google Text to Speech API, often referred to as gTTS. It’s like a magic tool that effortlessly turns your written words into audio, and you can even save it as an mp3 file.

What’s even more amazing is that gTTS supports a wide range of languages, including English, Hindi, Tamil, French, German, and many more. You get to choose the pace of the speech too, whether you want it to be fast or slow. However, please note that, as of the latest update, you can’t change the voice of the generated audio.

To install the gTTS API, open command line terminal and write:

pip install gTTS

You can use this on any platform. Now, we’re fully prepared to craft a sample program that transforms text into speech.

# Import text to speech conversion module
from gtts import gTTS
  
# Import os module so we can play the converted audio
import os
  
# Enter text that you want to convert from text to speech
mytext = 'Happy Friday!'
  
# Language
language = 'en'
  
# Pass text and language to gTTs, 
# Engine will convert audio to have high speed since slow=False option is set
output= gTTS(text=mytext, lang=language, slow=False)
  
# Saving the converted audio in a mp3 file named
output.save("speech_sample1.mp3")
  

Play the converted mp3 file. You will hear following:

'Happy Friday!'