一、安装库
pip install pyttsx3
二、实现功能
1.导入模块
import pyttsx3
2.进行初始化及设置。
engine = pyttsx3.init()
# (Windows系统)voice='HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_ZH-CN_HUIHUI_11.0'
engine.setProperty('voice', voice)
# 设置语速与音量
engine.setProperty('rate', 150)
engine.setProperty('volume', 0.8)
voice 的值可通过如下代码打印查看(添加其它语音包可去电脑设置中自行下载)
engine = pyttsx3.init()
voices = engine.getProperty('voices')
for v in voices:
print(f'{v}')
3.保存到本地
# filename:文件名(带扩展名,比如test.mp3)
path = '../../music/' + filename
# text:待转文本 path:保存路径
engine.save_to_file(text, path)
三、最终结果
完整代码:
import pyttsx3
def text_to_sound(text, filename, voice):
"""
文字转语音,可保存
"""
engine = pyttsx3.init()
engine.setProperty('voice', voice)
# 设置语速与音量
engine.setProperty('rate', 150)
engine.setProperty('volume', 0.8)
# 播放
engine.say(text)
if filename.strip() != '' and filename is not None:
# 保存
path = '../../music/' + filename
engine.save_to_file(text, path)
engine.runAndWait()
if __name__ == '__main__':
# text = input("请输入文字:")
text = '你好啊,朋友。'
tw_text = '哎哟,不错哦!'
# 粤语语音
e_v_id = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_ZH-HK_TRACY_11.0'
# 台湾语音
tw_v_id = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_ZH-TW_HANHAN_11.0'
# 普通话
v_id = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_ZH-CN_HUIHUI_11.0'
text_to_sound(text, ' ', e_v_id)
语音展示…