MATLAB: Looping all audio files through a FFT and saving the figure


I am able to run a FFT and save the figure each time manually. However, to save time I would like to just specify the folder that contains all the wav files and for the program to just go through each audio file and save the resulting figure automatically in a loop.
The FFT code is complete:
File= 'C:\Users\qkvm83\OneDrive - Durham University\Fieldwork\Haltwhistle_31_01_19\River_audio\Transect\Z24.wav'
[x,fs] = audioread(File);
lpad = 2*length(x);
xdft = fft(x,lpad);
xdft = xdft(1:lpad/2+1);
xdft = xdft/length(x);
xdft(2:end-1) = 2*xdft(2:end-1);
freq = 0:fs/lpad:fs/2;
plot(freq,(abs(xdft))), set(gca, 'YScale', 'log'), set(gca, 'XScale', 'log');
hold on
ylim([0.0000000001, 0.01])
q= abs(xdft);
hold off
I would just like to know how to set up a loop, that uses the folders directory. I have read through many old MatLab answers and read the literature, but my brain is frazzled now.
So in summary:
  1. How to set up the directory to 'C:\Users\qkvm83\OneDrive – Durham University\Fieldwork\Haltwhistle_31_01_19\River_audio\Transect\'
  2. How to set up the loop to go into the folder, take the audio files sequentially, then generate and save the figure into a new folder.
Any help would be beneficial, as I have been wrecking my brain for days on this.

Best Answer

  • William - perhaps something like the following will help
    function loadWavAndPerformFFT(fullPathToFolder)
    wavFiles = dir (fullfile(fullPathToFolder, '*.wav'));
    for k=1:length(wavFiles)
    wavFile = wavFiles(k).name;
    [x,fs] = audioread(wavFile);
    % perform FFT
    % show image
    % save to file
    where the above is a function that you would call with whatever folder you are interested in.