前言
pyttsx3 是 Python 中的文本到语音转换库。与其他库不同,它可以离线工作,并且与 Python 2 和 3 兼容。
安装
pip install pyttsx3
备注 :pyttsx3安装需要win32库持,否则会报"No module named win32com.client"或者"No module named win32"或者"No module named win32api"等错误。这时你只需要在安装pyttsx3前,pip install pypiwind32这个库即可。
基本使用
import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()
或者
import pyttsx3
pyttsx3.speak("I will speak this text")
声音、速率和音量参数设置
import pyttsx3
#创建对象
engine = pyttsx3.init()
"""语速调节"""
#获取当前语速的详细信息
rate = engine.getProperty('rate')
#打印当前语速
print (rate)
#设置1.25倍语音速率
engine.setProperty('rate', 125)
"""音量调节"""
#获取音量大小
volume = engine.getProperty('volume')
print (volume)
#设置音量为最大声(参数为0-1之间的小数,0表示无声,1表示最大音量)
engine.setProperty('volume',1.0)
"""变声调节"""
#获取当前语音的详细信息
voices = engine.getProperty('voices')
#改变声音,0表示男声
#engine.setProperty('voice', voices[0].id)
#改变声音,1表示女声
engine.setProperty('voice', voices[1].id)
engine.say("Hello World!")
engine.say('My current speaking rate is ' + str(rate))
engine.runAndWait()
engine.stop()
"""保存语音文件"""
#注意:在linux系统中需要安装espeak和ffmpeg库才能保存语音文件
engine.save_to_file('Hello World', 'test.mp3')
engine.runAndWait()
朗读TXT文本文件内容
#读txt文档
with open(r"文档地址.txt","r",encoding="utf-8") as f:
engine.say(f.line())