% 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

earDistance = .17; % distance between ears

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

% horizontal position w.r.t. observer for both "ears"
newDistance1 = sqrt(offset.^2 + (distance-earDistance/2).^2);
newDistance2 = sqrt(offset.^2 + (distance+earDistance/2).^2);

% envelope of the sound for both "ears"
envelope1 = 1.0./newDistance1;
envelope2 = 1.0./newDistance2;

% calculate the velocity of the source w.r.t the observer for both "ears"
theta1 = asin(offset./newDistance1);
theta2 = asin(offset./newDistance2);
newVSource1 = vSource*cos(theta1);
newVSource2 = vSource*cos(theta2);

% initialize vectors for both "ears"
f = zeros(1,length(t));
f2 = f;

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

% turn into final sound and normalize
x(:,1) = envelope1.*cos(2*pi*f.*t);
x(:,2) = envelope2.*cos(2*pi*f2.*t);

x(:,1) = x(:,1)./max(x(:,1));
x(:,2) = x(:,2)./max(x(:,2));


figure(1)
plot(t,newVSource1); grid on; hold on;
plot(t,newVSource2,'r');
legend('Observer 1','Observer 2');
title(['Velocity of Source Relative to Observer with Offset ',num2str(offset),' - Part 4b']);xlabel('Time (sec)');ylabel('Velocity');

figure(2)
plot(t,envelope1);grid on; hold on;
plot(t,envelope2,'r');
legend('Observer 1','Observer 2');
title(['Signal Envelope with Offset ', num2str(offset),' - Part 4b']);xlabel('Time (sec)');ylabel('Amplitude');

figure(3)
plot(t,f);grid on;hold on;
plot(t,f2,'r');
legend('Observer 1','Observer 2');
title('Apparent Frequency of Source - Part 4b');xlabel('Time (sec)');ylabel('Frequency (Hz)');

sound(x,Fs);