Latest Tech

Recent Posts: Label / Tag Ex:

Convert Text To Speech Using Python – Easy


How to Convert Text To Speech?

Today we are going to learn how to convert text to speech in Python. Python has countless modules to assist us as programmers. One of these modules that is going to be used today called gTTS.

What is gTTs?

gTTS is a shortcut for “Google To Text Speech”. It’s Google’s API used by python to convert text to speech and create mp3 audio files. So first we import gTTS.

from gtts import gTTS

Second, another important module we will include in our masterpiece which is OS module.

What is OS Module?

OS enables Python to use the operating system dependent functionality. It is used here so we can play the converted mp3 speech file.

import os

Third, we need to allow the user to have an input which is the text that will be converted to audio later.

mytext = input("Type your text to be converted, then PRESS ENTER  ")

Fourth, the language. You can choose any language, just change the parameter between the ' '. Example, you want it to be spanish, change it to 'es.

language = 'en'

Fifth, we need to pass the input text and language to the engine. The parameter slow = False, is to make the audio speed normal.

target = gTTS(text=mytext, lang=language, slow=False)

Finally, we save the converted the file to mp3 named Speech. OS.system, is to play the converted file.

target.save("speech.mp3")

os.system("speech.mp3")

This is the full code.

from gtts import gTTS


import os

mytext = input("Type your text to be converted, then PRESS ENTER  ")



language = 'en'

target = gTTS(text=mytext, lang=language, slow=False)


target.save("speech.mp3")

os.system("speech.mp3")

Simple is it? Remember to press ENTER after you type your text. The audio should pop up right after pressing ENTER.



 Happy Coding...