%% 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/

%%%%%%%%% set up the graphics
sf = 44100; % set the sampling frequency
n0 = 2^13;  % number of points to be sampled on each run
T = 2*n0/sf;  % length of time interval for one data set
     % factor of 2 is magic to me, might be stereo/mono difference
freq = [0:n0-1]/T; % set of all frequencies
n = find(freq>2000)(1); % choose only frequencies smaller than 2.0 kHz

fftFigure = figure(1);  % initialize graphics window
clf
% set the axis for the graphics with all properties, e.g. scaling
fftAxes = axes('parent',fftFigure,'xlimmode','manual','ylimmode','manual',...
               'xscale','linear','yscale','linear',...
               'xlim',[0 (n-1)/T],'ylim',[-80 0]);
% initialize the data, at first with zero values
fftLine = line('XData',[0:(n-1)]/T,'YData',zeros(1,n));
xlabel('frequency [Hz]'); ylabel('amplitude [db]'); % label the axis
drawnow(); % draw the graphics window

while length(kbhit(1))<1  % loop for the measurement, stop by hitting a key
   s = arecord(n0,2,sf,'hw:0,0');     % record the sound through the sound card
   spec = abs(fft(s(:,1)))/(2*n0);    % compute the spectrum
   set(fftLine,'YData',20*log10(spec(1:n)));  % write the data to the window
   drawnow();                         % update the display
end%while
