Interrupting a Current Sound to Play Another?

Hi, everyone:

I have a task in which a 1-second long sound (stored in the folder as a .wav file) is to be played whenever the ‘z’ key is pressed. Code at the beginning assigns the file to the object ‘bang’ with:

 bang = sound.Sound("glock16.wav")

and then the sound is played with a code component (written under /each frame/):

 if key_resp_2.keys == 'z':
     bang.play()

where key_resp_2 is the name of the keyboard component.

This works just fine. However, if the z key is pressed again before the .wav file is finished, it does not interrupt the sound to start a new one over. Instead, it waits until the current sound is finished before playing the next one. What I would like is for the z key to initiate the sound being played whenever it is pressed, even if it means interrupting the current .wav file to play.

To be more concrete, if it helps: The .wav is the sound of a gun firing, and when z is pressed it means a person has pulled the trigger of a gun and so pulling the trigger plays the sound of the gun firing. But if I pull the trigger in rapid succession, the sound of the gun shouldn’t delay – it should sound immediately when the trigger is pulled, each time.

Is there a way to make this happen?

psychopy 1.84.2 with os 10.11.6. (I’m using builder but these issues concern the code component.)

Thank you!

What is key_resp_2? Is that a Builder-style keyboard component? You probably just want to directly test the keyboard on each frame, something like this:

if event.getKeys('z'):
    bang.stop() # just in case already playing
    bang.play()

Thanks for the suggestion, Michael.

However, that just makes the sound play repeatedly and nonstop in a loop.

In addition, if I try to store “all keys” instead of just “last key” or “first key” (both of which result in the rapid repeating of the sound), it doesn’t play at all.

Yes, key_resp_2 is a builder keyboard component.

Any suggestions?

Actually, it seems as though using the code:

if len(theseKeys) > 0:
     bang.play()

seems to work fine (unless I’m missing some unintended problem associated with doing this…)