% Pat O'Keefe
% Project 1
% Part 2

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

freq = 350; % frequency of the source

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));

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

% turn into final sound and normalize
x = envelope.*cos(2*pi*f.*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 2']);xlabel('Time (sec)');ylabel('Velocity');

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

figure(3)
plot(t,f);grid on;
title('Apparent Frequency of Source - Part 2');xlabel('Time (sec)');ylabel('Frequency (Hz)');

sound(x,Fs);