PyGame has huge delay with playing sounds

旧街凉风 提交于 2020-01-01 11:35:30

问题


I am playing around with building a python script that play rhythms like a drum machine. I have used PyGame to handle the audio. However I experience significant/unacceptable delays between calling play and hearing the actual audio.

I pasted the following code into the interactive interpreter, and then execute the last line again and again:

import pygame
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
s = pygame.mixer.Sound('snare.wav')
s.play(loops=0, maxtime=0, fade_ms=0)

The time between pressing enter and hearing the audio is by my best guess around 400ms, and indeed noticeable and unacceptable. The delay is approximately the same as if I click the play button in VLC and wait for the audio to play.

I have tried this on both Windows and Ubuntu with the same result. My computer is a bit old, an Intel Core i3, 2.53GHz, but I think this should not be a problem.

What can I do about this?

In a loop:

This code demonstrates the same lag.

for i in range(10):
  print i
  s.play(loops=0, maxtime=0, fade_ms=0)
  sleep(2)

回答1:


A possible solution is to decrease the buffer size (example 512):

import pygame
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=512)
s = pygame.mixer.Sound('snare.wav')
s.play(loops=0, maxtime=0, fade_ms=0)



回答2:


I had the same problem a couple of minutes ago, and there's a solution that works for me in This other thread

It looks like an initialization problem, pygame doesn't get the buffers well if you init pygame first (or else XD). Initialize the mixer init() and pre_init() first, and experiment from there:

pygame.mixer.pre_init(44100, -16, 2, 512)
pygame.mixer.init()
pygame.init()

That should work :) Good luck!



来源:https://stackoverflow.com/questions/13356752/pygame-has-huge-delay-with-playing-sounds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!