%voiceRT_steff.m
%MEASURING VOCAL REACTION TIME USING MICROPHONE ATTACHED TO COMPUTER'S SOUNDCARD.
%PRESENTS FIVE TRIALS, MEASURES VOCAL REACTION TIME AND PRESENTS RESULTS ON COMMAND LINE

clear all
threshold = 0.08; % whatever value works! (background inside MEG <0.05)
sampling_rate=8000; %can only be 8000 or 16000 I think (see Cogent manual for confirmation)
config_display (1, 1, [1 1 1], [0 0 0], 'Ariel', 50, 4, 0 );
config_sound(1,8,sampling_rate,1)
%%%config_sound(nchannels,nbits,sampling_rate,nbuffers)
start_cogent;

preparerecording(2000); %DURATION OF VOCAL RECORDING IN MILLISECONDS

%THIS SECTION JUST PRESENTS A SIMPLE VISUAL STIMULUS (ANYTHING COULD REPLACE THIS SECTION)
preparestring( '+', 2 ); %puts fixation cross in buffer 2
drawpict(2); %buffer 2 drawn to screen
preparestring( 'Say "gap!"', 3 ); %puts stimulus in buffer 3
wait( 1000 );
trials=5

for i = 1:trials
    t0(i)=drawpict (3); %draws buffer 3 and saves time at start of stimulus presentation
    recordsound; %swtiches on sound recording
    t20(i)=time-t0(i); %tests how long recordsound and drawpict opertations take (NB:longer time on first trial)
    waituntil(t0(i)+1000);
    t1(i)=drawpict( 2 ); %buffer 2 redrawn to screen
    waitrecord %waits until end of sounds recording so next trial down't overwrite this one.
    sounds{i}= getrecording; %one flexible way of storing sounds (don't need to keep each trial's data if you are confident you won't need to debug afterwards)
    soundarray(:,i)=getrecording; %another way of storing sounds (this requires each sounds vector to be exaclty the same length)
    maxsound(i)=max(abs(sounds{i})); %value of the loudest single sample of this trial's recording (loudness in arbitrary uncalibrated units from -1 to +1. -1 and +1 are equally loud and 0 is silence. Soundcard clips loader sounds than -1 or +1)
    disp(maxsound(i)) %writes maximum sound value
    %freq=8000;
    ix = find(abs(sounds{i}) > threshold); %find the index of all samples loader than the threshold value (to be used later to calculate vocal RT)

    if length(ix) %only do this if at least one sample is loader than threshold
        rt = ix(1) / sampling_rate * 1000;%time in milliseconds from start of sound file of the first sample louder than threshold
        logstring( ['Reaction time = ' num2str(rt)] ) %added to logfile and written to command line
    else
        logstring( ['Reaction time = NO SOUND FOUND'] ) %added to logfile and written to command line (IF NO SOUNDS LOUDER THAN THRESHOLD)
    end

end

stop_cogent

%CAN PLOT THE SOUND ARRAYS USING CODE BELOW. NOT USUALLY NEEDED/WANTED DURING EXPERIMENT:
for i=1:trials
figure(i) %opens Figure I window
plot(sounds{i}) %PLOTS Ith TRIAL'S RECORDED SOUND
end