% Pat O'Keefe
% Project 1
% Part 3

close all;
clear all;

% define sampling rate and set up a time vector
Fs = 8000;
TotalTime = 4;
t = -TotalTime/2+1/Fs:1/Fs:TotalTime/2;

c = 345; %speed of sound

offset = 15; % distance of observer from source trajectory

% set up a major triad
freq = 300;
freq2 = freq*5/4;
freq3 = freq*3/2;

vSource = 15; % velocity of the source

distance = vSource*t; % horizontal position of source, NOT w.r.t. observer

newDistance = sqrt(offset.^2 + distance.^2); % horizontal position w.r.t. observer

envelope = 1.0./newDistance; % envelope of the sound. No need to limit this time.

% calculate the velocity of the source w.r.t the observer
theta = asin(offset./newDistance);
newVSource = vSource*cos(theta);

% initialize vector
f = zeros(1,length(t));
f2 = f;
f3 = f;

% apply doppler effect
for i = 1:length(t)
    if t(i)<=0
        f(i) = freq*c/(c-newVSource(i));
        f2(i) = freq2*c/(c-newVSource(i));
        f3(i) = freq3*c/(c-newVSource(i));
    else
        f(i) = freq*c/(c+newVSource(i));
        f2(i) = freq2*c/(c+newVSource(i));
        f3(i) = freq3*c/(c+newVSource(i));
    end
end

% turn into final sound and normalize
x = envelope.*(cos(2*pi*f.*t) + cos(2*pi*f2.*t) + cos(2*pi*f3.*t));
x = x/max(abs(x));

figure(1)
plot(t,newVSource); grid on;
title(['Velocity of Source Relative to Observer with Offset ',num2str(offset),' - Part 3']);xlabel('Time (sec)');ylabel('Velocity');

figure(2)
plot(t,envelope);grid on;
title(['Signal Envelope with Offset ', num2str(offset),' - Part 3']);xlabel('Time (sec)');ylabel('Amplitude');

figure(3)
plot(t,f,'b');grid on;hold on;
plot(t,f2,'r');
plot(t,f3,'k');
legend([num2str(freq),' Hz'],[num2str(freq2),' Hz'],[num2str(freq3),' Hz']);
title('Apparent Frequency of Source - Part 3');xlabel('Time (sec)');ylabel('Frequency (Hz)');

sound(x,Fs);