Using a Button Press to Stop Audio

Hello,
I’m having an issue with my audio in Coder. I have two separate .wav files (1.5 sec durations each) and I would like to be able to stop one audio file and the other start when I press a button. Unfortunately the sounds seem to overlap with each other and don’t stop on the dime. I’ve noticed in the help file that there is a stop command you can use, but I can’t figure out how to incorporate it. Any suggestions as to how I can approach this issue? My code is below:

from __future__ import division
from psychopy import prefs
prefs.general['audioLib'] = ['pyo']
from psychopy import locale_setup, visual, core, event, data, gui, sound
import numpy as np
import pandas as pd
import sys, os, csv, time, random, unicodedata, platform
import subprocess as subp
import shlex

cwd = os.path.dirname(os.path.abspath(__file__))
  
win = visual.Window(fullscr=True, pos=(0,0), units="norm", color="Black")
event.Mouse(visible=False)

Timer = core.Clock()

box = visual.Rect(win, fillColor="Red", lineColor="Red", size=(3.5, 3.5))
col_box = visual.Rect(win)


response=None
while Timer.getTime() < 10.0:
    event_press = event.getKeys(keyList=['left','right'])
    
    thesekeys= event.getKeys()
    if 'escape' in thesekeys:
        core.quit()
        
    box.setAutoDraw(True)
    
    if len(event_press):
        response= event_press[0]
    
    if response == 'left':
        col_box.fillColor, col_box.lineColor = ['Yellow','Yellow']
        col_box.size = (4.0,4.0)
        col_box.draw()
        sound.SoundPyo(value='sound1.wav').play()
    elif response == 'right':
        col_box.fillColor, col_box.lineColor = ['Blue','Blue']
        col_box.size = (4.0,4.0)
        col_box.draw()
        sound.SoundPyo(value='sound2.wav').play()
    else:
        pass

    win.flip()
    
box.setAutoDraw(False)
#Finished:
win.close()
core.quit()

Hi, I’m not able to test run the code at the moment, but you’re almost there so hopefully this will send you in the right direction.

It becomes easier to understand if you treat each occurrence of sound.SoundPyo() as a distinct object, as you’ve done with the col_box = visual.Rect(win)
Then you can access the methods listed in the API

mySound1 = sound.SoundPyo(value='sound1.wav') Can be declared in advance outside the loop

mySound1.play()
mySound1.stop() Can both be called as necessary

Of course, you’ll also need to do this for a mySound2 as well

The setAutoDraw(True) method could also be moved before the while loop, as it doesn’t need to be used on each iteration.