Implementing TTS Using the pyttsx3 Library in Python

pyttsx3 (Python Text-to-Speech version 3) is a Python library for text-to-speech (TTS) that supports offline operation. It does not rely on an internet connection or third-party APIs, directly invoking the operating system’s speech engine (such as Windows SAPI5, Linux eSpeak, or macOS NSSpeechSynthesizer) for speech synthesis. It is easy to install with no complex dependencies, and supports adjusting parameters such as speech rate, volume, and voice selection.

To use it, first install the pyttsx3 library:

 pip install pyttsx3

Code implementation:

tts.py

import pyttsx3

# Initialize the engine
engine = pyttsx3.init()

# Set properties
engine.setProperty("rate", 150)    # Speech rate (default 200)
engine.setProperty("volume", 1.0)  # Volume (0.0-1.0)

# Select voice (supports both Chinese and English, depending on system support)
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[0].id)  # Select voice by index

# Convert text to speech
text = "hello, to be alive!"
engine.say(text)

# Wait for playback to finish
engine.runAndWait()

Leave a Comment