MATLAB: How to read all the audio files from one directory and store it as one variable matrix

audioMATLABneural network

I need help, I have a set of audio samples I want to read all my audio sample at once and store it as one numerical matrix for developing ANN, I tried with this code but it give more erros, so if someone can give script or explanation on developing script for this?
% P = 'audiofolder';
S = dir(fullfile(P,'*.wav'));
N = natsortfiles({S.name});
C = cell(size(N));
D = cell(size(N));
for k = 1:numel(N)
str = fullfile(P,N{k});
[C{k},D{k}] = audioread(str);
end
mat = [C{:}];
fs = [D{:}];

Best Answer

  • That code is mostly right.
    I predict that your files do not all have exactly the same number of samples. You are using [C{:}] which is exactly equivalent to horzcat(C{:}] which tries to store the contents of the cell C as adjacent columns. That would fail if there is even one file with different number of samples, as samples are expressed through rows. It would not fail if the files had different number of channels, but on the other hand you are not in that code keeping track of the number of channels each file has.
    You need to decide what you want to do.
    If you want to just string all of the sounds together as if it had been one long recording, then use vertcat(C{:}) provided that the number of channels is the same.
    If you want to put the sounds side by side, then:
    • you could truncate all to the least samples
    • you could pad the short ones
    • you could discard the ones that are not the same
    • you could interpolate to all the same size. This might involve a pitch change, depending how you do it.
    You also need to decide what you want to do if the files are not all the same sampling frequency.