%% Expand Audio Signal
% Use dynamic range expansion to attenuate background noise from an audio signal.
% Set up the dsp.AudioFileReader and audioDeviceWriter System objects.

frameLength = 1024;
fileReader = dsp.AudioFileReader( ...
    'Filename','Counting-16-44p1-mono-15secs.wav', ...
    'SamplesPerFrame',frameLength);
deviceWriter = audioDeviceWriter( ...
    'SampleRate',fileReader.SampleRate);

%
% Corrupt the audio signal with Gaussian noise. Play the audio.

while ~isDone(fileReader)
    x = fileReader();
    xCorrupted = x + (1e-2/4)*randn(frameLength,1);
    deviceWriter(xCorrupted);
end

release(fileReader)

%
% Set up the expander with a threshold of -40 dB, a ratio of 10, an attack time of 0.01 seconds, a release time of 0.02 seconds, and a hold time of 0 seconds. Use the sample rate of your audio file reader.

dRE = expander(-40,10, ...
    'AttackTime',0.01, ...
    'ReleaseTime',0.02, ...
    'HoldTime',0, ...
    'SampleRate',fileReader.SampleRate);

%
% Set up the scope to visualize the signal before and after dynamic range expansion.

scope = dsp.TimeScope( ...
    'SampleRate',fileReader.SampleRate, ...
    'TimeSpanOverrunAction','Scroll', ...
    'TimeSpan',16, ...
    'BufferLength',1.5e6, ...
    'YLimits',[-1 1], ...
    'ShowGrid',true, ...
    'ShowLegend',true, ...
    'Title','Corrupted vs. Expanded Audio');

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

while ~isDone(fileReader)
    x = fileReader();
    xCorrupted = x + (1e-2/4)*randn(frameLength,1);
    y = dRE(xCorrupted);
    deviceWriter(y);
    scope([xCorrupted,y])
end

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

% Copyright 2012 The MathWorks, Inc.