% Time-frequency analysis
% Kefu Xue, Ph.D, Apr. 2000
%
c=262;
d=294;
e=330;
lg=392/2;
fs=1000;
T=1/fs;
N=500;
%cT=131/500; dT=147/500; eT=165/500 and lgT=98/500 are all rational. 
n=0:499;
t=n*T;
%Sampling the signal such that each note has 500 samples(half of a second),
x=[cos(c*2*pi*t) zeros(1,500) cos(c*2*pi*t) zeros(1,500) cos(d*2*pi*t) ...
      zeros(1,500) cos(e*2*pi*t) zeros(1,500) cos(c*2*pi*t) zeros(1,500) ...
      cos(e*2*pi*t) zeros(1,500) cos(d*2*pi*t) zeros(1,500) cos(lg*2*pi*t)];
%playing the sound
sound(x,1000,16);
%spectrum of the signal;
Xtotal=fft(x);
Ntotal=length(x);
fr=fs/Ntotal;
k=0:Ntotal-1;
f=k*fr;
%specgram
% window size 500, fs=1000Hz, window function none, overlap samples 0
[spg,ff,tt]=specgram(x,500,1000,ones(500,1),0);
figure;specgram(x,500,1000,ones(500,1),0);%plot
%Present results
sxx=abs(spg);
figure;
subplot(4,2,1);
stem(f(1:Ntotal/2+1), abs(Xtotal(1:Ntotal/2+1))); 
title('DFS representation of the music');
subplot(4,2,2);stem(ff,sxx(:,1));title('DFS of first note');
subplot(4,2,3);stem(ff,sxx(:,5));title('DFS of third note');
subplot(4,2,4);stem(ff,sxx(:,7));title('DFS of forth note');
subplot(4,2,5);stem(ff,sxx(:,9));title('DFS of fifth note')
subplot(4,2,6);stem(ff,sxx(:,11));title('DFS of sixth note');
subplot(4,2,7);stem(ff,sxx(:,15));title('DFS of eighth note');
subplot(4,2,8);stem(ff,sxx(:,2));title('DFS of spaces');
% use stem3 function to show the spectrogram
[X,Y]=meshgrid(tt,ff);
figure;stem3(X,Y,abs(spg));
title('Spectrogram of the music');