Jack H.
Jack H.

Reputation: 115

How can I detect keyboard input to play a sound with python?

I am making a program that will play a sound when you press a key (or just type) on the keyboard.

I just started to work on it, and I am trying to use pygame.key.get_pressed() to check for keyboard input. I got to here with the code:

from pygame import init, key

init()

spam = []

while True:
    spam = key.get_pressed()
    if True in spam:
        print('KEY PRESSED')
    elif False in spam:
        print('NONE')

It works by checking if a True value is in spam (spam is the name of the list pygame returns). key.get_pressed returns a list of True/False values for every key, True if pressed, False if not.

The problem with this code is that when I run it, it only outputs None. This means that I am not detecting the keyboard input.

If anyone knows how to fix this, or a better way to do it, I would greatly appreciate it!

Thanks!

Upvotes: 4

Views: 1070

Answers (1)

Rabbid76
Rabbid76

Reputation: 210996

pygame.key.get_pressed() gets the states of all keybord buttons. It returns a list.
But, note the values which are returned by pygame.key.get_pressed() are only updated when the key event is get events from the queue by pygame.event.get(). In simple words, pygame.key.get_pressed() only works, if there is an event loop, too.

You can evaluate a specific key (e.g. space key):

allKeys = pygame.key.get_pressed()
spam = allKeys[pygame.K_SPACE] 

If you want to evaluate if any key is pressed, then you've to evaluate if any() value in allKeys is True:

allKeys = pygame.key.get_pressed()
anyKey = any([k for k in allKeys if k == True])

Another solution would be to check if the KEYDOWN event occurred. The next pending event can be fetched by pygame.event.get():

keyPressed = False
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN: 
        keyPressed = True

Upvotes: 1

Related Questions