Python中的文本到语音转换语音
在Python中有几个 API 可用于将文本转换为语音。一种这样的 API 是Python文本到语音 API,通常称为pyttsx3
API。 pyttsx3
是一个非常易于使用的工具,可以将输入的文本转换为音频。
安装
要安装pyttsx3
API,请打开终端并编写
pip install pyttsx3
这个库依赖于win32,我们在执行程序时可能会出错。为了避免这种情况,只需在您的环境中安装pypiwin32
。
pip install pypiwin32
pyttsx3 中可用的一些重要功能是:
- pyttsx3.init([driverName : 字符串, debug : bool]) – 获取对将使用给定驱动程序的引擎实例的引用。如果请求的驱动程序已被另一个引擎实例使用,则返回该引擎。否则,将创建一个新引擎。
- getProperty(name : 字符串) – 获取引擎属性的当前值。
- setProperty(name, value) – 将命令排入队列以设置引擎属性。新属性值会影响在此命令之后排队的所有话语。
- say(text : unicode, name : 字符串) – 将命令排入队列以说出话语。根据队列中此命令之前设置的属性输出语音。
- runAndWait() – 在处理所有当前排队的命令时阻塞。适当地调用引擎通知的回调。在此调用之前排队的所有命令从队列中清空时返回。
现在我们都准备好编写一个将文本转换为语音的示例程序。
# Python program to show
# how to convert text to speech
import pyttsx3
# Initialize the converter
converter = pyttsx3.init()
# Set properties before adding
# Things to say
# Sets speed percent
# Can be more than 100
converter.setProperty('rate', 150)
# Set volume 0-1
converter.setProperty('volume', 0.7)
# Queue the entered text
# There will be a pause between
# each one like a pause in
# a sentence
converter.say("Hello GeeksforGeeks")
converter.say("I'm also a geek")
# Empties the say() queue
# Program will not continue
# until all speech is done talking
converter.runAndWait()
输出:
The output of the above program will be a voice saying, “Hello GeeksforGeeks” and “I’m also a geek”.
改变声音
假设您想将生成的声音从男性变为女性。你怎么做?让我们看看。
您会注意到,当您运行上述代码以实现文本到语音的转换时,响应的声音是男性声音。要更改语音,您可以通过从引擎获取voices
属性来获取可用语音列表,您可以根据系统中可用的语音更改语音。
要获取声音列表,请编写以下代码。
voices = converter.getProperty('voices')
for voice in voices:
# to get the info. about various voices in our PC
print("Voice:")
print("ID: %s" %voice.id)
print("Name: %s" %voice.name)
print("Age: %s" %voice.age)
print("Gender: %s" %voice.gender)
print("Languages Known: %s" %voice.languages)
输出:
要更改语音,请使用setProperty()
方法设置语音。上面找到的 Voice Id 用于设置语音。
下面是变声的实现。
voice_id = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0"
# Use female voice
converter.setProperty('voice', voice_id)
converter.runAndWait()
现在,您可以根据需要在声音之间切换。您可以尝试运行 for 循环以将不同的语句分配给不同的声音。运行代码并享受结果。