%% Output Mel Spectrogram
% Use transform to create an audio datastore that returns a mel spectrogram representation from the read function.
%
% Specify the file path to the audio samples included with Audio Toolbox™. Create an audio datastore that points to the specified folder.

folder = fullfile(matlabroot,'toolbox','audio','samples');
ADS = audioDatastore(folder);

%
% Define a function that transforms audio data from a time-domain representation to a log mel spectrogram. The function adds the additional outputs from the melSpectrogram function to the info struct output from reading the audio datastore.
% function [dataOut,infoOut] = extractMelSpectrogram(audioIn,info)
%
%     [S,F,T] = melSpectrogram(audioIn,info.SampleRate);
%
%     dataOut = 10*log10(S+eps);
%     infoOut = info;
%     infoOut.CenterFrequencies = F;
%     infoOut.TimeInstants = T;
% end
%
% Call transform to create a TransformedDatastore with Transforms set to extractMelSpectrogram.

ADSnew = transform(ADS,@extractMelSpectrogram,'IncludeInfo',true)

%
% Read the first three audio files and plot the log mel spectrograms. If there are multiple channels, plot only the first channel.

for i = 1:3
    [melSpec,info] = read(ADSnew);
    
    figure(i)
    surf(info.TimeInstants,info.CenterFrequencies,melSpec(:,:,1),'EdgeColor','none');
    xlabel('Time (s)')
    ylabel('Frequency (Hz)')
    [~,name] = fileparts(info.FileName);
    title(name)
    axis([0 info.TimeInstants(end) info.CenterFrequencies(1) info.CenterFrequencies(end)])
    view([0,90])
end

%
% Copyright 2018 The MathWorks, Inc.