%Homework 5 solution.  'Twinkle Twinkle Little Star'

%Set up some general timing parameters
dur = .3; %duration of short note (sec)
rampDur = 0.1; %duration of ramp (sec)
ITI = .05; %duration between notes (sec)
Fs = 44100; %sampling rate (Hz)
amp = .1;   %amplitude (volume)

%Set up a vector 'freq' that is a list of the 8 frequencies in the scale
C4Freq = 278.4375;  %Hz
curFreq = C4Freq;

%This vector has '1's for the 9 notes (of the 12) in the scale
scaleNotes = [1,0,1,0,1,1,0,1,0,1,0,1,1];

count = 1;
freq = zeros(1,8);
for i=1:13 %loop through all notes in the octave
    if scaleNotes(i)  %if this is in the scale, save the frequency
        freq(count) = curFreq;
        count = count+1;
    end
    curFreq = curFreq*2^(1/12); %increment the current frequency
end

%%  Play the song

%order of notes in each of the three phrases
phrase(1,:) = [1,1,5,5,6,6,5]; %twinkle twinkle little star
phrase(2,:) = [4,4,3,3,2,2,1]; %how I wonder what you are
phrase(3,:) = [5,5,4,4,3,3,2]; %up above the world so high

%durations of the notes in all phrases
durs=       dur*[1,1,1,1,1,1,2];

%order of phrases to play
twinkle = [1,2,3,3,1,2];


for i=1:length(twinkle);  %loop through the size phrases
    for j=1:size(phrase,2)  %loop through the notes in each phrase
        %generate the sound vector
        t = linspace(0,durs(j),durs(j)*Fs);

        %the frequency we want is freq(phrase(twinkle(i),j)).  Get it?
        
        y = amp*sin(2*pi*t*freq(phrase(twinkle(i),j)));

        %trapezoidal window
        trapezoid = zeros(size(t));

        %flat part
        trapezoid(t>= rampDur & t<= dur-rampDur) = 1;

        %rising part
        id = t<rampDur;
        trapezoid(id) = linspace(0,1,sum(id));

        %descending part
        id = t>dur-rampDur;
        trapezoid(id) = linspace(1,0,sum(id));

        y = y.*trapezoid;

        %play the sound.  
        sound(y,Fs);
        
        %Wait for the ITI
        tic
        while toc<ITI
        end
    end
end
