%% code by Andreas Stahel, Bern University of Applied Sciences
%% loosely based on the code spectrum_analyser.m from playrec
%% see http://www.playrec.co.uk/

%%%%%%% choose the parameters for the measurements
sf = 44100;         % sampling frequency
n0 = 2^12;          % number of points to be sampled on each run
T = 2*n0/sf;        % length of time interval for data recording
     % factor of 2 is magic to me, might be stereo/mono difference
freq = [0:n0-1]/T;  % the examined frequencies
n = find(freq>2000)(1); % display only op to 2.0 kHz

%%%%%%%%% set up the graphics
fftFigure = figure(1);
clf
fftAxes = axes('parent',fftFigure,'xlimmode','manual','ylimmode','manual',...
               'xscale','linear','yscale','linear',...
               'xlim',[0 (n-1)/T],'ylim',[0 0.05]);
fftLine = line('XData',[0:(n-1)]/T,'YData',zeros(1,n));
xlabel('frequency [Hz]'); ylabel('amplitude')
drawnow

disp('stop by hitting a key')

while length(kbhit(1))<1  % loop for the measurement, stop by hitting a key
  s = arecord(n0,2,sf,'hw:0,0');
  spec = abs(fft(s(:,1)))/(2*n0);
  set(fftLine,'YData',spec(1:n));
  drawnow();
endwhile

