clear all

recording = 'wav';
% recording = 'mic';
% recording = 'synth';

switch recording
	case 'wav'
		% leggi il file
% 		file = 'mic.wav';
% 		file = 'SanMartino.wav';
		[s,fs] = wavread(file);
		s = s / max(abs(s(:)));
		
	case 'mic'
		% registra
		Trec = 7;
		fs = 44100;
		bits = 16;
		channels = 2;
		recObj = audiorecorder(fs,bits,channels);
		fprintf('Press ENTER when ready... (will record %d seconds)',Trec);
		pause
		fprintf('\n[start]');
		record(recObj);
		for i = 1:Trec
			fprintf(' %d...',i);
			pause(1)
		end
		fprintf(' [stop]\n');
		
		% Store data in double-precision array.
		s = getaudiodata(recObj);
		wavwrite(s,fs,bits,'mic.wav');
		
	case 'synth'
		
		fs = 44100;
		T = 4;
		N = T*fs;
		Ts = 1/fs;
		t = (0:N-1).'*Ts;
		fp = 440;
		phi0 = 2*pi*rand;
		fm = 20;
		Am = 1;
		kf = 0;
		if kf
			fprintf('df_max=%g\n',3*fm+kf*Am);
		end
		Ap = 0.5;
		s = Ap*cos(2*pi*fp*t+phi0+Am*kf/fm*sin(2*pi*fm*t));
end
Ts = 1/fs;
[N,n_canali] = size(s);
N = min(N,15*fs); % 15 secondi al massimo
t = (0:N-1)*Ts;

% parametro dell'analisi tempo-frequenza
W = 8192;
w = kaiser(W,4);
t_win = (0:W-1)*Ts;
Sp_win_avg = 0;

% h1 = figure(1);clf;
h2 = figure(2);clf;

% play in tempo reale
player = audioplayer(s,fs);
play(player,[1,N]);tic

delay = 0.2;
while (toc - delay) * fs < N
	k = floor((toc - delay)*fs - W);
	
	% finestra k-esima
	if k+W < 0
		s_win = zeros(W,1);
	elseif k < 0
		s_win = [zeros(-k,1);s(1:W+k,1)];
	else
		s_win = s(k+(1:W),1);
	end
	
% 	set(0,'CurrentFigure',h1)
% 	plot(t_win,s_win)
% 	xlabel('t [s]')
% 	ylabel('s(t)')
% 	ylim([-1 1])
	
	S_win = fft(s_win.*w)*Ts;
	f_win = (-W/2:W/2-1)/(W*Ts);
	Sp_win = S_win(1:W/2);
	fp_win = (0:W/2-1)/(W*Ts);

	set(0,'CurrentFigure',h2)
	plot(fp_win*1e-3,20*log10(abs(Sp_win)))
	xlabel('f [kHz]')
	ylabel('|S| [dB]')
	ylim([-110 -30])
	xlim([0 4])

	drawnow
end

stop(player);
