%% Pre-Extract Features from Audio Data Set
% You can use pre-extracted features to reduce iteration time when developing a machine learning or deep learning system. It is also a common practice to use pre-extracted features for unsupervised learning tasks such as similarity clustering, and for content-based indexing tasks such as music information retrieval (MIR).
%
% Create an audioDatastore object that points to the audio samples included with Audio Toolbox™.

folder = fullfile(matlabroot,"toolbox","audio","samples");
ads = audioDatastore(folder)

%
% Create a custom write function that extracts mel frequency cepstral coefficients (mfcc) from the audio and writes the them to a MAT file. The function definition is located at the end of this example.
% function myWriter(audioIn,info,~)
%     fs = info.ReadInfo.SampleRate;
%
%     % Extract MFCC
%     [coeffs,delta,deltaDelta] = mfcc(audioIn,fs);
%
%     % Replace the file extension of the suggested output name with MAT.
%     filename = strrep(info.SuggestedOutputName,".wav",".mat");
%
%     % Save the MFCC coefficients to the MAT file.
%     save(filename,"coeffs","delta","deltaDelta")
% end
%
% Define the output location for the extracted features.

outputLocation = pwd;

%
% Call the writeall function with the audioDatastore object, output location, and custom write function. Also specify the suffix _MFCC to the file names.

tic
writeall(ads,outputLocation,"WriteFcn",@myWriter,"FilenameSuffix","_MFCC")
fprintf("Data set creation completed (%0.0f seconds)\n",toc)

%
% You have now created a data set consisting of MFCCs for each audio file.

fds = fileDatastore(pwd,"ReadFcn",@load,"FileExtensions",".mat","IncludeSubfolders",true)

%
%% Helper Function

function myWriter(audioIn,info,~)
    fs = info.ReadInfo.SampleRate;
    [coeffs,delta,deltaDelta] = mfcc(audioIn,fs);
    filename = strrep(info.SuggestedOutputName,".wav",".mat");
    save(filename,"coeffs","delta","deltaDelta")
end

% Copyright 2019 The MathWorks, Inc.