%% Analysis and Synthesis
% This example illustrates a nonoptimal but simple approach to analysis and synthesis using gammatoneFilterBank.
% Read in an audio file and listen to its contents.

[audioIn,fs] = audioread('Counting-16-44p1-mono-15secs.wav');
sound(audioIn,fs)

%
% Create a default gammatoneFilterBank. The default frequency range of the filter bank is 50 to 8000 Hz. Frequencies outside of this range are attenuated in the reconstructed signal.

gammaFiltBank = gammatoneFilterBank('SampleRate',fs)

%
% Pass the audio signal through the gammatone filter bank. The output is 32 channels, where the number of channels is set by the NumFilters property of the gammatoneFilterBank.

audioOut = gammaFiltBank(audioIn);

[N,numChannels] = size(audioOut)

%
% To reconstruct the original signal, sum the channels. Listen to the result.

reconstructedSignal = sum(audioOut,2);
sound(reconstructedSignal,fs)

%
% The gammatone filter bank introduced various group delays for the output channels, which results in poor reconstruction. To compensate for the group delay, remove the beginning delay from the individual channels and zero-pad the ends of the channels. Use info to get the group delays. Listen to the group delay-compensated reconstruction.

infoStruct = info(gammaFiltBank);
groupDelay = round(infoStruct.GroupDelays); % round for simplicity

audioPadded = [audioOut;zeros(max(groupDelay),gammaFiltBank.NumFilters)];

for i = 1:gammaFiltBank.NumFilters
    audioOut(:,i) = audioPadded(groupDelay(i)+1:N+groupDelay(i),i);
end

reconstructedSignal = sum(audioOut,2);
sound(reconstructedSignal,fs)

%
% Copyright 2018 The MathWorks, Inc.