Create a Speech Synthesis System with Python
Below is the step-by-step procedure to make Python speak by using os.system() in Python:
Step 1: Install Necessary Libraries
To proceed, you need to have the gTTS library installed. Open your terminal and run:
pip install gTTS
Step 2: Create a Python Script
Use your preferred code editor to create a new Python script (e.g., main.py). Below is the breakdown of our main.py file code:
Import Required Modules
In your Python script, import the necessary modules:
from gtts import gTTS
import os
Define the Speak Function
The speak function encapsulates the text-to-speech functionality. It takes a text input as a parameter and uses pyttsx3 to convert it into spoken words. Optional properties, such as the speech rate, can be set using engine.setProperty.
def text_to_speech(text):
res = gTTS(text=text, lang='en')
filename = "output.mp3"
res.save(filename)
os.system(f"start {filename}")
Use the Speak Function
Now, you can use the speak function to make Python speak.
if __name__ == "__main__":
text = "Hello, I am w3wiki and I made a Speech Synthesis System With Python."
text_to_speech(text)
Complete Code Implementation
Below is the complete code implementation of our Python main.py file.
main.py
from gtts import gTTS
import os
def text_to_speech(text):
res = gTTS(text=text, lang='en')
filename = "output.mp3"
res.save(filename)
os.system(f"start {filename}")
if __name__ == "__main__":
text = "Hello, I am w3wiki and I made a Speech Synthesis System With Python."
text_to_speech(text)
Step 3: Run the Script
Save your script and run it using:
python main.py
This will execute the speak function, and you should hear the specified text being spoken by the system’s default TTS engine.
Output:
You will listen an audio saying “Hello, I am w3wiki and I made a Speech Synthesis System With Python”.
How to Create a Speech Synthesis System with Python
Text-to-speech (TTS) is a fascinating feature that adds a human touch to your Python applications. The gTTS library simplifies the process of incorporating TTS capabilities into your scripts. In this article, we’ll explore a simple Python script that utilizes gTTS to make Python speak and understand the key components of the code.