%% Determine Microphone Calibration Factor
% This diagram depicts the setup used in the example:
%
% To run this example, you must connect a microphone and loudspeaker to a full-duplex sound card, and use an SPL meter to determine the true loudness level.
% Create an audioOscillator object to generate a 1 kHz sine wave at a sample rate of 48 kHz.

fs = 48e3;
osc = audioOscillator("sine",1e3,"SampleRate",fs);

%
% Create an audioPlayerRecorder object to write the sine wave to your loudspeaker and simultaneously read from your microphone.

playRec = audioPlayerRecorder(fs);

%
% Create a dsp.AsyncBuffer object to store the audio recorded from your microphone. Specify the capacity of the buffer to hold 3 seconds worth of data.

dur = 3;
buff = dsp.AsyncBuffer(dur*fs);

%
% In a loop, for three seconds:
% Generate a frame of a 1 kHz sinusoid.
% Write the frame to your loudspeaker and simultaneously read a frame from your microphone.
% Write the frame acquired from your microphone to the buffer.
% While the loop runs, note the true SPL measurement as reported from your SPL meter. Once complete, read the contents of the buffer object.

numFrames = dur*(fs/osc.SamplesPerFrame);
for ii = numFrames
    audioOut = osc();
    audioIn = playRec(audioOut);
    write(buff,audioIn);
end

SPL = 78.2; % read from physical SPL meter

micRecording = read(buff);

% Compute the calibration factor for the microphone.

calibrationFactor = calibrateMicrophone(micRecording,playRec.SampleRate,SPL);

% Copyright 2019 The MathWorks, Inc.