psychopy.org | Reference | Downloads | Github

Play sound at key press without ending trial

Hi all,

I’m trying to play a sound at key press. The trial consists of displaying an image for 15s. I’m trying to get an audio file (screenshot sound effect) to play after a key press response (spacebar), and the response can happen anytime during this 15 seconds. But I also do not want to end trial until the 15 seconds of viewing the image is over. For example, if I were to hit the spacebar and trigger the screenshot sound effect in the middle of the 15 seconds, I still want the remaining image display time to continue.

I’m still very new to PsychoPy, and I’m not sure if I can do this just using builder, but am unaware of any code I could insert either.

If anyone can please provide some assistance, that would be greatly greatly appreciated!

Thank you,
Alice

Hi Alice,

Please find attached a minimal working example using text components. The routine presents one piece of text for 15 s. While it does so, it uses a code component to check for key presses on every frame. If it detects a key press, it uses the time of the key press as onset time for another piece of text which is then presented for 1 s. A limitation is that only one key press per trial is accepted, that is, in your experiment participants would hear the sound only once per trial (based on your description, I wasn’t entirely sure if this is what you wanted).

Jan

present_text_on_button_press.psyexp (8.3 KB)

This is perfect! Thank you so much for your help!

You’re welcome. I just realised that there is a potential issue though: If the response key is pressed very close to the end of the trial and the feedback is presented for a fixed amount of time, this would extend your trial beyond the intended 15 s. It depends on your design if this would be a problem or not. You could circumvent the problem by having the if part of the code component checking trialClock and making sure it evaluates to True only if there is sufficient time left to present the feedback.

Also, you probably want to add the time when the space key was pressed to your output file, i.e. add something along the lines of the code below to your code component:

trials.addData("spacePressed", timeToPresent)

Jan