In this post, we will learn how to convert text to speech in Python with detailed explanation and example.
In Python, it is very easy and simple to convert text to speech using pre-built Python libraries. If you are a beginner, you can consider it as your project to learn how to work with external libraries and also by creating this text to speech converter you can do so much exciting things so letβs start learning how we can create text-to-speech converter.
Install Important Libraries
For creating text to speech converter we need to install two external libraries.
1. gTTS (Google Text-to-Speech) Library: gTTs is python external library and it will convert text input into mp3 file. to install this library write below command in your terminal. π Read more about gTTs Library
pip install gTTS
2. playsound Module: Using this module we will play our mp3 file generated by gTTs. To install it write below command in your terminal. π Read more about playsound module
pip install playsound
After installing both libraries write the following code and run it to see the output.
Source Code
from gtts import gTTS
import playsound
text = input("Enter your Text: ")
sound = gTTS(text, lang="en") # convert text to speech
# save your sound (audio file)
sound.save("my_sound.mp3")
print("Sound is playing....")
# Play the saved audio file
playsound.playsound("my_sound.mp3")
print("End")
Output
Enter your Text: Hello let's start learning python with allinpython
Sound is playing....
End
This is all about how we can convert text to speech. I hope this article helps you learn new things. Thank you for reading, and see you in the next post.
Also check out π 75+ Python programs for your Practice.