% Matlab commands for demonstrating Beat Notes and AM modulation

fs=11025*4;
tt=0:1/fs:2;
fm=440;
% Beat Notes
fd =5/2;
xx1 = cos(2*pi*(fm-fd)*tt);
xx2 = cos(2*pi*(fm+fd)*tt);
zz = xx1+xx2;
disp('Plotting beat notes signal with envelopes')
plot(tt,zz);
hold on
plot(tt,2*cos(2*pi*fd*tt),'r',tt,-2*cos(2*pi*fd*tt),'r')
title('Beat Notes, f_d=2.5Hz, f_m=440Hz');
hold off
disp('Playing beat notes...') 
sound(0.9*zz/max(abs(zz)),fs);


% AM
disp('Pausing before AM ...')
pause

ss = cos(2*pi*440*tt);
disp('Playing original signal (sinusoid of frequency 440Hz)...')
sound(0.9*ss,fs)
A=2;
fc=4500;

xx = (A+ss).*cos(2*pi*fc*tt);
plot(tt(1:10*round(fs/fm)),xx(1:10*round(fs/fm)),'b',...
    tt(1:10*round(fs/fm)),A+ss(1:10*round(fs/fm)),'r',...
    tt(1:10*round(fs/fm)),-A-ss(1:10*round(fs/fm)),'r')
title('AM of cos(2 \pi 440 t), f_c=2500Hz')
xlabel('Time (s)')

% Spectograms
disp('Pausing before spectogram of original signal ...')
pause
specgram(ss,1024,fs)
disp('Pausing before spectogram of AM signal ...')
pause
specgram(xx,1024,fs)
disp('Pausing before playing modulated signal')
pause
sound(0.9*xx/max(abs(xx)),fs)

% Demod
disp('Pausing before demod ...')
pause
specgram(xx.*cos(2*pi*fc*tt),1024,fs)
disp('Pausing before playing demodulated signal')
pause
sound(0.9/max(abs(xx))*xx.*cos(2*pi*fc*tt),fs)
% Lowpass Filter for removing double fc terms
b=remez(127,[0 1500 3500 fs]/fs,[1 1 0 0]);
yy = filter(b,1,xx.*cos(2*pi*fc*tt));
disp('Pausing before spectogram of filtered, demodulated signal ...')
pause
specgram(yy,1024,fs)
disp('Pausing before playing filtered, demodulated signal ...')
pause
sound(0.9*yy/max(abs(yy)),fs)
% does DC component need to be removed?

% Musical Scale
disp('A more interesting signal: musical scale')
pause
playscale % result is stored in vector xx
%whos 
sound(xx/max(abs(xx)),fs)
specgram(xx,512,fs)

disp('Pausing before specgram of modulated signal')
pause
%plot(xx(1:200))
tt = (0:length(xx)-1)/fs;
yy=(A+xx).*cos(2*pi*fc*tt);
%plot(tt,xx)
%plot(tt,yy)
specgram(yy,512,fs)
disp('Pausing before playing modulated signal')
sound(0.9*yy/max(abs(yy)),fs)

% demod
disp('Pausing before demod ...')
pause
zz=filter(b,1,yy.*cos(2*pi*fc*tt));
specgram(zz,1024,fs)
sound(0.9*zz/max(abs(zz)),fs)

% % non-coherent demod
% disp('Pausing before non-coherent demod ...')
% pause
% zz=filter(b,1,abs(yy));
% specgram(zz,1024,fs)
% sound(zz/max(abs(zz)),fs)

%which specgram
%which zcat
%--  4:48 PM 10/30/01 --%