python pyttsx3库将文本(text)转换为语音

利用python中的一些库,可以实现文本转音频的功能。这时候,电脑将作为一个AI语音播报助手,直接将输入的文字内容读给你听。

这里举一个简单的例子。

1、 首先安装一个pyttsx3库。

pip install pyttsx3

2、 导入需要的库

import pyttsx3 as pts

pt = pts.init() # 初始化

pt.say("Hello. Nice to meet you.") # 设置语音"Hello. Nice to meet you."

pt.runAndWait() #使电脑读出语音

如果电脑扬声器正常打开的话,就能听到语音了。

3、使用.setProperty()函数设置语音参数,.getProperty()获取参数值。

定义一个函数,根据目前的时间发出不同的问候语。

import pyttsx3

import datetime

engine=pyttsx3.init('sapi5')

voices=engine.getProperty('voices')

rate= engine.getProperty('rate')

volume= engine.getProperty('volume')

engine.setProperty('voice',voices[1].id) #voices[0]表示男声,voices[1]表示女声。

engine.setProperty('rate',100) #rate设置语速,默认值200。

engine.setProperty('volume',0.5) # volume设置音量比例,取值在0到1之间。

def speak(text):

engine.say(text)

    engine.runAndWait()

def wishMe():

    hour=datetime.datetime.now().hour

    if hour>=0 and hour<12:

      speak("Hello,Good Morning")

      print("Hello,Good Morning")

    elif hour>=12 and hour<18:

      speak("Hello,Good Afternoon")

      print("Hello,Good Afternoon")

    else:

      speak("Hello,Good Evening")

      print("Hello,Good Evening")

注意在".say"后面加上".runAndWait()"。

执行函数:wishMe()

图片

4、 保存语音

def save_file(text,filename):

engine.save_to_file(text, filename)

    engine.runAndWait()

hour=datetime.datetime.now().hour

save_file("The current time is {} o'clock".format(hour),'{}.wav'.format(hour))

1700:04
读者可根据需要,结合其他工具来实现更多的功能,比如让电脑自动读一首诗,自动进行天气预报等等。
THE END