%% Tune Parameters of Multiple Objects
% parameterTuner enables you to graphically tune parameters of multiple objects. In this example, you use a crossover filter to split a signal into multiple subbands and then apply different effects to the subbands.
% Create a dsp.AudioFileReader to read in audio frame-by-frame. Create an audioDeviceWriter to write audio to your sound card.

fileReader = dsp.AudioFileReader('FunkyDrums-48-stereo-25secs.mp3', ...
                                 'PlayCount',2);
deviceWriter = audioDeviceWriter('SampleRate',fileReader.SampleRate);

%
% Create a crossoverFilter with two crossovers to split the audio into three bands. Call visualize to plot the frequency responses of the filters. Call parameterTuner to open a UI to tune the crossover frequencies while streaming.

xFilt = crossoverFilter('SampleRate',fileReader.SampleRate,'NumCrossovers',2);
visualize(xFilt)
parameterTuner(xFilt)

%
%
%
% Create two compressor objects to apply dynamic range compression on two of the subbands. Call visualize to plot the static characteristic of both of the compressors. Call parameterTuner to open UIs to tune the static characteristics.

cmpr1 = compressor('SampleRate',fileReader.SampleRate);
visualize(cmpr1)
parameterTuner(cmpr1)

%
%
%

cmpr2 = compressor('SampleRate',fileReader.SampleRate);
visualize(cmpr2)
parameterTuner(cmpr2)

%
%
%
% Create an audiopluginexample.Chorus to apply a chorus effect to one of the bands. Call parameterTuner to open a UI to tune the chorus plugin parameters.

chorus = audiopluginexample.Chorus;
setSampleRate(chorus,fileReader.SampleRate);
parameterTuner(chorus)

%
% In an audio stream loop:
% Read in a frame of audio from the file.
% Split the audio into three bands using the crossover filter.
% Apply dynamic range compression to the first and second bands.
% Apply a chorus effect to the third band.
% Sum the audio bands.
% Write the frame of audio to your audio device for listening.

while ~isDone(fileReader)
    audioIn = fileReader();
    
    [b1,b2,b3] = xFilt(audioIn);
    
    b1 = cmpr1(b1);
    b2 = cmpr2(b2);
    b3 = process(chorus,b3);
    
    audioOut = b1+b2+b3;

    deviceWriter(audioOut);
    
    drawnow limitrate % Process parameterTuner callbacks
end

%
% As a best practice, release your objects once done.

release(fileReader)
release(deviceWriter)

%
% Copyright 2018 The MathWorks, Inc.