function audioReverberationCompilerExampleApp(timeToRun)
%AUDIOREVERBERATIONCOMPILEREXAMPLEAPP Apply reverberation to audio
%
% Inputs:
% timeToRun    - Time duration to run audio samples
%
% This function audioReverberationCompilerExampleApp is only in support of 
% audioReverberationCompilerExample. It may change in a future release.

% Copyright 2015-2017 The MathWorks, Inc.

%% Initialization

% Default values for inputs
if nargin == 0
    timeToRun = 60;       % Run until user stops simulation. 
end

% If launched from a standalone executable, parameters will be char.
% Convert them to logical/double values
if ischar(timeToRun)
    timeToRun = str2double(timeToRun);
end

% Audio file reader
frameSize = 512;
reader = dsp.AudioFileReader('FunkyDrums-44p1-stereo-25secs.mp3', ...
    'SamplesPerFrame',frameSize,'PlayCount',inf);
Fs = reader.SampleRate;

% Audio player
s = 'Choose audio player device: \n';
player = audioDeviceWriter('SampleRate',Fs);
devs = getAudioDevices(player);
for idx = 1:length(devs)
    s = [s, num2str(idx), '. ', devs{idx}, '\n']; %#ok
end
inp = input(s);
validateattributes(inp,{'numeric'}, ...
    {'integer','scalar','positive','finite','<=',length(devs)}, ...
    '','Input index');
player.Device = devs{inp};

% Parameters to be tuned
param(1).Name = 'Pre-delay (s)';
param(1).InitialValue = 0;
param(1).Limits = [0, 1];

param(2).Name = 'Highcut frequency (Hz)';
param(2).InitialValue = 20000;
param(2).Limits = [20, 20000];     

param(3).Name = 'Diffusion';
param(3).InitialValue = 0.5;
param(3).Limits = [0, 1];  

param(4).Name = 'DecayFactor';
param(4).InitialValue = 0.5;
param(4).Limits = [0, 1];  

param(5).Name = 'High frequency damping';
param(5).InitialValue = 5e-4;
param(5).Limits = [0, 1];  

param(6).Name = 'Wet/Dry Mix';
param(6).InitialValue = 0.3;
param(6).Limits = [0, 1];  

% Create the UI and pass it the parameters
tuningUI = HelperCreateParamTuningUI(param, ...
    'Reverberation controls');
clear HelperAudioReverberation

%% Streaming
nIters = round(timeToRun*Fs/reader.SamplesPerFrame);
count = 1;
while count < nIters
    
    S = HelperUnpackUIData(tuningUI);
    
    if S.Stop     % If "Stop Simulation" button is pressed 
        break;
    end
    
    if S.Pause
        continue;
    end
    
    audioIn = reader();

    audioOut = HelperAudioReverberation(audioIn, S, Fs);

    player(audioOut);
    
    count = count + 1;
end

%% Cleanup
if ishghandle(tuningUI)  % If parameter tuning UI is open, then close it.
    delete(tuningUI);
    drawnow;
    clear tuningUI
end
release(reader);
release(player);

clear HelperUnpackUIData HelperAudioReverberation