我创建了一个按钮类来检查是否选择了按钮(当鼠标悬停在按钮上时)。当按钮被选中、取消选中或单击时,它会播放一个 wav 文件。问题是声音播放和按钮状态更改之间存在巨大延迟。程序应检查每一帧以查看是否满足播放声音的条件,但 fps 似乎不是问题(60 和 600 fps 给出相同的延迟)。我试过减少缓冲区的值,pygame.mixer.init()
但这也没有区别。
声音文件:
buttonSoundSelect = pygame.mixer.Sound(os.path.join(soundPath, "button1.wav"))
buttonSoundUnselect = pygame.mixer.Sound(os.path.join(soundPath, "button2.wav"))
buttonSoundClick = pygame.mixer.Sound(os.path.join(soundPath, "button3.wav"))
buttonSounds = [buttonSoundSelect, buttonSoundUnselect, buttonSoundClick]
创建对象:
playButton = button(textInactive = "Play", font = mainFont, sounds = buttonSounds, command = playAction)
按钮类中检查按钮是否被选中的代码(这是在.display
每帧调用的方法中):
if pygame.mouse.get_pos()[0] >= self.x and pygame.mouse.get_pos()[0] <= self.x + self.width and \
pygame.mouse.get_pos()[1] >= self.y and pygame.mouse.get_pos()[1] <= self.y + self.height:
self.surfaceActive.blit(self.textSurfaceActive, (self.width / 2 - self.font.size(self.textActive)[0] / 2,
self.height / 2 - self.font.size(self.textActive)[1] / 2))
self.surface.blit(self.surfaceActive, (self.x, self.y))
if self.selected == False:
if self.sounds != None:
self.sounds[0].stop()
self.sounds[1].stop()
self.sounds[2].stop()
self.sounds[0].play()
self.selected = True
else:
self.surfaceInactive.blit(self.textSurfaceInactive, (self.width / 2 - self.font.size(self.textInactive)[0] / 2,
self.height / 2 - self.font.size(self.textInactive)[1] / 2))
self.surface.blit(self.surfaceInactive, (self.x, self.y))
if self.selected == True:
if self.sounds != None:
self.sounds[0].stop()
self.sounds[1].stop()
self.sounds[2].stop()
self.sounds[1].play()
self.selected = False
来自按钮类的代码,用于检查按钮是否被单击(这是在.clickEvent
单击鼠标左键时调用的方法内部):
if self.command != None:
if pygame.mouse.get_pos()[0] >= self.x and pygame.mouse.get_pos()[0] <= self.x + self.width and \
pygame.mouse.get_pos()[1] >= self.y and pygame.mouse.get_pos()[1] <= self.y + self.height:
if self.sounds != None:
self.sounds[2].play()
self.command()
所以我的问题是:为什么会有很长的延迟,我可以缩短它吗?