大家好
在“ 声音游戏:一个看不见的市场等待英雄”一文中 ,研究了具有酷炫环绕声的声音游戏以及其创建的库。
好吧,我决定从小处着手,对于初学者,在pygame的回合制游戏中组织合成器的动作评分。
当然,这种技术并不适用于所有游戏,但在某些情况下却非常适用。
创建语音模块。
我们将在其中组织两个工作选项:
- 通过其Controller dll连接到NVDA Narrator
- 通过SAPI5直接连接到Windows合成器;
首先,我们导入所有必需的模块。
要连接nvdaControllerClient32.dll,我们需要ctypes。
import ctypes
并且在计算机上没有NVDA的情况下,我们通过win32api直接与SAPI合成器一起工作。
import win32com.client
我们为我们的演讲创建一个班级。
class Speech: def __init__(self, config): """Initialize speech class.""" self.config = config
在这里您可能需要解释有关config的信息。 在负责初始化游戏所有模块并扭曲主循环的通用类Game中,正在加载游戏设置。
可以从更方便的位置加载设置:ini文件,json,sqlite或任何其他方便的选项。
但是,让我们继续初始化语音。
# COM . self.speaker = win32com.client.Dispatch("Sapi.SpVoice") # self.voices = self.speaker.GetVoices() # self.voices_names = [voice.GetDescription() for voice in self.voices]
使用设置中的某些参数配置连接的合成器。
在此示例中,我仅获取已安装语音的索引(默认索引为0),但是您可以通过按名称从下拉列表中进行选择来进行设置,如上所述。
语音速度设置为-10至+10。 但是我不认为有人会喜欢以低于5的速度收听声音。您可以通过更改设置中的值来进行实验。
当然还有声音的音量。 这是从0到100的标准值。
self.set_voice(self.config.voice) self.speaker.Rate = self.config.rate self.speaker.Volume = self.config.volume
最后,初始化nvda。
self.nvda = self.config.nvda self.nvda_error = False self.sLib = ctypes.windll.LoadLibrary('./nvdaControllerClient32.dll')
立即检查我们的程序是否可以连接到正在运行的NVDA程序。
nvda_error = self.sLib.nvdaController_testIfRunning() errorMessage = str(ctypes.WinError(nvda_error)) if 0 != nvda_error: print('NVDA error: ' + errorMessage) self.nvda_error = True
初始化SAPI合成器和nvda dll后,可以启动用于选择语音音频输出的功能。
self.set_speak_out()
添加功能以从索引可用列表中设置语音。
def set_voice(self, index): """Set voice for speak.""" try: self.speaker.Voice = self.voices[index] self.speak_sapi(self.voices_names[index]) except: print('error: do not set voice')
现在,该功能用于选择音频输出语音。 在这里,我们实际上选择了将用于工作的东西:nvda或直接合成器。
该选择包含两个参数:
- 设置中的标志是用户是否希望游戏使用NVDA。
- 连接到NVDA时可能出现的错误;
def set_speak_out(self): """Set speak out: nvda or sapi.""" if self.nvda and not self.nvda_error: self.speak = self.speak_nvda else: self.speak = self.speak_sapi
当然,我们将编写发音功能。
对于NVDA:
def speak_nvda(self, phrase): self.sLib.nvdaController_speakText(phrase)
这是直接向合成器发音的功能:
def speak_sapi(self, phrase): self.speaker.Speak(phrase)
仅此而已。 现在,在游戏逻辑中的任何位置,我们都将必要的信息发送到speech.speak()。
我希望本文对某人有用,并且会出现更多可用的游戏。