Python文本转语音库pyttsx3
pyttsx3
pyttsx3是python中的文本到语音转换库,与其他库不同,它脱机工作,并且与Python2和3兼容。
安装pip
python -m ensurepip --default-pip
python -m ensurepip --upgrade
python -m pip install --upgrade pip
安装pyttsx3
pip install pyttsx3
提示:No module named win32com.client、No module named win32或No module named win32api之类的错误,则需要另外安装pypiwin32。
代码案例
案例1:
#导入pyttsx3库
import pyttsx3
# 初始化
engine = pyttsx3.init()
# 朗读
engine.say("中华人民共和国~")
engine.runAndWait()
案例2(保存语音到本地):
import pyttsx3
# 初始化
engine = pyttsx3.init() # object creation
""" RATE(速度)"""
rate = engine.getProperty('rate') # getting details of current speaking rate
print("速度=>" + str(rate)) #printing current voice rate
engine.setProperty('rate', 125) # setting up new voice rate
"""VOLUME(音量)"""
volume = engine.getProperty('volume') #getting to know current volume level (min=0 and max=1)
print ("音量=>" + str(volume)) #printing current volume level
engine.setProperty('volume',1.0) # setting up volume level between 0 and 1
"""VOICE(声音)"""
voices = engine.getProperty('voices') #getting details of current voice
for voice in voices:
print ('id = {} \nname = {} \n'.format(voice.id, voice.name))
#engine.setProperty('voice', voices[0].id) #changing index, changes voices. o for male
#engine.setProperty('voice', voices[1].id) #changing index, changes voices. 1 for female
#engine.setProperty('voice', 'zh')
engine.say("中华人民共和国~")
engine.say('当前语速是' + str(rate))
engine.save_to_file('中华人民共和国,我的祖国,万岁、万岁、万万岁~', 'd://中华人民共和国.mp3')
# 朗读
engine.runAndWait()
engine.stop()
说明:
pyttsx.init([driverName : string, debug : bool]) → pyttsx.Engine
driverName:由pyttsx3.driver模块根据操作系统类型来调用,默认使用当前操作系统可以使用的最好的驱动,sapi5 - SAPI5 on Windows、nsss - NSSpeechSynthesizer on Mac OS X
、espeak - eSpeak on every other platform。
debug:这个参数是指定要不要以调试状态输出,建议开发阶段设置为True。
相关项目链接:
pypi(https://pypi.python.org)
github(https://github.com/nateshmbhat/pyttsx3)
完整文档(
https://pyttsx3.readthedocs.org)