%% Plot Momentary Loudness and Loudness Range of Audio Stream
% 

%%
% Create an audio file reader and an audio device writer.
fileReader = dsp.AudioFileReader('FunkyDrums-44p1-stereo-25secs.mp3', ...
    'SamplesPerFrame',1024);
fs = fileReader.SampleRate;
deviceWriter = audioDeviceWriter('SampleRate',fs);

%%
% Create a time scope to visualize your audio stream loop.
timeScope = dsp.TimeScope('NumInputPorts',2, ...
    'SampleRate',fs, ...
    'TimeSpanOverrunAction','Scroll', ...
    'LayoutDimensions',[2,1], ...
    'TimeSpan',5, ...
    'BufferLength',5*fs);

% Top subplot of scope
timeScope.Title = 'Momentary Loudness';
timeScope.YLabel = 'LUFS';
timeScope.YLimits = [-40, 0];

% Bottom subplot of scope
timeScope.ActiveDisplay = 2;
timeScope.Title = 'Loudness Range';
timeScope.YLabel = 'LU';
timeScope.YLimits = [-1, 2];

%%
% Create a loudness meter. Use the sample rate of your input file as the
% sample rate of your loudness meter. Call |visualize| to open an
% 'EBU-mode' visualization for your loudness meter.
loudMtr = loudnessMeter('SampleRate',fs);
visualize(loudMtr)

%%
% In an audio stream loop:
%
% * Read in your audio file.
% * Compute the momentary loudness and loudness range.
% * Visualize the momentary loudness and loudness range on your time scope.
% * Play the audio signal.
%
% The 'EBU-mode' loudness meter visualization updates automatically while
% it is open. As a best practice, release your file reader and device
% writer once the loop is completed.

while ~isDone(fileReader)
    audioIn = fileReader();
    [momentaryLoudness,~,~,LRA] = loudMtr(audioIn);
    timeScope(momentaryLoudness,LRA);
    deviceWriter(audioIn);
end

release(fileReader)
release(deviceWriter)

%% 
% Copyright 2012 The MathWorks, Inc.