我做了一个按钮类,检查是否选中了一个按钮(当鼠标悬停在按钮上时).选择,未选中或单击按钮时,它将播放一个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]
Run Code Online (Sandbox Code Playgroud)
创建对象:
playButton = button(textInactive = "Play", font = mainFont, sounds = buttonSounds, command = playAction)
Run Code Online (Sandbox Code Playgroud)
来自按钮类的代码,用于检查是否选择了按钮(这是在.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
Run Code Online (Sandbox Code Playgroud)
来自按钮类的代码,用于检查是否单击了按钮(这是在.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()
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:为什么会有很长的延迟,我可以缩短它吗?
rlv*_*dan 11
我也有声音滞后的问题.我发现pygame.mixer.pre_init()之前的呼叫pygame.init()解决了我的问题:
pygame.mixer.pre_init(44100, -16, 1, 512)
pygame.init()
Run Code Online (Sandbox Code Playgroud)
Wil*_*lva 11
减小缓冲区的大小将减少延迟。缓冲区必须是 2 的幂。默认缓冲区是 4096,但您可以在初始化混合器时更改它,如下所示:
pygame.mixer.init(44100, -16, 2, 64)
Run Code Online (Sandbox Code Playgroud)
更多信息可以在pygame 文档中找到
Rat*_*ial 10
我知道这已经过时了,但我找到了迄今为止我见过的最佳解决方案.
实际上修复非常简单.我曾经一直延迟我的pygame项目,因为我会在初始化混音器之前初始化pygame.(这似乎总是你应该对我这样做的方式).
但是,如果在初始化pygame本身之前初始化混音器,它会消除所有延迟.这解决了我所有的延迟问题.希望能帮助到你.
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.mixer.init()
pygame.init()
Run Code Online (Sandbox Code Playgroud)