The Wayback Machine - https://web.archive.org/web/20240927050312/https://www.geeksforgeeks.org/convert-text-speech-python/
Open In App

Convert Text to Speech in Python

Last Updated : 21 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

There are several APIs available to convert text to speech in Python. One of such APIs is the Google Text to Speech API commonly known as the gTTS API. gTTS is a very easy to use tool which converts the text entered, into audio which can be saved as a mp3 file. The gTTS API supports several languages including English, Hindi, Tamil, French, German and many more. The speech can be delivered in any one of the two available audio speeds, fast or slow. However, as of the latest update, it is not possible to change the voice of the generated audio.

Installation

To install the gTTS API, open terminal and write

pip install gTTS

Example 1: Using Python OS

Python
# Import the required module for text 
# to speech conversion
from gtts import gTTS

# This module is imported so that we can 
# play the converted audio
import os

# The text that you want to convert to audio
mytext = 'Welcome to geeksforgeeks Joe!'

# Language in which you want to convert
language = 'en'

# Passing the text and language to the engine, 
# here we have marked slow=False. Which tells 
# the module that the converted audio should 
# have a high speed
myobj = gTTS(text=mytext, lang=language, slow=False)

# Saving the converted audio in a mp3 file named
# welcome 
myobj.save("welcome.mp3")

# Playing the converted file
os.system("start welcome.mp3")

Output

The output of the above program should be a 
voice saying, 'Welcome to geeksforgeeks Joe!'

Example 2: Uisng Python Pygame

This works for any platform. Now we are all set to write a sample program that converts text to speech.

Python
# Import the required module for text 
# to speech conversion
from gtts import gTTS

# Import pygame for playing the converted audio
import pygame

# The text that you want to convert to audio
mytext = 'Welcome to geeksforgeeks!'

# Language in which you want to convert
language = 'en'

# Passing the text and language to the engine, 
# here we have marked slow=False. Which tells 
# the module that the converted audio should 
# have a high speed
myobj = gTTS(text=mytext, lang=language, slow=False)

# Saving the converted audio in a mp3 file named
# welcome 
myobj.save("welcome.mp3")

# Initialize the mixer module
pygame.mixer.init()

# Load the mp3 file
pygame.mixer.music.load("welcome.mp3")

# Play the loaded mp3 file
pygame.mixer.music.play()

Output

The output of the above program should be a 
voice saying, 'Welcome to geeksforgeeks!'

Convert Text to Speech in Python – FAQs

How Do I Convert a Text File to Speech in Python?

To convert a text file to speech in Python, you can use the pyttsx3 library, which is a text-to-speech conversion library in Python. It works offline and is compatible with both Python 2 and Python 3.

Example:

import pyttsx3

# Initialize the converter
engine = pyttsx3.init()

# Open and read the text file
with open('file.txt', 'r') as file:
text = file.read()

# Convert text to speech
engine.say(text)
engine.runAndWait()

How to Convert Speech to Text and Text to Speech in Python?

For converting speech to text and text to speech, you can use speech_recognition for speech to text and pyttsx3 for text to speech.

Text to Speech Example using pyttsx3:

import pyttsx3
engine = pyttsx3.init()
engine.say("Hello, how are you?")
engine.runAndWait()

Speech to Text Example using speech_recognition:

import speech_recognition as sr

recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = recognizer.listen(source)

try:
text = recognizer.recognize_google(audio)
print("You said:", text)
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print(f"Could not request results; {e}")

How to Convert a Text File to Dictionary in Python?

To convert a text file to a dictionary, the file should contain data that can be interpreted as key-value pairs. Here’s a simple example assuming each line in the file contains a key and value separated by a colon.

Example:

dictionary = {}
with open("data.txt", "r") as file:
for line in file:
key, value = line.strip().split(':')
dictionary[key] = value

print(dictionary)

Does Python Have Text to Speech?

Yes, Python supports text-to-speech capabilities through several libraries, with pyttsx3 being one of the most popular because it works offline and supports multiple TTS engines.

How to Convert txt to docx in Python?

To convert a .txt file to .docx, you can use the python-docx library, which allows you to create, modify, and extract information from Word documents.

Example:

from docx import Document

# Create a new Document
doc = Document()
with open('file.txt', 'r') as file:
for line in file:
# Add a paragraph for each line
doc.add_paragraph(line.strip())

# Save the document to a .docx file
doc.save('output.docx')

These examples illustrate how to perform various conversions and operations involving text and speech in Python, showcasing its versatility in handling different formats and technologies



Previous Article
Next Article

Similar Reads

Python: Convert Speech to text and text to Speech
Speech Recognition is an important feature in several applications used such as home automation, artificial intelligence, etc. This article aims to provide an introduction on how to make use of the SpeechRecognition and pyttsx3 library of Python.Installation required: Python Speech Recognition module: pip install speechrecognitionPyAudio: Use the f
3 min read
Speech Recognition in Python using Google Speech API
Speech Recognition is an important feature in several applications used such as home automation, artificial intelligence, etc. This article aims to provide an introduction to how to make use of the SpeechRecognition library of Python. This is useful as it can be used on microcontrollers such as Raspberry Pi with the help of an external microphone.
4 min read
Convert Text to Speech in Python using win32com.client
There are several APIs available to convert text to speech in python. One of such APIs available in the python library commonly known as win32com library. It provides a bunch of methods to get excited about and one of them is the Dispatch method of the library. Dispatch method when passed with the argument of SAPI.SpVoice It interacts with the Micr
2 min read
Convert PDF File Text to Audio Speech using Python
Let us see how to read a PDF that is converting a textual PDF file into audio. Packages Used: pyttsx3: It is a Python library for Text to Speech. It has many functions which will help the machine to communicate with us. It will help the machine to speak to usPyPDF2: It will help to the text from the PDF. A Pure-Python library built as a PDF toolkit
2 min read
Python Text To Speech | pyttsx module
pyttsx is a cross-platform text to speech library which is platform independent. The major advantage of using this library for text-to-speech conversion is that it works offline. However, pyttsx supports only Python 2.x. Hence, we will see pyttsx3 which is modified to work on both Python 2.x and Python 3.x with the same code. Use this command for I
2 min read
Python | Text to Speech by using pyttsx3
pyttsx3 is a text-to-speech conversion library in Python. Unlike alternative libraries, it works offline and is compatible with both Python 2 and 3. An application invokes the pyttsx3.init() factory function to get a reference to a pyttsx3. Engine instance. it is a very easy to use tool which converts the entered text into speech. The pyttsx3 modul
2 min read
Text to speech GUI convertor using Tkinter in Python
Prerequisite: Introduction to Tkinter Tkinter is the standard GUI library for Python. Python when combined with tkinter provides a fast and easy way to create GUI applications.By this library we can make a compelling choice for building GUI applications in Python, especially for applications where a modern sheen is unnecessary, and the top priority
3 min read
Extract speech text from video in Python
Nowadays, videos have become an integral part of our lives. Videos educate us and provide the necessary information. In this article, we will learn how to extract text speech from video using Python. Extract Speech Text from the Video To extract speech text from video in Python, we require the following modules to install, Here we are using Python
3 min read
Speech To Text using IBM Watson Studio
IBM Watson Studio is an integrated environment designed to develop, train, manage models, and deploy AI-powered applications and is a Software as a Service (SaaS) solution delivered on the IBM Cloud. The IBM Cloud provides lots of services like Speech To Text, Text To Speech, Visual Recognition, Natural Language Classifier, Language Translator, etc
2 min read
Convert Text and Text File to PDF using Python
PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Document Format) is one of the basic requirements in
3 min read
Convert Text Image to Hand Written Text Image using Python
In this article, we are going to see how to convert text images to handwritten text images using PyWhatkit, Pillow, and Tesseract in Python. Module needed: Pytesseract: Sometimes known as Python-tesseract, is a Python-based optical character recognition (OCR) program. It can read and recognize text in photos, license plates, and other documents. To
2 min read
Part of Speech Tagging with Stop words using NLTK in python
The Natural Language Toolkit (NLTK) is a platform used for building programs for text analysis. One of the more powerful aspects of the NLTK module is the Part of Speech tagging.In order to run the below python program you must have to install NLTK. Please follow the installation steps. Open your terminal, run pip install nltk.Write python in the c
4 min read
Python - Get Today's Current Day using Speech Recognition
We often don't remember the day of the date due to our load of work we are doing. So, here is a Python program with the help of which we can find the day of the date with just a simple chat with our laptop or mobile. Modules NeededDateTime: This is a Library in Python with the help of which we can manipulate the date and time. It comes preinstalled
4 min read
Speech Recognition in Hindi using Python
We can use Python for Speech Recognition, it is mostly used to recognize English words. However, in this article, we are going to use Python so that it can also recognize Hindi words with the help of the Speech Recognition module. Requirements:Speech Recognition Module: It is a library with the help of which Python can recognize the command given.
2 min read
Speech Recognition in Python using CMU Sphinx
"Hey, Siri!", "Okay, Google!" and "Alexa playing some music" are some of the words that have become an integral part of our life as giving voice commands to our virtual assistants make our life a lot easier. But have you ever wondered how these devices are giving commands via voice/speech? Do applications understand your voice? How does the compute
5 min read
Restart your Computer with Speech Recognition
We can do this with the help of Python. Python has many libraries that can help many things to be done were easy. We need the help of the terminal for doing this task. Python's one of the best library Speech Recognition will help us to do this so. Modules RequiredPyttsx3: This is a text to speech Library in Python . We have to use pip for it.pip in
4 min read
POS(Parts-Of-Speech) Tagging in NLP
One of the core tasks in Natural Language Processing (NLP) is Parts of Speech (PoS) tagging, which is giving each word in a text a grammatical category, such as nouns, verbs, adjectives, and adverbs. Through improved comprehension of phrase structure and semantics, this technique makes it possible for machines to study and comprehend human language
11 min read
Convert Text file to JSON in Python
JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modul
4 min read
Convert emoji into text in Python
Converting emoticons or emojis into text in Python can be done using the demoji module. It is used to accurately remove and replace emojis in text strings. To install the demoji module the below command can be used: pip install demoji The demoji module also requires an initial download of data from the Unicode Consortium's emoji code repository as
1 min read
Convert Text File to CSV using Python Pandas
Let's see how to Convert Text File to CSV using Python Pandas. Python will read data from a text file and will create a dataframe with rows equal to number of lines present in the text file and columns equal to the number of fields present in a single line. See below example for better understanding. Dataframe created from upper text file will look
2 min read
Convert English text into the Phonetics using Python
In this article, we are going to see how to convert English text into the International Phonetic Alphabet. We are going to use the eng-to-ipa module to convert into phonetic. Installation: Run this code into your terminal. pip install eng-to-ipa Let's understands this module step-by-step: 1. Import this module and use convert() method to convert a
1 min read
How to convert CSV columns to text in Python?
In this article, we are going to see how to convert CSV columns to text in Python, and we will also see how to convert all CSV column to text. Approach: Read .CSV file using pandas dataframe.Convert particular column to list using list() constructorThen sequentially convert each element of the list to a string and join them using a specific charact
2 min read
How to Set Text of Tkinter Text Widget With a Button?
Prerequisite: Python GUI – tkinter Text Widget is used where a user wants to insert multi-line text fields. In this article, we are going to learn the approaches to set the text inside the text fields of the text widget with the help of a button. Approach: Using insert and delete methodImport the Tkinter module.Create a GUI window.Create our text w
2 min read
How to wrap text within Tkinter Text Box?
In this article, we will see that how can we wrap the text in the TKinter Text-Box using the Tkinter module Called textWrap Module. The textwrap module can be used for wrapping and formatting plain text. This module provides formatting of the text by adjusting the line breaks in the input paragraph. Example 1: Firstly We will import the Tkinter Lib
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Fetching text from Wikipedia's Infobox in Python
An infobox is a template used to collect and present a subset of information about its subject. It can be described as a structured document containing a set of attribute-value pairs, and in Wikipedia, it represents a summary of information about the subject of an article.So a Wikipedia infobox is a fixed-format table usually added to the top right
3 min read
Get all text of the page using Selenium in Python
As we know Selenium is an automation tool through which we can automate browsers by writing some lines of code. It is compatible with all browsers, Operating systems, and also its program can be written in any programming language such as Python, Java, and many more. Selenium provides a convenient API to access Selenium WebDrivers like Firefox, IE,
3 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Python | Display text to PyGame window
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of the developer, what type of game he/she wants to develop using this toolkit.. Command to install pygame on wind
6 min read
Python | How to dynamically change text of Checkbutton
Tkinter is a GUI (Graphical User interface) module which is used to create various types of applications. It comes along with the Python and consists of various types of widgets which can be used to make GUI more attractive and user-friendly. Checkbutton is one of the widgets which is used to select multiple options. Checkbutton can be created as f
2 min read
Article Tags :
Practice Tags :