zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python之pyttsx3库实现语音播报

Python 实现 语音 播报
2023-09-11 14:22:10 时间

import pyttsx3
 
def Word_VR(word, speed=50):
    engine = pyttsx3.init()
    # 设置新的语音音量, 音量最小为 0, 最大为 1
    engine.setProperty('volume', 1)
    voices = engine.getProperty('voices')
    # 改变语速  范围为0-200   默认值为200
    rate = engine.getProperty('rate')
    engine.setProperty('rate', rate+ speed)
    #voices[0]是男声,voices[1]是女生
    engine.setProperty('voice', voices[0].id)
    # engine.setProperty("voice", "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_ZH - CN_HUIHUI_11.0")
    engine.say(word)
    engine.runAndWait()
 
if __name__=='__main__':
    Word_VR("你好,World", 60)

备注:
1.需要插入音箱或者耳机
2.第一个参数是需要播报的文字,第二个参数是语速
3.切换男声女声没有起作用,欢迎大家留言指导


API说明:
engine = pyttsx3.init()

pytttsx初始化配置,固定写法,没啥好解释的。
engine.say(参数1)

参数1:text,输入要说的字符串
engine.runAndWait()

pytttsx发出语音,并在发出语音时阻塞程序,固定写法,没啥好解释的。
基本例程
import pyttsx3
# text参数是需要转成音频的文字
def textChangeVoice(text):
    engine = pyttsx3.init()#pytttsx初始化配置
    engine.say(text)#把文本存入
    engine.runAndWait()#发出语音,并在发出语音时阻塞程序

完整例程

import pyttsx3

# text参数是需要转成音频的文字
def textChangeVoice(text):
    engine = pyttsx3.init()#pytttsx初始化配置
    engine.say(text)#把文本存入
    engine.runAndWait()#发出语音,并在发出语音时阻塞程序

textChangeVoice("很高兴认识爱学习的你,如果你觉得程序好用,收藏点赞可好?")
text=input("输入要转化成语音的文本:")
textChangeVoice(text)