TechAid24

Your Technical Consultant

How to Convert Text to Speech in Python – Easy Implementation with Examples

Posted on by Anonymous Guest 2 minutes read

In this tutorial, you will learn how to text to speech using Python. Python is an incredibly strong and flexible language used for multi-purpose programming. There are a lot of things possible using Python; one of them is text-to-speech conversion.

We are going to use a Python package called gTTS (Google Text-to-Speech) for this purpose. gTTS is a Python library and CLI tool to interface with Google Translate’s text-to-speech API. Which writes spoken mp3 data to a file, a file-like object (byte string) for further audio manipulation, or stdout.

Google Cloud Text-to-Speech converts text into human-like speech in more than 100 voices across 20+ languages and variants. The gTTS API supports several languages, including English, Hindi, Tamil, French, German, and many more. Let’s begin with installing the gTTS package first.

pip install gtts

After the installation is done, you can go ahead and run the following Scripts. Note that gTTS works perfectly in Python, but it needs an internet connection to work since it relies on Google to get the audio data, so your machine must have a working internet connection.

 

Python Program to convert a text into speech

import os 
from gtts import gTTS

Text = "I love Django central and Python programming Language"

print("please wait...processing")
TTS = gTTS(text=Text, lang='en-uk')

# Save to mp3 in current dir.
TTS.save("voice.mp3")

# Plays the mp3 using the default app on your system that is linked to mp3s.
os.system("start voice.mp3")

Save the file and run it. This should open your default music player app and play the audio. But what if you wanted to convert a large string or document into speech? For that, you might wanna save the content into a text file, then convert it into speech as follows.

 

Python program to convert a text file into speech

import os 
from gtts import gTTS

# You will need a text file named test.txt to play, put it in the current dir. 
FLIST = open("test.txt", "r").read().replace("\n", " ") 

print("please wait...processing")
TTS = gTTS(text=str(FLIST), lang='en-uk')

# Save to mp3 in current dir.
TTS.save("voice.mp3")

# Plays the mp3 using the default app on your system that is linked to mp3s. 
print(FLIST) 
os.system("start voice.mp3")

Save and run the file, and you should get the desired output.

Text To Speech Conversion Using Python

Tags:

Anonymous Guest

An anonymous author is a writer who conceals their true identity when publishing content, often for privacy, security, or confidentiality reasons. This approach is often used in technical articles to focus on the information being presented rather than the author's personal identity.

Leave a Reply

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