Text to Speech in Python for NLP: Simple Guide & Example
You can do text to speech in Python using the
pyttsx3 library, which converts text into spoken audio offline. Install it with pip install pyttsx3, then use its simple API to input text and play or save the speech output.Syntax
The basic syntax to use pyttsx3 involves initializing the engine, setting properties like speech rate or voice, and then calling say() to queue text for speaking. Finally, runAndWait() processes the speech.
engine = pyttsx3.init(): Creates the speech engine.engine.say(text): Adds text to speak.engine.runAndWait(): Runs the speech queue and waits until done.- Optional:
engine.setProperty()to adjust voice or speed.
python
import pyttsx3 engine = pyttsx3.init() # Initialize the TTS engine engine.say('Hello, this is a test.') # Queue text to speak engine.runAndWait() # Play the speech
Output
The computer speaks: "Hello, this is a test."
Example
This example shows how to convert a simple text string to speech, change the speech rate, and select a different voice if available.
python
import pyttsx3 engine = pyttsx3.init() # Set speech rate (default is usually 200 words per minute) rate = engine.getProperty('rate') engine.setProperty('rate', rate - 50) # slower speech # List available voices and select one voices = engine.getProperty('voices') if len(voices) > 1: engine.setProperty('voice', voices[1].id) # change to second voice if exists text = 'Welcome to text to speech conversion using Python.' engine.say(text) engine.runAndWait()
Output
The computer speaks: "Welcome to text to speech conversion using Python."
Common Pitfalls
Common mistakes include not calling runAndWait() after say(), which means the speech won't play. Another issue is using voices that may not exist on your system, causing errors. Also, forgetting to install pyttsx3 or missing dependencies can cause failures.
Always test voice availability and handle exceptions for better reliability.
python
import pyttsx3 engine = pyttsx3.init() # Wrong: Missing runAndWait(), speech will not play engine.say('This will not be heard') # Correct: engine.say('This will be heard') engine.runAndWait()
Output
The computer speaks only: "This will be heard"
Quick Reference
| Function | Description |
|---|---|
| pyttsx3.init() | Initialize the text-to-speech engine |
| engine.say(text) | Queue text to be spoken |
| engine.runAndWait() | Process and play the queued speech |
| engine.setProperty('rate', value) | Set speech speed (words per minute) |
| engine.setProperty('voice', voice_id) | Set the voice by ID |
| engine.getProperty('voices') | Get list of available voices |
Key Takeaways
Use the pyttsx3 library for offline text to speech in Python.
Always call engine.runAndWait() after engine.say() to hear speech.
Adjust speech rate and voice properties to customize output.
Check available voices on your system before setting voice.
Install pyttsx3 with pip and ensure dependencies are met.
