% Generate test tones for EE362 experiment
%
% Steven Backer
% Winter 2006

% remove old wave files
!rm -f *.wav

fs = 44100; % sampling rate
f0 = 1000;  % tone frequency

% frequencies for spacing
% 1/2 period = time tone is ON (duration)
f_test = 0.5;  % just for calibration/testing
f = [f_test 3.0:.2:5.6];
dur = 1./(2*f');
n = 0:dur*fs-1;

% create amplitude envelope with 5ms rise/fall times
rt = 0.005;
fade_length = ceil(rt*fs);
fade_n = 0:fade_length-1;

% generate a linear envelope
% Note: although are ears sensitivity is actually logarithmic, 
% a linear envelope is used here for simplicity.  It would be
% better to use an exponential envelope, but Recanzone points out
% in his article that onset of the tones has very little effect
% on the experiment.
attack = linspace(0,1,fade_length);
decay = linspace(1,0,fade_length);


% synthesize
for i = 1:15
    n = 0:dur(i)*fs-1;
    num_samp(i) = max(n)+1;

    % create the envelope
    sustain_length = floor(dur(i)*fs - 2*fade_length);
    env = [attack ones(1,sustain_length) decay];
    scalar = 0.9; % avoid clipping
    
    % tone
    tone = scalar*env.*sin(2*pi*f0/fs*n);
    
    % write to file
    wav_name = sprintf('tone_%0.3g.wav',f(i));
    wavwrite(tone, fs, 16, wav_name);
end

% fix name format to be more consistent
!mv tone_3.wav tone_3.0.wav
!mv tone_4.wav tone_4.0.wav
!mv tone_5.wav tone_5.0.wav

% directory listing after file is run
% $ ls *.wav
% tone_0.5.wav  tone_3.4.wav  tone_4.0.wav  tone_4.6.wav  tone_5.2.wav
% tone_3.0.wav  tone_3.6.wav  tone_4.2.wav  tone_4.8.wav  tone_5.4.wav
% tone_3.2.wav  tone_3.8.wav  tone_4.4.wav  tone_5.0.wav  tone_5.6.wav
