%% Determine and Decrease Overrun
% Overrun refers to input signal drops, which occur when the audio stream loop does not keep pace with the device. Determine overrun of an audio stream loop, add an artificial computational load to the audio stream loop, and then modify properties of your audioDeviceReader object to decrease overrun. Your results depend on your computer.
% Create an audioDeviceReader System object with SamplesPerFrame set to 256 and SampleRate set to 44100. Call setup to reduce the computational load of initialization in an audio stream loop.

deviceReader = audioDeviceReader( ...
    'SamplesPerFrame',256, ...
    'SampleRate',44100);
setup(deviceReader)

%
% Create a dsp.AudioFileWriter object. Specify the file name and data type to write.

fileWriter = dsp.AudioFileWriter('mySpeech.wav','FileFormat','WAV');

%
% Record 5 seconds of speech. In an audio stream loop, read an audio signal frame from your device, and write the audio signal frame to a specified file.

totalOverrun = 0;
disp('Speak into microphone now.')
tic
while toc < 5
    [input,numOverrun] = deviceReader();
    totalOverrun = totalOverrun + numOverrun;
    fileWriter(input);
end
fprintf('Recording complete.\n')
fprintf('Total number of samples overrun: %d.\n',totalOverrun)
fprintf('Total seconds overrun: %d.\n',double(totalOverrun)/double(deviceReader.SampleRate))

%
% Release your audioDeviceReader and dsp.AudioDeviceWriter objects and zero your counter variable.

release(fileWriter)
release(deviceReader)
totalOverrun = 0;

%
% Use pause to add an artificial computational load to your audio stream loop. The computational load causes the audio stream loop to go slower than the device, which causes acquired samples to be dropped.

disp('Speak into microphone now.')
tic
while toc < 5
    [input,numOverrun] = deviceReader();
    totalOverrun = totalOverrun + numOverrun;
    fileWriter(input);
    pause(0.01)
end
fprintf('Recording complete.\n')
fprintf('Total number of samples overrun: %d.\n',totalOverrun)
fprintf('Total seconds overrun: %d.\n',double(totalOverrun)/double(deviceReader.SampleRate))

%
% Release your audioDeviceReader and dsp.AudioFileWriter objects, and set the SamplePerFrame property to 512. The device buffer size increases so that the device now takes longer to acquire a frame of data. Set your counter variable to zero.

release(fileWriter)
release(deviceReader)
deviceReader.SamplesPerFrame = 512;
totalOverrun = 0;

%
% Calculate the total overrun of the audio stream loop using your modified SamplesPerFrame property.

disp('Speak into microphone now.')
tic
while toc < 5
    [input,numOverrun] = deviceReader();
    totalOverrun = totalOverrun + numOverrun;
    fileWriter(input);
    pause(0.01)
end
fprintf('Recording complete.\n')
fprintf('Total number of samples overrun: %d.\n',totalOverrun)
fprintf('Total seconds overrun: %f.\n',totalOverrun/deviceReader.SampleRate)

%
% Copyright 2012 The MathWorks, Inc.