我做了一個按鈕類,檢查是否選擇了一個按鈕(當鼠標懸停在按鈕上)。當按鈕被選中時,取消選中或點擊它播放一個wav文件。問題在於聲音播放和按鈕狀態改變之間存在巨大的延遲。程序應該檢查每一幀,看看是否符合聲音播放的條件,但fps似乎不是問題(60和600 fps給出相同的延遲)。我已經嘗試減少pygame.mixer.init()
中的緩衝區值,但這也顯示沒有區別。pygame - 聲音延遲
聲音文件:
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()
所以我的問題是: 爲什麼會出現長時間的延遲,我可以把它縮短?
我仍然有聲滯後。 – Guney
我也是,儘管它從0.4下降到0.3秒。仍然想知道爲什麼**延遲發生。 – Lewistrick