Hi, I would like to ask is it possible for pygame to respond on a key press immediately? I am trying to make a drumming simulation and the response comes after 1-2 seconds. The code is:

import pygame, sys
from pygame import *

pygame.mixer.init()
pygame.init()

#Loading sounds...
snare = pygame.mixer.Sound('Snare.wav')
hihat = pygame.mixer.Sound('HiHat.wav')
kick = pygame.mixer.Sound('Kick.wav') 
crash = pygame.mixer.Sound('Crash.wav')
tom1 = pygame.mixer.Sound('HiTom.wav')
tom2 = pygame.mixer.Sound('LowTom.wav')
tomFloor = pygame.mixer.Sound('FloorTom.wav')
ride = pygame.mixer.Sound('Ride.wav')
hihatOpen = pygame.mixer.Sound('HiHatOpen.wav')

screen = pygame.display.set_mode((640,320), 0, 32)
pygame.display.set_caption('PyDrummer')
background = pygame.image.load('BG.jpg').convert()

while 1:
      for event in pygame.event.get():
            if event.type == QUIT:
                  pygame.quit()
                  sys.exit()
            if event.type == KEYDOWN:
                  if event.key == K_b:
                        kick.play()
#... and so on i check if a key is pressed, and if it is,  i play sound

#...
      screen.blit(background, (0,0))
      pygame.display.flip()

can anybode help me?

I tried your program with some of my own test files and experienced no delay.
What OS are you using?
How large are your sound files?

To speed things up rearrange the if statments and take things out of the eventloop that don't need to be there ...

import pygame as pg

pg.mixer.init()
pg.init()

# load sounds into memory for testing ...
one = pg.mixer.Sound('1.wav')
two = pg.mixer.Sound('2.wav')
three = pg.mixer.Sound('3.wav')

screen = pg.display.set_mode((640,320), 0, 32)
pg.display.set_caption('PyDrummer')
background = pg.image.load('circles.jpg').convert()
screen.blit(background, (0,0))
pg.display.flip()

while 1:
    for event in pg.event.get():
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_1:
                one.play()
            elif event.key == pg.K_2:
                two.play()
            elif event.key == pg.K_3:
                three.play()
        elif event.type == pg.QUIT:
            raise SystemExit

Edited 6 Years Ago by vegaseat: code

OK, thank you a lot. I'm currently using Windows XP with service pack 3,
and the sound'n'graphics together less than 1 MB.

even faster would be:

key = pygame.key.get_pressed()
event = pygame.event.poll()

# exit
if event.type == QUIT or key[K_ESCAPE]:
    pygame.quit(); sys.exit()

# left arrow
if key[K_LEFT]:
    # do something
    pass

even faster would be:

key = pygame.key.get_pressed()
event = pygame.event.poll()

# exit
if event.type == QUIT or key[K_ESCAPE]:
    pygame.quit(); sys.exit()

# left arrow
if key[K_LEFT]:
    # do something
    pass

Let's hope you tested out which approach is faster.

This article has been dead for over six months. Start a new discussion instead.