% Sample Matlab script to implement a rough STFT scheme to evaluate
% spectral magnitude peak variation over the course of a sound.
%
% by Gary Scavone, McGill University, 2025.

[x, fs] = audioread('Violin.C4.aif');
N = max(size(x));  % duration of sound in samples
M = 2048;          % size of FFT window
H = M;             % # of samples to hop in sound for each new FFT
f = fs*(0:M-1)/M;
maxFreq = 5000;
heightThreshold = 10;

nStart = 1;
while nStart + M < N
  X = 20*log10(abs(fft(x(nStart:nStart+M-1))));
  plot(f, X);
  xlim([0 maxFreq]);
  xlabel('Frequency (Hz)')
  ylabel('Magntitude (dB)')
  disp('Paused ... hit key to continue');
  [pks, fidx] = findpeaks(X, "NPeaks", 10, "MinPeakHeight", heightThreshold)
  hold on
  scatter( fs*fidx/M, pks );
  hold off
  pause
  nStart = nStart + H;
end