Python Program to Convert Text to Speech
pyttsx3 library in Python to convert text to speech with pyttsx3.init() to initialize, engine.say(text) to set the text, and engine.runAndWait() to play the speech.Examples
How to Think About It
Algorithm
Code
import pyttsx3 def text_to_speech(text): engine = pyttsx3.init() engine.say(text) engine.runAndWait() # Example usage text_to_speech('Hello, how are you?') print('Speech completed.')
Dry Run
Let's trace the example 'Hello, how are you?' through the code
Import pyttsx3
The program loads the pyttsx3 library to use its speech functions.
Initialize engine
engine = pyttsx3.init() creates a speech engine instance.
Set text to speak
engine.say('Hello, how are you?') queues the text for speech.
Run speech engine
engine.runAndWait() plays the spoken text aloud.
Print completion
The program prints 'Speech completed.' after speaking.
| Step | Action | Value |
|---|---|---|
| 1 | Import library | pyttsx3 loaded |
| 2 | Initialize engine | engine instance created |
| 3 | Set text | 'Hello, how are you?' queued |
| 4 | Run engine | Speech played aloud |
| 5 | 'Speech completed.' |
Why This Works
Step 1: Initialize speech engine
The pyttsx3.init() function creates an engine that can convert text to speech.
Step 2: Queue text for speech
The engine.say(text) method tells the engine what words to speak.
Step 3: Play the speech
The engine.runAndWait() method processes the queued text and plays the audio aloud.
Alternative Approaches
from gtts import gTTS import os def text_to_speech_gtts(text): tts = gTTS(text=text, lang='en') tts.save('output.mp3') os.system('start output.mp3') # Use 'open' on Mac, 'xdg-open' on Linux text_to_speech_gtts('Hello, how are you?') print('Speech completed.')
import win32com.client def text_to_speech_win(text): speaker = win32com.client.Dispatch('SAPI.SpVoice') speaker.Speak(text) text_to_speech_win('Hello, how are you?') print('Speech completed.')
Complexity: O(n) time, O(n) space
Time Complexity
The time depends linearly on the length of the text n because the engine processes each character to generate speech.
Space Complexity
Space is proportional to the text length n as the engine stores the text internally before speaking.
Which Approach is Fastest?
The local pyttsx3 engine is faster than online services like gTTS because it does not require network calls.
| Approach | Time | Space | Best For |
|---|---|---|---|
| pyttsx3 | O(n) | O(n) | Offline, fast local speech |
| gTTS | O(n) + network delay | O(n) | High-quality speech, requires internet |
| pywin32 SAPI | O(n) | O(n) | Windows-only, native speech |
pip install pyttsx3 before running the program.engine.runAndWait() causes no speech to play.