read multiple audio files as an index, and get length of each file to another array in matlab

To read multiple audio files as an index and get the length of each file, you can do the following steps:

  1. Define a folder containing all the audio files.
  2. Use the dir function to get the details of all the files with a specific extension (e.g., .wav) in that folder.
  3. Store the file names in a cell array.
  4. Loop through the cell array and read each audio file using the audioread function.
  5. Get the length of each audio file using the length function and store it in another array.

Here's an example code snippet that demonstrates this:

main.m
folder = 'path_to_folder'; % define folder containing audio files
extension = '*.wav'; % define audio file extension

% get details of all audio files in folder
audio_files = dir(fullfile(folder, extension)); 
num_files = length(audio_files); % get number of audio files

% initialize arrays to store audio file names and lengths
file_names = cell(num_files, 1);
file_lengths = zeros(num_files, 1);

% loop through audio files to get names and lengths
for i = 1:num_files
    file_names{i} = audio_files(i).name;
    audio_file = fullfile(folder, audio_files(i).name);
    [audio, sample_rate] = audioread(audio_file);
    file_lengths(i) = length(audio);
end
660 chars
19 lines

In this example, folder is the path to the folder containing the audio files, extension is the file extension of the audio files (assuming all audio files have the same extension), and file_names and file_lengths are the arrays that will store the filenames and lengths of the audio files, respectively.

The dir function is used to get the details of all the audio files in the folder that have the .wav extension. The fullfile function is used to create the full path to each audio file. The audioread function is used to read each audio file and return the audio waveform and its sample rate. Finally, the length function is used to get the length of each audio waveform.

Note that this code assumes that all audio files have the same sample rate. If this is not the case, you may need to resample the audio to a common sample rate before computing the length.

related categories

gistlibby LogSnag