Tôi đã tạo một lớp nút để kiểm tra xem nút có được chọn hay không (khi chuột di chuột qua nút). Khi nút được chọn, không được chọn hoặc nhấp vào nút đó sẽ phát tệp wav. Vấn đề là có sự chậm trễ lớn giữa việc phát âm thanh và trạng thái của nút thay đổi. Chương trình nên kiểm tra mọi khung hình để xem liệu các điều kiện cho âm thanh để chơi đã được đáp ứng nhưng fps dường như không phải là vấn đề (60 và 600 khung hình/giây cho cùng một độ trễ). Tôi đã thử giảm giá trị bộ đệm trong pygame.mixer.init()
nhưng điều đó cũng cho thấy không có sự khác biệt.Pygame - Độ trễ âm thanh
file âm thanh:
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]
Tạo đối tượng:
playButton = button(textInactive = "Play", font = mainFont, sounds = buttonSounds, command = playAction)
Mã từ lớp nút để kiểm tra nếu nút được chọn (đây là bên trong phương pháp .display
được gọi là mỗi khung) :
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
Mã từ lớp nút kiểm tra xem nút được click (đây là bên trong phương pháp .clickEvent
được gọi khi nút chuột trái được nhấp):
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()
Vì vậy, câu hỏi của tôi là: Tại sao lại có một sự chậm trễ lâu và tôi có thể làm cho nó ngắn hơn?
Tôi vẫn nhận được độ trễ âm thanh. – Guney
Tôi cũng vậy, mặc dù nó giảm từ 0,4 đến 0,3 s. Vẫn tự hỏi ** tại sao ** sự chậm trễ xảy ra. – Lewistrick