# Is it possible to generate sound stimuli with dynamically modulated volume in psychopy?

Hello world
This is my first time trying to write an audio task. I want to create a pure tone stimulus with constantly changing amplitude which follows a sine wave pattern, and the max amplitude need to be varied in each trial. below is my attempt to generate the sound in the way I used to create visual stimuli. I imagine this to be a smooth sound but it sounds very glitchy. Iām not sure, if this type of stimulus can be generated in psychopy. Do I need to use another software to create the sound file and then load into psychopy? or is there a better way to create this in psychopy? Thanks!

``````import math
from math import pi
from psychopy import prefs
prefs.hardware['audioLib'] = ['PTB']
from psychopy import core, sound

frame_per_cycle=12 #how many brief sound components constitute one sinewave cycle
stim_duration=0.2 #stimulus duration for each interval in secs
frame_step=2*pi/frame_per_cycle
max_amplitude=0.5
for x2 in range(frame_per_cycle*2): #2 sinewave cycles per interval
vol=max_amplitude*math.sin(x2*frame_step)/2+1
tock = sound.Sound('500', secs=stim_duration/frame_per_cycle, volume=vol)
tock.play()
core.wait(stim_duration/frame_per_cycle)
``````

Hey! You should be able to generate this for sure

In builder add a sound component
Start the āvolumeā field with a \$ indicating that you will use python code
Enter the equation for a sine wave using the internal variable t as time.
Set to update every frame

Our learning materials have a demo where a visual stimulus changes size every frame using a sine wave. The principles are the same go to workshops.psychopy.org, download the examples.zip then itās builder>dynamic>heart throb

Hope this helps!
Becca

Hi Becca, thank you for your help.
Iāve input ā\$(0.5sin(t)/2+1)" in the volume box and selected āset every frameā but got the error message saying that t is not defined. Do you have any idea why is this happening?
" sound_1.setVolume((0.5
sin(t)/2+1), log=False)
NameError: name ātā is not definedā

Oh that is curious! t is usually a global variable in PsychoPy, so letās check that out.

Can you please export your builder exp to coder and search ātā (to check if it is there, not to make edits to the script)

Alternatively, each routine you create in builder usually has its own clock (e.g. MyRoutineClock for a routine called āMy Routineā, you can search all the clocks PsychoPy has going on in your exported code by searching ācore.Clockā). To get the current time you can substitute t for MyRoutineClock.getTime() to get the current time on each frame.

Let us know how you get on

Becca