%% Calibrate Microphone Using Externally Generated Calibration Tone
% The diagram depicts the example setup and data flow.
%
%
% To run this example, you must connect a microphone to your audio card, generate a 1 kHz tone using an external device, and use an SPL meter to determine the true loudness level.
% Specify a 48 kHz sample rate for your audio device and a 3-second duration for acquiring audio. Create an audioDeviceReader object to read from your audio device.

fs = 48e3;
dur = 3;

deviceReader = audioDeviceReader(fs);

% Create a dsp.AsyncBuffer object to store the streamed audio.

buff = dsp.AsyncBuffer(dur*fs);

% Start the 1 kHz test tone using an external loudspeaker. Then, in a loop, read from your audio device and then write the data 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.

tic
while toc < dur
    audioIn = deviceReader();
    write(buff,audioIn);
end

SPL = 77.7; % read from physical SPL meter

micRecording = read(buff);

% Compute the calibration factor for the microphone.

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

% Copyright 2019 The MathWorks, Inc.