### Examples Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Illustrative examples of how to use the pyttsx3 library for various text-to-speech tasks. ```APIDOC ## Examples ### Speaking text ```python import pyttsx3 engine = pyttsx3.init() engine.say('Sally sells seashells by the seashore.') engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait() ``` ### Saving voice to a file ```python import pyttsx3 engine = pyttsx3.init() engine.save_to_file('Hello World' , 'test.mp3') engine.runAndWait() ``` ### Listening for events ```python import pyttsx3 def onStart(name): print('starting', name) def onWord(name, location, length): print('word', name, location, length) def onEnd(name, completed): print('finishing', name, completed) engine = pyttsx3.init() engine.connect('started-utterance', onStart) engine.connect('started-word', onWord) engine.connect('finished-utterance', onEnd) engine.say('The quick brown fox jumped over the lazy dog.', 'fox') engine.runAndWait() ``` ### Interrupting an utterance ```python import pyttsx3 def onWord(name, location, length): print('word', name, location, length) if location > 10: engine.stop() engine = pyttsx3.init() engine.connect('started-word', onWord) engine.say('The quick brown fox jumped over the lazy dog.', 'fox') engine.runAndWait() ``` ### Changing voices ```python engine = pyttsx3.init() voices = engine.getProperty('voices') for voice in voices: engine.setProperty('voice', voice.id) engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait() ``` ### Changing speech rate ```python engine = pyttsx3.init() rate = engine.getProperty('rate') engine.setProperty('rate', rate+50) engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait() ``` ### Changing volume ```python engine = pyttsx3.init() volume = engine.getProperty('volume') engine.setProperty('volume', volume-0.25) engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait() ``` ### Running a driver event loop ```python engine = pyttsx3.init() def onStart(name): print('starting', name) def onWord(name, location, length): print('word', name, location, length) def onEnd(name, completed): print('finishing', name, completed) if name == 'fox': engine.say('What a lazy dog!', 'dog') elif name == 'dog': engine.endLoop() engine = pyttsx3.init() engine.connect('started-utterance', onStart) engine.connect('started-word', onWord) engine.connect('finished-utterance', onEnd) engine.say('The quick brown fox jumped over the lazy dog.', 'fox') engine.startLoop() ``` ### Using an external event loop ```python engine = pyttsx3.init() engine.say('The quick brown fox jumped over the lazy dog.', 'fox') engine.startLoop(False) # engine.iterate() must be called inside externalLoop() externalLoop() engine.endLoop() ``` ``` -------------------------------- ### Complete Application Example Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt A comprehensive example demonstrating initialization, voice configuration, event handling, and saving speech to an audio file. ```APIDOC ## Complete Application Example ### Description This example demonstrates a complete pyttsx3 application, including initializing the engine, setting speech properties (rate, volume), selecting a voice, connecting event handlers for word and utterance completion, speaking text, and saving audio to a file. ### Method `init()` `setProperty(name, value)` `getProperty(name)` `connect(event, callback)` `say(text, name)` `runAndWait()` `save_to_file(text, filename)` `stop()` ### Endpoint N/A (Method calls on engine object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pyttsx3 def text_to_speech_app(): # Initialize engine engine = pyttsx3.init() # Configure voice settings engine.setProperty('rate', 175) # Speaking rate engine.setProperty('volume', 0.9) # Volume level # Select a voice voices = engine.getProperty('voices') if len(voices) > 1: engine.setProperty('voice', voices[1].id) # Use second voice # Event tracking word_count = [0] def on_word(name, location, length): word_count[0] += 1 def on_end(name, completed): print(f"Spoke {word_count[0]} words, completed: {completed}") word_count[0] = 0 engine.connect('started-word', on_word) engine.connect('finished-utterance', on_end) # Speak text message = "Welcome to pyttsx3. This library converts text to speech offline." engine.say(message, name='welcome') engine.runAndWait() # Blocks until all queued commands are spoken # Save to file engine.save_to_file(message, 'welcome.mp3') engine.runAndWait() # Blocks until file saving is complete print("Audio saved to welcome.mp3") # Cleanup engine.stop() if __name__ == '__main__': text_to_speech_app() ``` ### Response #### Success Response (200) N/A (This is a script execution, not an API response) #### Response Example ``` Spoke 11 words, completed: True Audio saved to welcome.mp3 ``` ``` -------------------------------- ### Install pyttsx3 and Dependencies Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Instructions for installing the pyttsx3 library and necessary system-level dependencies for Linux and macOS platforms. ```bash # Basic installation pip install pyttsx3 # Linux: Install eSpeak engine sudo apt update && sudo apt install espeak-ng libespeak1 # macOS: If pyobjc errors occur pip install pyobjc>=9.0.1 ``` -------------------------------- ### Install pyttsx3 and Dependencies Source: https://github.com/nateshmbhat/pyttsx3/blob/master/README.md Commands to install the pyttsx3 library and necessary system dependencies for Linux environments. ```bash pip install pyttsx3 pip install --upgrade wheel sudo apt update && sudo apt install espeak-ng libespeak1 ``` -------------------------------- ### Connect and Listen to Events Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Demonstrates how to connect custom callback functions to various speech events like utterance start, word start, and utterance end. The engine then speaks text, and the connected functions are executed at the appropriate times. ```python import pyttsx3 def onStart(name): print('starting', name) def onWord(name, location, length): print('word', name, location, length) def onEnd(name, completed): print('finishing', name, completed) engine = pyttsx3.init() engine.connect('started-utterance', onStart) engine.connect('started-word', onWord) engine.connect('finished-utterance', onEnd) engine.say('The quick brown fox jumped over the lazy dog.', 'fox') engine.runAndWait() ``` -------------------------------- ### Complete pyttsx3 Application Example Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt A comprehensive Python application demonstrating the full capabilities of pyttsx3, including initialization, voice property configuration (rate, volume, voice selection), event handling for word count and utterance completion, speaking text, and saving audio to a file. ```python import pyttsx3 def text_to_speech_app(): engine = pyttsx3.init() engine.setProperty('rate', 175) engine.setProperty('volume', 0.9) voices = engine.getProperty('voices') if len(voices) > 1: engine.setProperty('voice', voices[1].id) word_count = [0] def on_word(name, location, length): word_count[0] += 1 def on_end(name, completed): print(f"Spoke {word_count[0]} words, completed: {completed}") word_count[0] = 0 engine.connect('started-word', on_word) engine.connect('finished-utterance', on_end) message = "Welcome to pyttsx3. This library converts text to speech offline." engine.say(message, name='welcome') engine.runAndWait() engine.save_to_file(message, 'welcome.mp3') engine.runAndWait() print("Audio saved to welcome.mp3") engine.stop() if __name__ == '__main__': text_to_speech_app() ``` -------------------------------- ### Start and Manage Driver Event Loop Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Initializes the engine, connects event handlers, and starts the driver's internal event loop using `startLoop()`. This loop processes queued commands and fires notifications. The loop can be explicitly ended with `engine.endLoop()`. ```python engine = pyttsx3.init() def onStart(name): print('starting', name) def onWord(name, location, length): print('word', name, location, length) def onEnd(name, completed): print('finishing', name, completed) if name == 'fox': engine.say('What a lazy dog!', 'dog') elif name == 'dog': engine.endLoop() engine = pyttsx3.init() engine.connect('started-utterance', onStart) engine.connect('started-word', onWord) engine.connect('finished-utterance', onEnd) engine.say('The quick brown fox jumped over the lazy dog.', 'fox') engine.startLoop() ``` -------------------------------- ### Configure Speech Properties in pyttsx3 Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Demonstrates how to get and set speech parameters such as volume, pitch, and rate. These settings allow fine-tuning of the synthesized voice output. ```python import pyttsx3 engine = pyttsx3.init() # Set volume engine.setProperty('volume', 0.5) engine.say("This is spoken at half volume.") # Set pitch (espeak driver) engine.setProperty('pitch', 75) engine.say("This is spoken with higher pitch.") # Reset to defaults engine.setProperty('rate', 200) engine.setProperty('volume', 1.0) engine.runAndWait() ``` -------------------------------- ### Configure Voice Properties Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Demonstrates how to get and set engine properties such as speech rate and volume to customize the synthesized voice output. ```python import pyttsx3 engine = pyttsx3.init() # Get and set RATE (words per minute, default ~200) current_rate = engine.getProperty('rate') print(f"Current rate: {current_rate} wpm") engine.setProperty('rate', 150) # Slower speech engine.say("This is spoken at 150 words per minute.") engine.runAndWait() ``` -------------------------------- ### Implement Event Callbacks Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Demonstrates how to register callback functions to track the lifecycle of an utterance, including start, word-level progress, completion, and error handling. ```python import pyttsx3 engine = pyttsx3.init() def on_start(name): print(f"Starting: {name}") engine.connect('started-utterance', on_start) engine.say('Hello', name='greeting') engine.runAndWait() ``` -------------------------------- ### Use External Event Loop Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Initializes the engine and queues a command, then starts an external event loop by calling `startLoop(False)`. This requires the user to manually manage the event loop by calling `engine.iterate()` within their own loop structure, followed by `engine.endLoop()`. ```python engine = pyttsx3.init() engine.say('The quick brown fox jumped over the lazy dog.', 'fox') engine.startLoop(False) # engine.iterate() must be called inside externalLoop() externalLoop() engine.endLoop() ``` -------------------------------- ### Volume and Pitch Control Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Demonstrates how to get and set the speech volume (0.0 to 1.0) and pitch (0-100, espeak driver only). ```APIDOC ## Volume and Pitch Control ### Description This section shows how to manipulate the speech synthesis engine's volume and pitch. ### Method - `engine.getProperty('volume')` - `engine.setProperty('volume', value)` - `engine.getProperty('pitch')` - `engine.setProperty('pitch', value)` ### Parameters #### Volume - **volume** (float) - Required - A float between 0.0 and 1.0 representing the speech volume. #### Pitch - **pitch** (int) - Required - An integer between 0 and 100 representing the speech pitch. This is only supported by the espeak driver. ### Request Example ```python import pyttsx3 engine = pyttsx3.init() # Get and set VOLUME (0.0 to 1.0) current_volume = engine.getProperty('volume') print(f"Current volume: {current_volume}") engine.setProperty('volume', 0.5) # Half volume engine.say("This is spoken at half volume.") engine.runAndWait() # Get and set PITCH (0-100, default 50, espeak driver only) pitch = engine.getProperty('pitch') print(f"Current pitch: {pitch}") engine.setProperty('pitch', 75) # Higher pitch engine.say("This is spoken with higher pitch.") engine.runAndWait() # Reset to defaults engine.setProperty('rate', 200) engine.setProperty('volume', 1.0) ``` ### Response No direct response, but the audio output will reflect the set volume and pitch. ``` -------------------------------- ### Event Callbacks Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Registers callback functions to handle speech events such as utterance start/end, word start, and errors. ```APIDOC ## engine.connect() - Event Callbacks ### Description Registers callback functions for speech events: `started-utterance`, `started-word`, `finished-utterance`, and `error`. Returns a token for later disconnection. ### Method `engine.connect(event_name, callback_function)` ### Endpoint N/A (This is a method call within the library) ### Parameters #### Path Parameters - **event_name** (string) - Required - The name of the event to connect to (e.g., 'started-utterance', 'finished-utterance'). - **callback_function** (function) - Required - The function to be called when the event occurs. ### Request Example ```python import pyttsx3 engine = pyttsx3.init() # Callback when utterance starts def on_start(name): print(f"Starting utterance: {name}") # Callback for each word (with position info) def on_word(name, location, length): print(f"Word in '{name}': position={location}, length={length}") # Callback when utterance finishes def on_end(name, completed): status = "completed" if completed else "interrupted" print(f"Finished utterance '{name}': {status}") # Callback for errors def on_error(name, exception): print(f"Error in '{name}': {exception}") # Register all callbacks token_start = engine.connect('started-utterance', on_start) token_word = engine.connect('started-word', on_word) token_end = engine.connect('finished-utterance', on_end) token_error = engine.connect('error', on_error) # Speak with named utterance to track in callbacks engine.say('The quick brown fox jumps over the lazy dog.', name='pangram') engine.runAndWait() # Output: # Starting utterance: pangram # Word in 'pangram': position=0, length=3 # Word in 'pangram': position=4, length=5 # ... (more words) # Finished utterance 'pangram': completed ``` ### Response - **token** (object) - A token that can be used to disconnect the callback later using `engine.disconnect(token)`. ``` -------------------------------- ### pyttsx3.init() Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Initializes the text-to-speech engine with a specific driver. ```APIDOC ## GET pyttsx3.init() ### Description Gets a reference to an engine instance that will use the given driver. If the requested driver is already in use, that instance is returned. ### Method GET ### Endpoint pyttsx3.init(driverName=None, debug=False) ### Parameters #### Query Parameters - **driverName** (string) - Optional - Name of the driver module (avspeech, espeak, nsss, sapi5). - **debug** (bool) - Optional - Enable debug output. ### Response #### Success Response (200) - **engine** (pyttsx3.Engine) - An instance of the speech engine. ``` -------------------------------- ### Basic Text-to-Speech Execution Source: https://github.com/nateshmbhat/pyttsx3/blob/master/README.md Demonstrates how to initialize the engine and speak text using both standard and shorthand methods. ```python import pyttsx3 engine = pyttsx3.init() engine.say("I will speak this text") engine.runAndWait() # Single line usage pyttsx3.speak("I will speak this text") ``` -------------------------------- ### Initialize pyttsx3 Engine Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Demonstrates how to initialize the TTS engine with default or specific drivers and how to enable debug mode for troubleshooting. ```python import pyttsx3 # Initialize with default driver (auto-detected based on OS) engine = pyttsx3.init() # Initialize with specific driver # Options: 'sapi5' (Windows), 'nsss' (macOS), 'espeak' (Linux/all), 'avspeech' (macOS) engine = pyttsx3.init(driverName='espeak') # Enable debug output for troubleshooting engine = pyttsx3.init(debug=True) # Check which driver is being used print(f"Using driver: {engine.driver_name}") ``` -------------------------------- ### Configure Speech Properties and Save to File Source: https://github.com/nateshmbhat/pyttsx3/blob/master/README.md Shows how to adjust speaking rate, volume, and voice selection, as well as how to export the speech output to an audio file. ```python import pyttsx3 engine = pyttsx3.init() # Set rate engine.setProperty('rate', 125) # Set volume engine.setProperty('volume', 1.0) # Set voice voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) engine.say("Hello World!") engine.runAndWait() # Save to file engine.save_to_file('Hello World', 'test.mp3') engine.runAndWait() ``` -------------------------------- ### Initialize and Speak Text Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Initializes the pyttsx3 engine and queues multiple utterances to be spoken sequentially. The `runAndWait()` method processes these commands and blocks until all speech is completed. ```python import pyttsx3 engine = pyttsx3.init() engine.say('Sally sells seashells by the seashore.') engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait() ``` -------------------------------- ### Quick Text-to-Speech Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Shows the simplest method to perform text-to-speech conversion using the convenience speak function. ```python import pyttsx3 # Simplest way to speak text - one line pyttsx3.speak("Hello, this is a quick text-to-speech example!") # Equivalent to: engine = pyttsx3.init() engine.say("Hello, this is a quick text-to-speech example!") engine.runAndWait() ``` -------------------------------- ### Process Speech Queue with runAndWait Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Demonstrates how to block execution until the speech queue is fully processed, ensuring all utterances are spoken before proceeding. ```python import pyttsx3 engine = pyttsx3.init() engine.say("Processing first batch of text.") engine.say("Still in the first batch.") engine.runAndWait() # Blocks until both utterances complete print("First batch complete!") engine.say("Now processing second batch.") engine.runAndWait() # Blocks again for second batch print("All speech complete!") ``` -------------------------------- ### Event Loop Control with engine.startLoop() and engine.endLoop() in pyttsx3 Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Illustrates manual control over the pyttsx3 event loop using `startLoop()` and `endLoop()`. This is useful for advanced scenarios, especially when integrating with callbacks for interactive applications. ```python import pyttsx3 engine = pyttsx3.init() def on_end(name, completed): if name == 'greeting': engine.say('How can I help you today?', name='question') elif name == 'question': engine.say('Goodbye!', name='farewell') elif name == 'farewell': engine.endLoop() engine.connect('finished-utterance', on_end) engine.say('Hello! Welcome to the system.', name='greeting') engine.startLoop() ``` -------------------------------- ### Queue Speech Utterances Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Explains how to queue multiple text sentences for sequential speech synthesis and how to use named utterances for tracking. ```python import pyttsx3 engine = pyttsx3.init() # Queue single utterance engine.say("First sentence to speak.") # Queue multiple utterances - they play in sequence engine.say("This is the second sentence.") engine.say("And this is the third.") # Named utterance for event tracking engine.say("Important announcement!", name="announcement") # Process the queue and speak all utterances engine.runAndWait() ``` -------------------------------- ### Manage and Select System Voices Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Shows how to retrieve all available voices on the system and select a specific voice by ID or by filtering attributes like gender. ```python import pyttsx3 engine = pyttsx3.init() voices = engine.getProperty('voices') # Select voice by index engine.setProperty('voice', voices[0].id) # Find voice by gender for voice in voices: if 'female' in (voice.gender or '').lower(): engine.setProperty('voice', voice.id) break engine.runAndWait() ``` -------------------------------- ### Implementing a Custom Driver Delegate Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/drivers.md This snippet illustrates the structure of a custom driver delegate class. It must implement methods like say, startLoop, and setProperty to handle speech synthesis and engine communication. ```python class MyDriverDelegate: def __init__(self, proxy, *args, **kwargs): self.proxy = proxy def say(self, text, name): self.proxy.setBusy(True) # Implementation for speech output self.proxy.notify('finished-utterance', name=name) self.proxy.setBusy(False) def setProperty(self, name, value): # Implementation for setting properties self.proxy.setBusy(False) def startLoop(self): # Implementation for event loop pass def stop(self): # Implementation for stopping output self.proxy.setBusy(False) def buildDriver(proxy): return MyDriverDelegate(proxy) ``` -------------------------------- ### Iterate and Change Voices Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Demonstrates iterating through available voices and setting each one as the active voice. The engine then speaks a sample sentence using the currently selected voice. This requires the engine to be initialized. ```python engine = pyttsx3.init() voices = engine.getProperty('voices') for voice in voices: engine.setProperty('voice', voice.id) engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait() ``` -------------------------------- ### External Event Loop Integration with pyttsx3 Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Demonstrates integrating pyttsx3 with an external event loop, suitable for GUI applications or async frameworks. It uses `startLoop(useDriverLoop=False)` and manual `engine.iterate()` calls. ```python import pyttsx3 import time engine = pyttsx3.init() def on_end(name, completed): print(f"Finished: {name}") if name == 'last': engine.endLoop() engine.connect('finished-utterance', on_end) engine.say('First utterance.', name='first') engine.say('Second utterance.', name='second') engine.say('Last utterance.', name='last') engine.startLoop(useDriverLoop=False) while True: try: engine.iterate() time.sleep(0.01) except RuntimeError: break print("External loop complete!") ``` -------------------------------- ### Save Speech to File Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Initializes the pyttsx3 engine and saves spoken text to an audio file. `runAndWait()` is required to process the save command and generate the file. ```python import pyttsx3 engine = pyttsx3.init() engine.save_to_file('Hello World' , 'test.mp3') engine.runAndWait() ``` -------------------------------- ### Engine.connect() Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Registers a callback for specific engine events. ```APIDOC ## POST /engine/connect ### Description Registers a callback function for notifications on a specific topic such as 'started-utterance' or 'error'. ### Method POST ### Endpoint engine.connect(topic, cb) ### Parameters #### Request Body - **topic** (string) - Required - The event name to subscribe to. - **cb** (callable) - Required - The function to invoke when the event fires. ### Response #### Success Response (200) - **token** (dict) - A token used to unsubscribe the callback later. ``` -------------------------------- ### Driver Factory Function Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/drivers.md The `buildDriver` function is responsible for instantiating the driver delegate. It takes a `DriverProxy` instance provided by the `pyttsx3.Engine`. ```APIDOC ## pyttsx3.drivers.buildDriver ### Description Instantiates delegate subclass declared in this module. ### Method Factory Function ### Parameters #### Path Parameters - **proxy** (pyttsx3.driver.DriverProxy) - Required - Proxy instance provided by a `pyttsx3.Engine` instance. ### Returns - **DriverDelegate** - An instance of the driver delegate. ``` -------------------------------- ### Save Synthesized Speech to Audio Files Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Explains how to export text-to-speech output directly to audio files like MP3 or WAV instead of playing them through the system speakers. ```python import pyttsx3 engine = pyttsx3.init() # Save speech to file engine.save_to_file('Hello World!', 'output.mp3') engine.runAndWait() ``` -------------------------------- ### Engine Methods Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Core methods for controlling the text-to-speech engine, including speaking text, setting properties, and managing the event loop. ```APIDOC ## Engine Methods ### say(text: unicode, name: string) → None #### Description Queues a command to speak an utterance. The speech is output according to the properties set before this command in the queue. #### Parameters * **text** (unicode) - Required - Text to speak. * **name** (string) - Required - Name to associate with the utterance. Included in notifications about this utterance. ### setProperty(name, value) → None #### Description Queues a command to set an engine property. The new property value affects all utterances queued after this command. #### Parameters * **name** (string) - Required - Name of the property to change. * **value** (any) - Required - Value to set. ### startLoop(useDriverLoop: bool = True) → None #### Description Starts running an event loop during which queued commands are processed and notifications are fired. #### Parameters * **useDriverLoop** (bool) - Optional - True to use the loop provided by the selected driver. False to indicate the caller will enter its own loop after invoking this method. Defaults to True. ### stop() → None #### Description Stops the current utterance and clears the command queue. ### save_to_file(text, filename) → None #### Description Saves the spoken text to an audio file. #### Parameters * **text** (unicode) - Required - Text to save. * **filename** (string) - Required - The name of the file to save to. ### getProperty(name) → any #### Description Retrieves the current value of an engine property. #### Parameters * **name** (string) - Required - The name of the property to retrieve. ### setProperty(name, value) → None #### Description Sets the value of an engine property. #### Parameters * **name** (string) - Required - The name of the property to set. * **value** (any) - Required - The value to set the property to. ### connect(name, callable) → None #### Description Connects a callback function to an event. #### Parameters * **name** (string) - Required - The name of the event to connect to. * **callable** (function) - Required - The callback function to execute when the event is fired. ### runAndWait() → None #### Description Processes all currently queued commands and waits for them to complete. This method should be called after queuing commands like `say` or `save_to_file`. ### endLoop() → None #### Description Ends the current event loop. This is typically used when `startLoop` was called with `useDriverLoop=False`. ``` -------------------------------- ### Accessing Voice Metadata with the Voice Class in pyttsx3 Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Explains how to access and use the `Voice` class in pyttsx3 to retrieve metadata about available speech synthesis voices, such as ID, name, languages, gender, and age. Includes a function to filter voices by criteria. ```python import pyttsx3 engine = pyttsx3.init() voices = engine.getProperty('voices') voice = voices[0] print(f"ID: {voice.id}") print(f"Name: {voice.name}") print(f"Languages: {voice.languages}") print(f"Gender: {voice.gender}") print(f"Age: {voice.age}") def find_voices(voices, language=None, gender=None): results = [] for voice in voices: if language and language not in str(voice.languages): continue if gender and voice.gender != gender: continue results.append(voice) return results english_female = find_voices(voices, language='en', gender='female') for v in english_female: print(f"Found: {v.name}") ``` -------------------------------- ### DriverDelegate Interface Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/drivers.md All custom drivers must implement the `DriverDelegate` interface. This interface defines the methods for controlling speech output, properties, and event loops. ```APIDOC ## class pyttsx3.drivers.DriverDelegate ### Description This is an interface documentation. The actual class is not declared in `pyttsx3.drivers` and cannot be used as a base class directly. ### Methods #### __init__(proxy: pyttsx3.drivers.DriverProxy, *args, **kwargs) -> None - **Description**: Constructor. Must store the proxy reference. - **Parameters**: - **proxy** (pyttsx3.drivers.DriverProxy) - Required - Proxy instance provided by the `buildDriver()` function. #### destroy() - **Description**: Optional. Invoked by the `pyttsx3.driver.DriverProxy` when it is being destroyed so this delegate can clean up any synthesizer resources. If not implemented, the proxy proceeds safely. #### endLoop() -> None - **Description**: Immediately ends a running driver event loop. #### getProperty(name: string) -> object - **Description**: Immediately gets the named property value. Must support properties listed in `pyttsx3.Engine.getProperty()`. - **Parameters**: - **name** (string) - Required - Name of the property to query. - **Returns**: Value of the property at the time of this invocation. #### say(text: unicode, name: string) -> None - **Description**: Immediately speaks an utterance. Must trigger notifications for utterance start, word start, and utterance end. Must call `setBusy(True)` before returning. - **Parameters**: - **text** (unicode) - Required - Text to speak. - **name** (string) - Required - Name to associate with the utterance. #### setProperty(name: string, value: object) -> None - **Description**: Immediately sets the named property value. Must support properties listed in `pyttsx3.Engine.setProperty()`. Must call `setBusy(False)` after setting the property. - **Parameters**: - **name** (string) - Required - Name of the property to change. - **value** (object) - Required - Value to set. #### startLoop() - **Description**: Immediately starts an event loop responsible for sending notifications and pumping the command queue. #### stop() - **Description**: Immediately stops the current utterance output. Must trigger a finished-utterance notification if output is ongoing. Must call `setBusy(False)` after stopping. ``` -------------------------------- ### engine.startLoop() / engine.endLoop() - Event Loop Control Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Provides manual control over the engine's event loop for advanced use cases and integration with callbacks. ```APIDOC ## engine.startLoop() / engine.endLoop() ### Description These methods provide manual control over the event loop. `startLoop()` begins processing events, and `endLoop()` terminates it. Use with callbacks for interactive applications or custom event handling. ### Method `startLoop(useDriverLoop=True)` `endLoop()` ### Endpoint N/A (Method calls on engine object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pyttsx3 engine = pyttsx3.init() def on_end(name, completed): if name == 'greeting': engine.say('How can I help you today?', name='question') elif name == 'question': engine.say('Goodbye!', name='farewell') elif name == 'farewell': engine.endLoop() # Stop the loop after farewell engine.connect('finished-utterance', on_end) # Start with first utterance engine.say('Hello! Welcome to the system.', name='greeting') engine.startLoop() # Blocks until endLoop() is called print("Conversation complete!") ``` ### Response #### Success Response (200) N/A (These are method calls, not HTTP requests) #### Response Example N/A ``` -------------------------------- ### Engine.getProperty() Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Retrieves current engine configuration properties. ```APIDOC ## GET /engine/property ### Description Retrieves the current value of an engine property like rate, voice, or volume. ### Method GET ### Endpoint engine.getProperty(name) ### Parameters #### Query Parameters - **name** (string) - Required - The property name (e.g., 'rate', 'voice', 'volume'). ### Response #### Success Response (200) - **value** (object) - The current value of the requested property. ``` -------------------------------- ### DriverProxy Interface Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/drivers.md The `DriverProxy` interface provides methods for the driver delegate to interact with the `pyttsx3.Engine`, such as checking busy status and sending notifications. ```APIDOC ## class pyttsx3.driver.DriverProxy ### Description Provides methods for a driver delegate to communicate with the `pyttsx3.Engine`. ### Methods #### isBusy() -> bool - **Description**: Gets if the proxy is busy and cannot process the next command in the queue. - **Returns**: True if busy, False if idle. #### notify(topic: string, **kwargs) -> None - **Description**: Fires a notification. - **Parameters**: - **topic** (string) - Required - The name of the notification. - **Kwargs**: - Name/value pairs associated with the topic. ``` -------------------------------- ### Check Speaking Status with engine.isBusy() in pyttsx3 Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Shows how to use the `isBusy()` method to check if the pyttsx3 engine is currently speaking. This is useful for polling in external event loops to know when speech has completed before proceeding. ```python import pyttsx3 import time engine = pyttsx3.init() engine.say("This is a long sentence that takes time to speak.", name='test') engine.startLoop(useDriverLoop=False) while engine.isBusy(): print("Still speaking...") engine.iterate() time.sleep(0.1) print("Finished speaking!") engine.endLoop() ``` -------------------------------- ### List Available Voices Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Retrieves and lists all available speech synthesis voices on the system, along with their attributes. ```APIDOC ## engine.getProperty('voices') - List Available Voices ### Description Retrieves a list of Voice objects representing all available speech synthesis voices on the system. Each Voice has id, name, languages, gender, and age attributes. ### Method `engine.getProperty('voices')` ### Endpoint N/A (This is a method call within the library) ### Parameters None ### Request Example ```python import pyttsx3 engine = pyttsx3.init() # Get all available voices voices = engine.getProperty('voices') # List all voices with details print(f"Found {len(voices)} voices:\n") for i, voice in enumerate(voices): print(f"[{i}] ID: {voice.id}") print(f" Name: {voice.name}") print(f" Languages: {voice.languages}") print(f" Gender: {voice.gender}") print(f" Age: {voice.age}") print() ``` ### Response - **voices** (list of Voice objects) - A list where each Voice object contains: - **id** (string) - The unique identifier for the voice. - **name** (string) - The display name of the voice. - **languages** (list of strings) - A list of language codes supported by the voice. - **gender** (string) - The gender associated with the voice (e.g., 'male', 'female'). - **age** (string or None) - The age associated with the voice, if available. ``` -------------------------------- ### Stop Current Speech Synthesis Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Shows how to immediately halt speech synthesis and clear the queue using the stop method, often used with background threads. ```python import pyttsx3 import threading import time engine = pyttsx3.init() def stop_after_delay(): time.sleep(2) # Wait 2 seconds print("Stopping speech...") engine.stop() # Start stop timer in background threading.Thread(target=stop_after_delay).start() # Queue a long text engine.say("This is a very long sentence that will be interrupted " * 10) engine.runAndWait() print("Speech was stopped or completed.") ``` -------------------------------- ### External Event Loop Integration Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Integrates pyttsx3 with external event loops, such as those in GUI applications or async frameworks, by manually iterating the engine. ```APIDOC ## External Event Loop Integration ### Description For GUI applications or async frameworks, use `startLoop(useDriverLoop=False)` with manual iteration (`engine.iterate()`) to integrate with external event loops. This allows the pyttsx3 event processing to run within your application's existing event loop. ### Method `startLoop(useDriverLoop=False)` `iterate()` `endLoop()` ### Endpoint N/A (Method calls on engine object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pyttsx3 import time engine = pyttsx3.init() def on_end(name, completed): print(f"Finished: {name}") if name == 'last': engine.endLoop() engine.connect('finished-utterance', on_end) # Queue multiple utterances engine.say('First utterance.', name='first') engine.say('Second utterance.', name='second') engine.say('Last utterance.', name='last') # Start without driver loop engine.startLoop(useDriverLoop=False) # Simulate external event loop # In real app, integrate engine.iterate() into your framework's event loop while True: try: engine.iterate() # Process TTS events time.sleep(0.01) # Small delay except RuntimeError: break # Loop ended print("External loop complete!") ``` ### Response #### Success Response (200) N/A (This is a method call, not an HTTP request) #### Response Example N/A ``` -------------------------------- ### Disconnect Callbacks Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Demonstrates how to disconnect previously registered callbacks to prevent memory leaks or unwanted behavior. ```APIDOC ## Disconnect Callbacks ### Description Disconnect callbacks when no longer needed to manage resources effectively. ### Method `disconnect()` ### Endpoint N/A (Method call on engine object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'token_start', 'token_word', 'token_end', 'token_error' are valid callback tokens engine.disconnect(token_start) engine.disconnect(token_word) engine.disconnect(token_end) engine.disconnect(token_error) ``` ### Response #### Success Response (200) N/A (This is a method call, not an HTTP request) #### Response Example N/A ``` -------------------------------- ### Disconnect Callbacks in pyttsx3 Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Demonstrates how to disconnect previously registered callbacks to prevent memory leaks or unwanted behavior when they are no longer needed. This is crucial for managing the lifecycle of event listeners. ```python engine.disconnect(token_start) engine.disconnect(token_word) engine.disconnect(token_end) engine.disconnect(token_error) ``` -------------------------------- ### Interrupt Utterance with stop() Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Shows how to interrupt the current speech output. A callback function monitors word locations and calls `engine.stop()` when a specific condition (word location > 10) is met, halting speech and clearing the queue. ```python import pyttsx3 def onWord(name, location, length): print('word', name, location, length) if location > 10: engine.stop() engine = pyttsx3.init() engine.connect('started-word', onWord) engine.say('The quick brown fox jumped over the lazy dog.', 'fox') engine.runAndWait() ``` -------------------------------- ### Common Properties Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Properties that can be set or retrieved for the speech engine. ```APIDOC ## Common Properties ### rate #### Description Integer speech rate in words per minute. ### voice #### Description String identifier of the active voice. Use the `id` from the `Voice` object. ### volume #### Description Floating point volume in the range of 0.0 to 1.0 inclusive. ``` -------------------------------- ### Modify Speech Rate Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Retrieves the current speech rate using `getProperty('rate')`, increases it by 50 words per minute, and then sets the new rate using `setProperty('rate', ...)`. Finally, it speaks a sentence with the adjusted rate. ```python engine = pyttsx3.init() rate = engine.getProperty('rate') engine.setProperty('rate', rate+50) engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait() ``` -------------------------------- ### Voice Class - Voice Metadata Source: https://context7.com/nateshmbhat/pyttsx3/llms.txt Provides access to metadata for available speech synthesis voices, including ID, name, language, gender, and age. ```APIDOC ## Voice Class - Voice Metadata ### Description The `Voice` class contains metadata about available speech synthesis voices. This includes their unique identifier (`id`), human-readable name (`name`), supported languages (`languages`), gender (`gender`), and age (`age`). ### Method `getProperty('voices')` ### Endpoint N/A (Method call on engine object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pyttsx3 engine = pyttsx3.init() voices = engine.getProperty('voices') # Accessing attributes of a voice object voice = voices[0] # Assuming at least one voice is available print(f"ID: {voice.id}") # Unique identifier for setProperty print(f"Name: {voice.name}") # Human-readable name print(f"Languages: {voice.languages}") # List of language codes print(f"Gender: {voice.gender}") # 'male', 'female', 'neutral', or None print(f"Age: {voice.age}") # Age in years or None # Example of finding voices by criteria def find_voices(voices, language=None, gender=None): results = [] for voice in voices: if language and language not in str(voice.languages): continue if gender and voice.gender != gender: continue results.append(voice) return results # Find English female voices english_female = find_voices(voices, language='en', gender='female') for v in english_female: print(f"Found: {v.name}") ``` ### Response #### Success Response (200) - **voices** (list of `Voice` objects) - A list containing metadata for each available voice. - **id** (string) - Unique identifier for the voice. - **name** (string) - Human-readable name of the voice. - **languages** (list of strings) - List of language codes supported by the voice. - **gender** (string or None) - Gender of the voice ('male', 'female', 'neutral'). - **age** (integer or None) - Approximate age of the voice. #### Response Example ```json [ { "id": "HKEY_LOCAL_MACHINE\...", "name": "Microsoft Zira Desktop - English (United States)", "languages": ["en-US"], "gender": "female", "age": null } ] ``` ``` -------------------------------- ### Voice Metadata Source: https://github.com/nateshmbhat/pyttsx3/blob/master/docs/engine.md Information about available speech synthesizer voices. ```APIDOC ## Voice Metadata ### class pyttsx3.voice.Voice Contains information about a speech synthesizer voice. #### Properties * **id** (string) - Required - String identifier of the voice. Used to set the active voice via `pyttsx3.engine.Engine.setPropertyValue()`. * **name** (string) - Optional - Human readable name of the voice. * **languages** (List[string]) - Optional - List of string languages supported by this voice. * **gender** (string) - Optional - String gender of the voice: male, female, or neutral. * **age** (integer) - Optional - Integer age of the voice in years. ```