%% Calculate Spectral Rolloff Point of Streaming Audio
% Create a dsp.AudioFileReader object to read in audio data frame-by-frame. Create a dsp.SignalSink to log the spectral rolloff point calculation.

fileReader = dsp.AudioFileReader('Counting-16-44p1-mono-15secs.wav');
logger = dsp.SignalSink;

%
% In an audio stream loop:
% Read in a frame of audio data.
% Calculate the spectral rolloff point for the frame of audio.
% Log the spectral rolloff point for later plotting.
% To calculate the spectral rolloff point for only a given input frame, specify a window with the same number of samples as the input, and set the overlap length to zero. Plot the logged data.

win = hamming(fileReader.SamplesPerFrame);
while ~isDone(fileReader)
    audioIn = fileReader();
    rolloffPoint = spectralRolloffPoint(audioIn,fileReader.SampleRate, ...
                                       'Window',win, ...
                                       'OverlapLength',0);
    logger(rolloffPoint)
end

plot(logger.Buffer)
ylabel('Rolloff Point (Hz)')

%
% Use dsp.AsyncBuffer if
% The input to your audio stream loop has a variable samples-per-frame.
% The input to your audio stream loop has an inconsistent samples-per-frame with the analysis window of spectralRolloffPoint.
% You want to calculate the spectral rolloff point for overlapped data.
% Create a dsp.AsyncBuffer object, reset the logger, and release the file reader.

buff = dsp.AsyncBuffer;
reset(logger)
release(fileReader)

%
% Specify that the spectral rolloff point is calculated for 50 ms frames with a 25 ms overlap.

fs = fileReader.SampleRate;

samplesPerFrame = round(fs*0.05);
samplesOverlap = round(fs*0.025);

samplesPerHop = samplesPerFrame - samplesOverlap;

win = hamming(samplesPerFrame);

while ~isDone(fileReader)
    audioIn = fileReader();
    write(buff,audioIn);
    
    while buff.NumUnreadSamples >= samplesPerHop
        audioBuffered = read(buff,samplesPerFrame,samplesOverlap);
        
        rolloffPoint = spectralRolloffPoint(audioBuffered,fs, ...
                                   'Window',win, ...
                                   'OverlapLength',0);
        logger(rolloffPoint)
    end
    
end
release(fileReader)

%
% Plot the logged data.

plot(logger.Buffer)
ylabel('Rolloff Point (Hz)')

%
% Copyright 2018 The MathWorks, Inc.