1 min read

Python pyttsx3 Module

pyttsx3 is a text-to-speech conversion library in Python. Unlike alternative libraries, it works offline and is compatible with both Python 2 and 3.

Installation

pip install pyttsx3

Basic Usage

import pyttsx3

engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()

Changing Properties

You can get and set properties like rate (speed), volume, and voice.

import pyttsx3

engine = pyttsx3.init()

# Rate
rate = engine.getProperty('rate')
print(f"Current rate: {rate}")
engine.setProperty('rate', 125)

# Volume
volume = engine.getProperty('volume')
print(f"Current volume: {volume}")
engine.setProperty('volume', 1.0) # Between 0 and 1

# Voices
voices = engine.getProperty('voices')
# 0 for male, 1 for female (usually)
engine.setProperty('voice', voices[1].id)

engine.say("Hello World!")
engine.runAndWait()

Saving to File

Instead of playing the sound immediately, you can save it to a file.

engine.save_to_file('Hello World', 'test.mp3')
engine.runAndWait()

programming/python/python