在本文中,您将学习如何让 Python 开口说话,我们将创建一个 Python 程序,将我们提供的任何文本转换为语音。 
怎么能让 Python 说话? Python 提供了数十万个第三方库,允许开发人员编写任何类型的程序,允许用很少的代码做复杂的事情。所以。我们可以使用第三方库方便的将文本转换为语音。 使用 PyTTSx3 将文本转换为语音在使用此模块之前,请记住使用 pip 安装它: pip install pyttsx3 如果你使用的是 Windows ,在安装 pyttsx3 前,还必须安装模块 pypiwin32。 pip install pypiwin32 只需要几行代码,就可以让 Python 开口说话。 import pyttsx3 # 初始化引擎 engine = pyttsx3.init() # 将文本转为语音 engine.say("如何让 Python 开口说话!") engine.runAndWait() engine.stop()
运行程序,你将听到来自计算机的声音。 可以多次调用say() 函数,也可以直接使用 speak() 函数:pyttsx3.speak("How are you?") 。 可以使用以下代码,查看计算机支持哪些语言。 import pyttsx3 engine = pyttsx3.init() 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>
还可以在调用 say() 函数之前修改语音的标准速率和音量。 import pyttsx3 # 初始化引擎 engine = pyttsx3.init() # 设置速率 rate = engine.getProperty('rate') engine.setProperty('rate', rate+50) # 设置音量 volume = engine.getProperty('volume') engine.setProperty('volume', volume+0.25) # 将文本转为语音 engine.say("如何让 Python 开口说话!") pyttsx3.speak("How are you?") engine.runAndWait() engine.stop()
还可以使用 save_to_file() 函数,将语音保存为 MP3 文件。 import pyttsx3 # 初始化引擎 engine = pyttsx3.init() # 设置速率 rate = engine.getProperty('rate') engine.setProperty('rate', rate+50) # 设置音量 volume = engine.getProperty('volume') engine.setProperty('volume', volume+0.25) # 将文本转为语音 str1 = "如何让 Python 开口说话!" engine.say("如何让 Python 开口说话!") engine.save_to_file(str1, 'say.mp3') engine.runAndWait() engine.stop()
还可以读取文本文件的内容并转换为 MP3 文件。 import pyttsx3 # 初始化引擎 engine = pyttsx3.init() # 设置速率 rate = engine.getProperty('rate') engine.setProperty('rate', rate+50) # 设置音量 volume = engine.getProperty('volume') engine.setProperty('volume', volume+0.25) # 将文本转为语音 with open("1.txt", "r") as f: #打开文本 str1 = f.read() #读取文本 engine.save_to_file(str1, 'say.mp3') engine.runAndWait() engine.stop()
至此,我们了解了如何使用 Python 模块 PyTTSx3 将文本转换为语音,从创建的程序中可以看出,使用 PyTTSx3 模块非常灵活方便。除了 PyTTSx3 外,还有很多其他模块也能实现文本转语音的功能,比如 PyTTSx4、gTTS 等。
|