Text-to-Speech App Project (code) in Python

← Back to Projects

Text-to-Speech App in Python.

About the project: Creating a Python project for a Text-to-Speech (TTS) App.

This Python script is a complete, interactive app. When you run it, you can enter any text, and the program will speak it out loud.

The app will continue to run until you type q to quit.

This app will take text input from you and convert it into spoken words.

To do this, it will use a third-party library, pyttsx3, which works with text-to-speech engines on your system.

To use this program, you will need to install the pyttsx3 library. You can do this by running the following command in your terminal or command prompt:


   
   pip install pyttsx3
   
   

Project Level: Beginner

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# text_to_speech_app.py

import pyttsx3

def initialize_engine():
    """
    Initializes the pyttsx3 engine.
    Returns the engine instance.
    """
    try:
        engine = pyttsx3.init()
        return engine
    except Exception as e:
        print(f"Error initializing TTS engine: {e}")
        return None

def main():
    """
    Main function to run the Text-to-Speech App.
    """
    engine = initialize_engine()
    if not engine:
        print("Text-to-Speech functionality is not available.")
        print("Please ensure you have a TTS engine installed on your system.")
        return

    print("--- Python Text-to-Speech App ---")
    print("Enter the text you want to hear (or 'q' to quit).")

    while True:
        text_to_speak = input("\nEnter text: ").strip()

        if text_to_speak.lower() == 'q':
            print("Exiting Text-to-Speech App. Goodbye!")
            break
        
        if not text_to_speak:
            print("Please enter some text.")
            continue
        
        # Say the text
        engine.say(text_to_speak)
        # Block while the app is speaking
        engine.runAndWait()

    # Clean up the engine after the loop
    engine.stop()

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()