Search code examples
matlabaudiofrequencysampling

Splitting an audio file in Matlab


I'm trying to split an audio file into 30 millisecond disjoint intervals using Matlab. I have the following code at the moment:

clear all
close all

% load the audio file and get its sampling rate
[y, fs] = audioread('JFK_ES156.wav');

for m = 1 : 6000
    [t(m), fs] = audioread('JFK_ES156.wav', [(m*(0.03)*fs) ((m+1)*(0.03)*fs)]);
end

But the problem is that I get the following error:

In an assignment  A(I) = B, the number of elements in B and I
must be the same.

Error in splitting (line 12)
    [t(m), fs] = audioread('JFK_ES156.wav', [(m*(0.03)*fs)
    ((m+1)*(0.03)*fs)]);

I don't see why there's a mismatch in the number of elements in B and I and how to solve this. How can I get past this error? Or is there just an easier way to split the audio file (maybe another function I don't know about or something)?


Solution

  • You should just use the variable y and reshape it to form your split audio. For example,

    chunk_size = fs*0.03;
    y_chunks = reshape(y, chunk_size, 6000);
    

    That will give you a matrix with each column a 30 ms chunk. This code will also be faster than reading small segments from file in a loop.

    As hiandbaii suggested you could also use cell array. Make sure you clear your existing variables before that. Not clearing the array t is probably the reason you got the error "Cell contents assignment to a non-cell array object."

    Your original error is because you cannot assign a vector with scalar indexing. That is, 'm' is a scalar, but your audioread call is returning a vector. This is what the error says about mismatch in size of I and B. You could also fix that by making t a 2-D array and use an assignment like

    [t(m,:), fs] =