%% Compress Audio Signal
% Use dynamic range compression to attenuate the volume of loud sounds.
% Set up the dsp.AudioFileReader and audioDeviceWriter System objects™.

frameLength = 1024;
fileReader = dsp.AudioFileReader( ...
    'Filename','RockDrums-44p1-stereo-11secs.mp3', ...
    'SamplesPerFrame',frameLength);
deviceWriter = audioDeviceWriter( ...
    'SampleRate',fileReader.SampleRate);

%
% Set up the compressor to have a threshold of -15 dB, a ratio of 7, and a knee width of 5 dB. Use the sample rate of your audio file reader.

dRC = compressor(-15,7, ...
    'KneeWidth',5, ...
    'SampleRate',fileReader.SampleRate);

%
% Set up the scope to visualize the original audio signal, the compressed audio signal, and the applied compressor gain.

scope = dsp.TimeScope( ...
    'SampleRate',fileReader.SampleRate, ...
    'TimeSpan',1, ...
    'BufferLength',44100*4, ...
    'YLimits',[-1,1], ...
    'TimeSpanOverrunAction','Scroll', ...
    'ShowGrid',true, ...
    'LayoutDimensions',[2,1], ...
    'NumInputPorts',2, ...
    'Title', ...
    ['Original vs. Compressed Audio (top)' ...
    ' and Compressor Gain in dB (bottom)']);
scope.ActiveDisplay = 2;
scope.YLimits = [-4,0];
scope.YLabel = 'Gain (dB)';

%
% Play the processed audio and visualize it on the scope.

while ~isDone(fileReader)
    x = fileReader();
    [y,g] = dRC(x);
    deviceWriter(y);
    scope([x(:,1),y(:,1)],g(:,1))
end

release(dRC)
release(deviceWriter)
release(scope)

% Copyright 2012 The MathWorks, Inc.