# Play sound at key press

**URL:** <https://discourse.psychopy.org/t/play-sound-at-key-press/3206>\
**Category:** Builder\
**Tags:** sound\
**Created:** [October 9, 2017, 12:03pm UTC](https://discourse.psychopy.org/t/play-sound-at-key-press/3206 "2017-10-09T12:03:37Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![js94](https://avatars.discourse-cdn.com/v4/letter/j/f14d63/32.png) [@js94](https://discourse.psychopy.org/u/js94)\
**Post date:** [October 9, 2017, 12:03pm UTC](https://discourse.psychopy.org/t/play-sound-at-key-press/3206/1 "2017-10-09T12:03:37Z")

</div>

Hey all  
I’m quite new to Psychopy and trying to do the following in my experiment:

It’s a dot motion task with 2 enabled response keys (left and right) where I want  
**- sound A played when the LEFT key is pressed**  
**- and a randomly chosen sound A, B, C or D played when the RIGHT key is pressed**

(the sounds are unrelated to whether the key response is correct)

Currently, I’ve implemented this in Psychopy builder with a code component which looks like this:

- **at the begin of my routine** :

a\_sound = sound.Sound(u’A’, secs=0.5)  
b\_sound = sound.Sound(u’B’, secs=0.5)  
c\_sound = sound.Sound(u’C’, secs=0.5)  
d\_sound = sound.Sound(u’D’, secs=0.5)

- **and at each frame** I’ve got this:

response = event.getKeys(keyList=[‘left’,‘right’])

if ‘left’ in response:  
a\_sound.play()  
elif ‘right’ in response:  
random([a\_sound.play(), b\_sound.play(), c\_sound.play, d\_sound.play()])

Two problems emerge when I try to run this:

- the left key sound only occurs after a double left key press instead of just one
- the randomiser function does not seem to work at all (experiment shuts down after right key press)

Any suggestions of what I’m doing wrong / or how to implement the same thing in another way? Really any help would be much appreciated!

---

<div class="post-metadata">

**Author:** ![kuppuslp](https://avatars.discourse-cdn.com/v4/letter/k/ecb155/32.png) [@kuppuslp](https://discourse.psychopy.org/u/kuppuslp)\
**Post date:** [October 14, 2017, 9:44am UTC](https://discourse.psychopy.org/t/play-sound-at-key-press/3206/2 "2017-10-14T09:44:44Z")

</div>

Not an expert. Just wondering, if you import numpy as np at your begin routine?

---

<div class="post-metadata">

**Author:** ![kuppuslp](https://avatars.discourse-cdn.com/v4/letter/k/ecb155/32.png) [@kuppuslp](https://discourse.psychopy.org/u/kuppuslp)\
**Post date:** [October 14, 2017, 9:49am UTC](https://discourse.psychopy.org/t/play-sound-at-key-press/3206/3 "2017-10-14T09:49:20Z")

</div>

If that indeed was the problem, you should also use ‘np.random.choice(RandList)’, where ‘RandList’ is a list of sounds that you want to be played randomly.
