原github网址:https://github.com/nateshmbhat/pyttsx3
安装
pip install pyttsx3
如果您遇到安装错误,请确保首先使用以下命令升级您的 Wheel 版本:
pip install --upgrade wheel
Linux 安装要求:
如果您使用的是 linux 系统并且语音输出不起作用,那么:
安装 espeak 、 ffmpeg 和 libespeak1 如下图所示:
sudo apt update && sudo apt install espeak ffmpeg libespeak1
朗读文本示例:
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()
将语音保存到文件
import pyttsx3
engine = pyttsx3.init()
engine.save_to_file('Hello World' , 'test.mp3')
engine.runAndWait()
监听事件
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.')
engine.runAndWait()
打断话语
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.')
engine.runAndWait()
改变声音
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()
改变语速
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()
改变音量
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()
运行驱动程序事件循环
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()
使用外部事件循环
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()
打印好玩的
import cowsay
print(dir(cowsay))
cowsay.dragon('┗|`O′|┛ 嗷~~')