Play sound for as long key is pressed (and stop at release)

Win10 - PsychoPy-2022.2.3

I was wondering if there is a way to play a sound for as long a key is pressed, so with the sound starting when the key gets pressed down and stopping when it is released.
There is no problem with repeating the sound as it would be a long beep sound.
The goal is to have the participant listen to a morse sequence with long and short beeps and to have them reproduce it on the space bar, and I wanted to help them by giving sound feedback.

Thanks in advance.

Hi @L_Ota,

I don’t know if this is the most elegant solution, but it works. You need the ptb sound backend for this (see audio settings).

Begin routine

sound1 = sound.Sound("A", secs = 10)

from psychopy.hardware import keyboard
from psychopy import core

kb = keyboard.Keyboard()

Each frame

keysDown = event.getKeys()
keysUp = kb.getKeys()

if "space" in keysDown:
if "space" in keysUp:

Hey @ajus
Thanks for the input!
However, I now get an error message when trying to start the experiment. I cannot even enter the participant number before it crashes.
That is the exact error message I get:
I did change to ptb in Properties > Audio > Audio Library, and in the code replaced “A” by the path of my sound.
Do you have an idea of what may be happening?
Thanks again for your time.

No, not really, since there is no real error message. Could you try inserting the code into a new and empty experiment just to see if the crash has anything to do with your actual experiment or if it is your machine that maybe can’t handle ptb?

I get this message when inserting the code in a new experiment;


I don’t know what exactly is needed to run ptb but my computer should be able to run it.

Are you sure this is an empty experiment? Can you run this?
morse.psyexp (7.9 KB)

Ok, your file works just fine, yet I am sure my experiment was empty.
I think I’ll be able to figure it out tho, thanks a lot for your time!

edit: ok so apparently, my other sounds were stereo, but mono is needed with ptb. Even when I converted them to mono, it did not work because “force stereo” was checked in the audio settings. I unchecked it and it works now.
Thanks again for your help