Skip to content

Latest commit

 

History

History
72 lines (53 loc) · 2.9 KB

File metadata and controls

72 lines (53 loc) · 2.9 KB

七十四、文本到语音转换器

原文:http://inventwithpython.com/bigbookpython/project74.html

这个程序演示了第三方模块pyttsx3的使用。您输入的任何消息都会被操作系统的文本到语音转换功能大声朗读出来。虽然计算机生成的语音是计算机科学的一个极其复杂的分支,但pyttsx3模块为它提供了一个简单的接口,使这个小程序适合初学者。一旦你学会了如何使用这个模块,你就可以把生成的语音添加到你自己的程序中。

关于pyttsx3模块的更多信息可以在pypi.org/project/pyttsx3找到。

运行示例

当您运行texttospeechtalker.py时,输出如下:

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>`
> quit
Thanks for playing!

工作原理

这个程序很短,因为pyttsx3模块处理所有的文本到语音代码。要使用该模块,请按照本书介绍中的说明进行安装。一旦你这样做了,你的 Python 脚本可以用import pyttsx3导入它并调用pyttsc3.init()函数。这将返回一个代表文本到语音转换引擎的Engine对象。这个对象有一个say()方法,当您运行runAndWait()方法时,您可以将一个文本字符串传递给它,以便计算机朗读。

"""Text To Speech Talker, by Al Sweigart email@protected
An example program using the text-to-speech features of the pyttsx3
module.
View this code at https://nostarch.com/big-book-small-python-projects
Tags: tiny, beginner"""

import sys

try:
    import pyttsx3
except ImportError:
    print('The pyttsx3 module needs to be installed to run this')
    print('program. On Windows, open a Command Prompt and run:')
    print('pip install pyttsx3')
    print('On macOS and Linux, open a Terminal and run:')
    print('pip3 install pyttsx3')
    sys.exit()

tts = pyttsx3.init()  # Initialize the TTS engine.

print('Text To Speech Talker, by Al Sweigart email@protected')
print('Text-to-speech using the pyttsx3 module, which in turn uses')
print('the NSSpeechSynthesizer (on macOS), SAPI5 (on Windows), or')
print('eSpeak (on Linux) speech engines.')
print()
print('Enter the text to speak, or QUIT to quit.')
while True:
    text = input('> ')

    if text.upper() == 'QUIT':
        print('Thanks for playing!')
        sys.exit()

    tts.say(text)  # Add some text for the TTS engine to say.
    tts.runAndWait()  # Make the TTS engine say it. 

探索程序

这是一个基础程序,所以没有太多的选项来定制它。相反,考虑一下你的其他程序会从文本到语音转换中受益。