This program demonstrates the use of the pyttsx3 third-party module. Any message you enter will be spoken out loud by your operating system’s text-to-speech capabilities. Although computer-generated speech is an incredibly complex branch of computer science, the pyttsx3 module provides an easy interface for it, making this small program suitable for beginners. Once you’ve learned how to use the module, you can add generated speech to your own programs.
When you run texttospeechtalker.py, the output will look like this:
Text To Speech Talker, by Al Sweigart [email protected]
Text-to-speech using the pyttsx3 module, which in turn uses
the NSSpeechSynthesizer (on macOS), SAPI5 (on Windows), or
eSpeak (on Linux) speech engines.
Enter the text to speak, or QUIT to quit.
> Hello. My name is Guido van Robot.<computer speaks text out loud>
Thanks for playing!
How It Works
This program is short because the pyttsx3 module handles all of the text-to-speech code. To use this module, install it by following the instructions in this book’s introduction. Once you’ve done so, your Python script can import it with import pyttsx3 and call the pyttsc3.init() function. This returns an Engine object that represents the text-to-speech engine. This object has a say() method to which you can pass a string of text for the computer to speak when you run the runAndWait() method.
1. """Text To Speech Talker, by Al Sweigart [email protected] 2. An example program using the text-to-speech features of the pyttsx3 3. module. 4. View this code at https://nostarch.com/big-book-small-python-projects 5. Tags: tiny, beginner""" 6. 7. importsys 8. 9. try:10. importpyttsx311. exceptImportError:12. print('The pyttsx3 module needs to be installed to run this')13. print('program. On Windows, open a Command Prompt and run:')14. print('pip install pyttsx3')15. print('On macOS and Linux, open a Terminal and run:')16. print('pip3 install pyttsx3')17. sys.exit()18. 19. tts=pyttsx3.init()# Initialize the TTS engine.20. 21. print('Text To Speech Talker, by Al Sweigart [email protected]')22. print('Text-to-speech using the pyttsx3 module, which in turn uses')23. print('the NSSpeechSynthesizer (on macOS), SAPI5 (on Windows), or')24. print('eSpeak (on Linux) speech engines.')25. print()26. print('Enter the text to speak, or QUIT to quit.')27. whileTrue:28. text=input('> ')29. 30. iftext.upper()=='QUIT':31. print('Thanks for playing!')32. sys.exit()33. 34. tts.say(text)# Add some text for the TTS engine to say.35. tts.runAndWait()# Make the TTS engine say it.
Exploring the Program
This is a base program, so there aren’t many options to customize it. Instead, consider what other programs of yours would benefit from text-to-speech.