Search code examples
eventskeypsychopy

Play sound if space is not pressed in Psychopy


I am trying to get a sound to play if 'Space' is not pressed AND if time is >1s, and to stop it if 'Space' is pressed

alarm = sound.Sound(700, secs = 5)

if (len(event.getKeys())==0) & (time1.getTime() > 1):
    alarm.play()
elif event.getKeys(keyList = 'space'):
    alarm.stop()

However, when I do this, I cannot press 'space' to stop the alarm. Can anyone tell me what I am doing wrong here? Is there any thing wrong with the '(len(event.getKeys())==0)' portion?

In Matlab, I can just write

if ~KbCheck && .....

but I am not sure how to do it in Psychopy.

Thanks!


Solution

  • Use event.getKeys(keyList=['space']). The keyList is a list, not a string. Also, change the order of your logic since the first call to event.getKeys() clears the keyboard buffer for all keys, since no keyList was provided so that nothing is left to be registered in your elif.

    So this should do the trick:

    if event.getKeys(keyList = ['space']):
        alarm.stop()
    elif time1.getTime() > 1 and not event.getKeys():  # if another key was pressed... #added brackets here 
        alarm.play()
    

    As you can see, I also simplified the syntax for one of the tests.