%% Synchronize Playback and Recording
% Synchronize playback and recording using a single audio device. If synchronization is lost, print information about samples dropped.
% Create objects to read from and write to an audio file. Create an audioPlayerRecorder object to play an audio signal to your device and simultaneously record audio from your device.

fileReader = dsp.AudioFileReader('Counting-16-44p1-mono-15secs.wav', ...
    'SamplesPerFrame',512);
fs = fileReader.SampleRate;

fileWriter = dsp.AudioFileWriter('Counting-PlaybackRecorded.wav', ...
    'SampleRate',fs);

aPR = audioPlayerRecorder('SampleRate',fs);

%
% In a frame-based loop:
% Read an audio signal from your file.
% Play the audio signal to your device and simultaneously record audio from your device. Use the optional nUnderruns and nOverruns output arguments to track any loss of synchronization.
% Write your recorded audio to a file.
% Once the loop is completed, release the objects to free devices and resources.

while ~isDone(fileReader)
    audioToPlay = fileReader();
    
    [audioRecorded,nUnderruns,nOverruns] = aPR(audioToPlay);
    
    fileWriter(audioRecorded)
    
    if nUnderruns > 0
        fprintf('Audio player queue was underrun by %d samples.\n',nUnderruns);
    end
    if nOverruns > 0
        fprintf('Audio recorder queue was overrun by %d samples.\n',nOverruns);
    end
end

%

release(fileReader)
release(fileWriter)
release(aPR)

%
% Copyright 2012 The MathWorks, Inc.