依赖库
pip install pyttsx3
示例代码
import pyttsx3
def speak(text, voice_type='male', language="cn"):
# 初始化了 TTS 引擎
engine = pyttsx3.init()
# 获取当前系统中所有可用的声音
voices = engine.getProperty('voices')
# 选择声音
if voice_type == 'female':
engine.setProperty('voice', voices[1].id)
else:
engine.setProperty('voice', voices[0].id)
# 播放中文(需要带CN的语音包)
if language == "cn":
for vType in voices:
# print(vType)
if "TTS_MS_ZH-CN" in vType.id:
engine.setProperty('voice', vType.id)
print("setup cn-voices")
break
# 设置语速(可选)
rate = engine.getProperty('rate')
engine.setProperty('rate', rate - 50) # 适当调整语速
# 朗读文本
engine.say(text)
engine.runAndWait()
# 示例使用
text_to_speak = "这几天心里颇不宁静。今晚在院子里坐着乘凉,忽然想起日日走过的荷塘,在这满月的光里,总该另有一番样子吧。月亮渐渐地升高了," \
"墙外马路上孩子们的欢笑,已经听不见了;妻在屋里拍着闰儿,迷迷糊糊地哼着眠歌。我悄悄地披了大衫,带上门出去。"
text_to_speak = "In 1989 an 8.2 earthquake almost flattened America, killing over 30,000 people in less than " \
"four minutes. In the midst of utter devastation and chaos, a father left his wife safely at home and " \
"rushed to the school where his son was supposed to be, only to discover that the building was as flat as a pancake."
# print("len=",len(text_to_speak))
# for i in range(len(text_to_speak)):
# print(text_to_speak[i])
speak(text_to_speak, voice_type='female', language="en")