Skip to content

Instantly share code, notes, and snippets.

@jahabrewer
Created May 17, 2018 01:04
Show Gist options
  • Save jahabrewer/8ca0b8f01b14ad0b14ba3db02a9e779f to your computer and use it in GitHub Desktop.
Save jahabrewer/8ca0b8f01b14ad0b14ba3db02a9e779f to your computer and use it in GitHub Desktop.
Loads an audio file and plots its waveform and FFT
## Adapted from https://www.mathworks.com/help/matlab/ref/fft.html
function retval = fftandplot (filename, tStart, tEnd)
Fs = audioinfo(filename).SampleRate;
X = audioread(filename);
# Convert to mono
X = X(:,1);
# Convert times to sample indexes
iStart = round(tStart*Fs);
iEnd = round(tEnd*Fs);
timeDomain = [max(iStart,1):iEnd];
L = length(timeDomain);
# TODO does the duration have to be even?
# Show original audio
figure;
plot(timeDomain, X(timeDomain))
title('Original audio signal')
xlabel('t (samples)')
ylabel('X(t)')
# Compute fft
Y = fft(X);
P2 = abs(Y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);
# Show fft
f = Fs*(0:(L/2))/L;
figure;
plot(f, P1)
title('DFT of audio')
xlabel('f (Hz)')
ylabel('amplitude?')
# Find max freq component
[xMax, iMax] = max(P1);
printf("Freq with highest amplitude is %d Hz\n", f(iMax))
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment