0

I am trying to make a sound play continuously if a certain time has passed. Below is my code. However, the sound keeps replaying instead of one continuous sound as it is in a while loop. Putting it outside the while loop will not work as the time is incremented inside the while loop. How do I go about doing this? Please help! I have been stuck at this for 2 days..... This is an issue with my ordering of my coding, so its nothing to do with the sound being played correctly or not.

Thanks!

t = 0;

pahandle = PsychPortAudio('Open', [], 1, 1, 48000, 2);

myBeep = MakeBeep(500, 0.5, 48000);

PsychPortAudio('RunMode', pahandle, 1);
PsychPortAudio('FillBuffer', pahandle, [myBeep; myBeep]);

while t < 20
    t = t + 1;

    if ~KbCheck && t >= 5 
        PsychPortAudio('Start', pahandle, 0, 0, 1);

    elseif KbCheck
        PsychPortAudio('Stop', pahandle, 1, 1);
        break
    elseif  t > 20
        PsychPortAudio('Stop', pahandle, 1, 1);
        break
    end
end

PsychPortAudio('Close', pahandle);
TYL
  • 1,577
  • 20
  • 33

1 Answers1

0

I found the answer to my own question and it is really quite simple. Just add a new variable to control if the sound is currently playing or not. I did it by adding IsPlaying to all the if statements.

t = 0;
IsPlaying = 0;

pahandle = PsychPortAudio('Open', [], 1, 1, 48000, 2);

myBeep = MakeBeep(500, 0.5, 48000);

PsychPortAudio('RunMode', pahandle, 1);
PsychPortAudio('FillBuffer', pahandle, [myBeep; myBeep]);

while t < 20
t = t + 1;

if ~KbCheck && t >= 5 && IsPlaying == 0
    PsychPortAudio('Start', pahandle, 0, 0, 1);
    IsPlaying = 1;

elseif KbCheck
    PsychPortAudio('Stop', pahandle, 1, 1);
    IsPlaying = 0;
    break
elseif  t > 20
    PsychPortAudio('Stop', pahandle, 1, 1);
    IsPlaying = 0;  
    break
end
end

PsychPortAudio('Close', pahandle);
TYL
  • 1,577
  • 20
  • 33