%% Filter Audio Using Low-Shelf Equalizer
% Create audio file reader and audio device writer objects. Use the sample rate of the reader as the sample rate of the writer.

frameSize = 256;

fileReader = dsp.AudioFileReader("RockGuitar-16-44p1-stereo-72secs.wav","SamplesPerFrame",frameSize);

deviceWriter = audioDeviceWriter("SampleRate",fileReader.SampleRate);

%
% Play the audio signal through your device.

count = 0;
while count < 2500
    audio = step(fileReader);
    play(deviceWriter,audio);
    count = count + 1;
end
reset(fileReader)

%
% Design a second-order sections (SOS) low-shelf equalizer.

gain = 10;
slope = 3;
Fc = 0.025;

[B,A] = designShelvingEQ(gain,slope,Fc);

%
% Visualize your shelving filter design.

SOS = [B',[1,A']];
fvtool(dsp.BiquadFilter("SOSMatrix",SOS), ...
    "Fs",fileReader.SampleRate, ...
    "FrequencyScale","Log");

%
% Create a biquad filter object.

myFilter = dsp.BiquadFilter( ...
    "SOSMatrixSource","Input port", ...
    "ScaleValuesInputPort",false);

%
% Create a spectrum analyzer object to visualize the original audio signal and the audio signal passed through your low-shelf equalizer.

scope = dsp.SpectrumAnalyzer( ...
    "SampleRate",fileReader.SampleRate, ...
    "PlotAsTwoSidedSpectrum",false, ...
    "FrequencyScale","Log", ...
    "FrequencyResolutionMethod","WindowLength", ...
    "WindowLength",frameSize, ...
    "Title","Original and Equalized Signal", ...
    "ShowLegend",true, ...
    "ChannelNames",{'Original Signal','Equalized Signal'});

%
% Play the equalized audio signal and visualize the original and equalized spectrums.

count = 0;
while count < 2500
    originalSignal = fileReader();
    equalizedSignal = myFilter(originalSignal,B,A);
    scope([originalSignal(:,1),equalizedSignal(:,1)]);
    deviceWriter(equalizedSignal);
    count = count + 1;
end

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

release(fileReader)
release(deviceWriter)
release(scope)

% Copyright 2012 The MathWorks, Inc.