目录
一、pyttsx3 概述
代码会说话:pyttsx3是Python中的文本到语音转换库。
二、pyttsx3的安装
pip install pyttsx
image-20220429155835751
三、pyttsx3的运用
导入pyttsx3库后,调用speak函数即可进行语音播放。
import pyttsx3
#语音播放 
pyttsx3.speak("How are you?")
pyttsx3.speak("I am fine, thank you")
是不是很简单呢?
如果我们想要修改速度、音量、语音合成器等,我们可以使用以下方法。
[En]
If we want to modify the speed, volume, speech synthesizer, etc., we can use the following methods.
1、pyttsx3通过初始化来获取语音引擎,在调用init后会返回一个engine对象。
import pyttsx3
engine = pyttsx3.init() #初始化语音引擎
2、查看语速、音量等参数
rate = engine.getProperty('rate')
print(f'语速:{rate}')
volume = engine.getProperty('volume')   
print (f'音量:{volume}') 
运行结果为:
语速:200
音量:1.0
3、设置语速、音量等参数
engine.setProperty('rate', 100)   #设置语速
engine.setProperty('volume',0.6)  #设置音量
4、查看语音合成器
voices = engine.getProperty('voices') 
for voice in voices:
    print(voice) 
运行结果如下:
<voice id=hkey_local_machine\software\microsoft\speech\voices\tokens\tts_ms_zh-cn_huihui_11.0 name="Microsoft Huihui Desktop - Chinese (Simplified)" languages="[]" gender="None" age="None">
<voice id=hkey_local_machine\software\microsoft\speech\voices\tokens\tts_ms_en-us_zira_11.0 name="Microsoft Zira Desktop - English (United States)" languages="[]" gender="None" age="None">
</voice id=hkey_local_machine\software\microsoft\speech\voices\tokens\tts_ms_en-us_zira_11.0></voice id=hkey_local_machine\software\microsoft\speech\voices\tokens\tts_ms_zh-cn_huihui_11.0>
合成器的主要参数如下:
age
发音人的年龄,默认为Nonegender
以字符串为类型的发音人性别: male, female, or neutral.默认为Noneid
关于Voice的字符串确认信息languages
发音支持的语言列表,默认为一个空的列表name
发音人名称,默认为None
有两个默认的语音合成器,都可以合成英文音频,但只有第一个合成器可以合成中文音频。如果你需要其他语音合成器,你需要自己下载和设置。
[En]
There are two default speech synthesizers, both of which can synthesize English audio, but only the first synthesizer can synthesize Chinese audio. If you need other speech synthesizers, you need to download and set up them yourself.
5、设置语音合成器
如果我们需要第一个语音合成器,代码如下:
[En]
If we need the first speech synthesizer, the code is as follows:
voices = engine.getProperty('voices') 
engine.setProperty('voice',voices[0].id)   #设置第一个语音合成器
6、语音播报
engine.say("春光灿烂猪八戒")
engine.runAndWait()
engine.stop()
四、全套代码
import pyttsx3
engine = pyttsx3.init() #初始化语音引擎
engine.setProperty('rate', 100)   #设置语速
engine.setProperty('volume',0.6)  #设置音量
voices = engine.getProperty('voices') 
engine.setProperty('voice',voices[0].id)   #设置第一个语音合成器
engine.say("春光灿烂猪八戒")
engine.runAndWait()
engine.stop()
Original: https://blog.csdn.net/mfsdmlove/article/details/124500805
Author: Python for Finance
Title: 代码会说话——pyttsx3简介
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/526976/
转载文章受原作者版权保护。转载请注明原作者出处!