%% Detect Voice Activity Using Overlapped Frames
% Use a voice activity detector to detect the presence of speech in an audio 
% signal. Plot the probability of speech presence along with the audio samples.
% 
% Create a |dsp.AudioFileReader| System object?  to read a speech file.

afr = dsp.AudioFileReader('Counting-16-44p1-mono-15secs.wav');
fs = afr.SampleRate;
%% 
% Chunk the audio into 20 ms frames with 75% overlap between successive 
% frames. Convert the frame time in seconds to samples. Determine the hop size 
% (the increment of new samples). In the audio file reader, set the samples per 
% frame to the hop size. Create a default |dsp.AsyncBuffer| object to manage overlapping 
% between audio frames.

frameSize = ceil(20e-3*fs);
overlapSize = ceil(0.75*frameSize);
hopSize = frameSize - overlapSize;
afr.SamplesPerFrame = hopSize;

inputBuffer = dsp.AsyncBuffer('Capacity',frameSize);
%% 
% Create a |voiceActivityDetector| System object. Specify an FFT length 
% of 1024.

VAD = voiceActivityDetector('FFTLength',1024);
%% 
% Create a scope to plot the audio signal and corresponding probability 
% of speech presence as detected by the voice activity detector. Create an |audioDeviceWriter| 
% System object to play audio through your sound card.

scope = dsp.TimeScope('NumInputPorts',2, ...
    'SampleRate',fs, ...
    'TimeSpan',3, ...
    'BufferLength',3*fs, ...
    'YLimits',[-1.5,1.5], ...
    'TimeSpanOverrunAction','Scroll', ...
    'ShowLegend',true, ...
    'ChannelNames',{'Audio','Probability of speech presence'});

player = audioDeviceWriter('SampleRate',fs);
%% 
% Initialize a vector to hold the probability values.

pHold = ones(hopSize,1);
%% 
% In an audio stream loop:
% 
% # Read a hop worth of samples from the audio file and save the samples into 
% the buffer.
% # Read a frame from the buffer with specified overlap from the previous frame.
% # Call the voice activity detector to get the probability of speech for the 
% frame under analysis.
% # Set the last element of the probability vector to the new probability decision. 
% Visualize the audio and speech presence probability using the time scope.
% # Play the audio through your sound card.
% # Set the probability vector to the most recent result for plotting in the 
% next loop.

while ~isDone(afr)
    x = afr();
    n = write(inputBuffer,x);
    
    overlappedInput = read(inputBuffer,frameSize,overlapSize);
    
    p = VAD(overlappedInput);
    
    pHold(end) = p;
    scope(x,pHold)
    
    player(x);
    
    pHold(:) = p;
end
%% 
% Release the |player| once the audio finishes playing.

release(player)

%% 
% Copyright 2012 The MathWorks, Inc.