SoFunction
Updated on 2025-04-14

Complete Guide to Use Python Text-to-Speech Engine pyttsx3

Text-to-Speech (TTS) technology is a very useful tool when developing applications that require voice output. Python's pyttsx3 library provides a simple and offline way to implement this without relying on an internet connection or external API. This article will introduce the installation, basic usage and advanced functions of pyttsx3 to help you quickly master this practical tool.

What is pyttsx3

pyttsx3 is a cross-platform Python text-to-speech conversion library that works without the need for a network connection. This library uses TTS engines installed on your system, such as SAPI5 on Windows, NSS on macOS, and espeak on Linux.

Install

Installing pyttsx3 is very simple, just use the pip command:

pip install pyttsx3

On some systems, additional dependencies may be required:

Windows: No additional installation is usually required (using SAPI5)

macOS: PyObjC may need to be installed

pip install pyobjc

Linux: espeak needs to be installed

sudo apt-get install espeak

Basic use

Initialize the engine and speak

Here is the simplest example of using pyttsx3:

import pyttsx3

# Initialize the TTS engineengine = ()

# Set the text to be said("Hello, I'm a Python text to speech engine")

# Run and wait for the voice to complete()

Adjust voice properties

1. Change the speed of speech

The speed of speech is measured in word count per minute (WPM), and the default value is usually 200:

# Get the current speaking speedrate = ('rate')
print(f"Current speaking speed:{rate}")

# Set a new speaking speed (50% reduction)('rate', rate-100)

("This is the voice effect after lowering the speed of speech")
()

2. Change the volume

Volume range from 0.0 to 1.0:

# Get the current volumevolume = ('volume')
print(f"Current volume:{volume}")

# Set the new volume (0.0 to 1.0)('volume', 0.7)  #70% volume
("This is the voice effect after adjusting the volume")
()

3. Change the sound

pyttsx3 allows to use different sounds available on the system:

# Get a list of available soundsvoices = ('voices')

# Print information about available soundsfor i, voice in enumerate(voices):
    print(f"voice{i}:")
    print(f" - ID: {}")
    print(f" - name: {}")
    print(f" - language: {}")
    print(f" - gender: {}")
    print(f" - age: {}")

# Set the second sound (if any)if len(voices) > 1:
    ('voice', voices[1].id)
    ("This is the effect of using another sound")
    ()

Advanced features

Save voice as file

In addition to playing voice directly, pyttsx3 can also save voice as an audio file:

engine = ()

# Set the text to be savedtext = "This text will be saved as an audio file"

# Save as WAV fileengine.save_to_file(text, '')
()

Use event callback

pyttsx3 provides an event callback mechanism that allows you to perform specific actions when a speech starts, ends, or errors occur:

def onStart(name):
    print(f'start: {name}')

def onWord(name, location, length):
    print(f'word: {name}, Location: {location}, length: {length}')

def onEnd(name, completed):
    print(f'Finish: {name}, Finish: {completed}')

# Connect callback functionengine = ()
('started-utterance', onStart)
('started-word', onWord)
('finished-utterance', onEnd)

('This text will trigger the callback function')
()

Multi-threaded use

In graphical interfaces or applications that require non-blocking voice output, the TTS engine can be run in a separate thread:

import threading
import time

def speak_in_thread(text):
    engine = ()
    (text)
    ()
    ()

# Create a thread to play voicespeech_thread = (target=speak_in_thread, args=("This text will be played in a separate thread and will not block the main program",))
speech_thread.start()

# The main program can continue to perform other tasksprint("Voice playback has started, but the main program continues to execute")
for i in range(5):
    print(f"Main thread count: {i}")
    (0.5)

# Wait for the voice thread to endspeech_thread.join()
print("Voice playback is completed")

Practical Examples

Simple text reader

import pyttsx3

def text_reader(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            text = ()
            
        engine = ()
        print("Start reading the file...")
        (text)
        ()
        print("File reading completed")
    except FileNotFoundError:
        print(f"mistake: File not found '{file_path}'")
    except Exception as e:
        print(f"发生mistake: {e}")

#User Exampletext_reader('')

Simple voice reminder tool

import pyttsx3
import time
import threading

class VoiceReminder:
    def __init__(self):
         = ()
         = []
         = True
        self.check_thread = (target=self._check_reminders)
        self.check_thread.daemon = True
        self.check_thread.start()
    
    def add_reminder(self, message, minutes):
        reminder_time = () + minutes * 60
        ((reminder_time, message))
        print(f"Reminder set: '{message}' Will be in {minutes} Reminder in minutes")
    
    def _check_reminders(self):
        while :
            current_time = ()
            # Check if there is an expired reminder            for i, (reminder_time, message) in enumerate([:]):
                if current_time >= reminder_time:
                    print(f"remind: {message}")
                    (message)
                    ()
                    # Delete triggered reminders                    (i)
            (1)
    
    def stop(self):
         = False
        self.check_thread.join(timeout=1)

#User Examplereminder = VoiceReminder()
reminder.add_reminder("It's time to drink water", 0.1)  # Reminder in 6 secondsreminder.add_reminder("Stay a break from your eyes", 0.2)  # Reminder in 12 seconds
# Keep the program running long enough to trigger the reminder(15)
()

FAQs and Solutions

module named ‘’

Solution: pip install pywin32

module named ‘pyttsx3’

Make sure pyttsx3 is installed correctly: pip install pyttsx3

3. Cannot change the sound/No sound found

Make sure that extra TTS sound is installed on the system. On Windows, you can add extra sound to Control Panel > Voice Recognition > Text to Speech.

No sound output on

Make sure espeak is installed: sudo apt-get install espeak

5. Speed ​​adjustment does not work

Try a wider range of adjustments, some engines are not sensitive to small adjustments.

Summarize

pyttsx3 is a powerful and easy to use Python text-to-speech library that provides the core functionality of speech synthesis while maintaining a simple API. Its offline features make it ideal for applications that require TTS capabilities but do not want to rely on network services.

Through this tutorial, you should have mastered the basic usage of pyttsx3 and some advanced techniques. You can apply this knowledge to various projects such as assistive technologies, language learning applications, voice notification systems, or any application that requires voice output.

This is the article about the complete guide to using Python text to voice engine pyttsx3. For more related Python pyttsx3 text to voice content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!