Python | Text to Speech by using pyttsx3

Python | Text to Speech by using pyttsx3

pyttsx3 is a Python text-to-speech conversion library that works offline and is compatible with both Python 2 and Python 3. Unlike other libraries that rely on cloud services, pyttsx3 works directly with speech engines on your machine, like sapi5 on Windows, nsss on macOS, and espeak on Linux.

Here's a step-by-step guide on how to convert text to speech using pyttsx3:

  1. Installation:

    Install the library using pip:

    pip install pyttsx3
    
  2. Basic Usage:

    Here's a simple example to convert text to speech:

    import pyttsx3
    
    # Initialize the TTS engine
    engine = pyttsx3.init()
    
    # Set properties (optional)
    engine.setProperty('rate', 150)     # Speed of speech
    engine.setProperty('volume', 0.9)   # Volume level (from 0.0 to 1.0)
    
    # Convert text to speech
    engine.say("Hello, how are you?")
    engine.runAndWait()
    
  3. Changing Voices:

    The library allows you to switch between different voices if available on your system:

    import pyttsx3
    
    engine = pyttsx3.init()
    
    voices = engine.getProperty('voices')
    for index, voice in enumerate(voices):
        print(index, voice.id)
        engine.setProperty('voice', voice.id)
        engine.say("Hello, how are you?")
        engine.runAndWait()
    

    This code snippet will loop through all available voices on your system, and you will hear each voice say "Hello, how are you?". Adjust the voice by setting the voice property based on the voice's id.

  4. Handling Events:

    You can also handle various events like when speaking starts or finishes:

    import pyttsx3
    
    def onStart(name):
        print('Starting to speak...')
    
    def onWord(name, location, length):
        print('On word...')
    
    def onEnd(name, completed):
        print('Finished speaking!')
    
    engine = pyttsx3.init()
    engine.connect('started-utterance', onStart)
    engine.connect('started-word', onWord)
    engine.connect('finished-utterance', onEnd)
    
    engine.say("Hello, how are you?")
    engine.runAndWait()
    
  5. Saving Speech to an Audio File:

    If you'd like to save the converted speech to an audio file instead of playing it:

    import pyttsx3
    
    engine = pyttsx3.init()
    engine.save_to_file("Hello, how are you?", "output.mp3")
    engine.runAndWait()
    

With these basics, you can easily incorporate text-to-speech functionalities into your Python projects using pyttsx3.


More Tags

winreg group-policy command highlight android-appbarlayout controller temp-tables powershell-cmdlet operating-system hierarchy

More Programming Guides

Other Guides

More Programming Examples