clear
close all
clc

%% Set basic Constants
sampleRate = 44100;
nBits = 16;
nChannels = 1;
timerPeriod = 100e-3; % repetition rate of showing data
nSamplesPerPeriod = sampleRate*timerPeriod;

%% Get information about audio device
allAudioDevices = audiodevinfo;
% show information of audio devices
namesOfDevices = {allAudioDevices.input.Name}.';
IDsOfDevices = {allAudioDevices.input.ID}';
% display table with all devices
disp(table(namesOfDevices, IDsOfDevices))

%% Does any of devices support wanted parameters?
IDofSupported = audiodevinfo(1, sampleRate, nBits, nChannels);
if IDofSupported == -1
   error('No device supproting specified parameters!');
end

%% Initialize recorder
% define IDofSupporting of different recording device if needed
hRecorder = audiorecorder(sampleRate, nBits, nChannels, IDofSupported);
%% Initialize figure
hFig = figure('CloseRequestFcn', @(src, evet)stopRecording(src, hRecorder));
hAxSignal = subplot(1, 2, 1, 'Parent', hFig, 'YLim', [-0.5, 0.5]*2^nBits);
hLineSignal = line('Parent', hAxSignal, 'XData', 1:nSamplesPerPeriod, ...
   'YData', zeros(1, nSamplesPerPeriod));

hAxSpectrum = subplot(1, 2, 2, 'Parent', hFig, 'YLim', [1e-3, nSamplesPerPeriod], ...
   'XScale', 'log');
hLineSpectrum = line('Parent', hAxSpectrum, 'XData', 1:nSamplesPerPeriod/2, ...
   'YData', zeros(1, nSamplesPerPeriod/2));
%% Set recorder properties
hRecorder.TimerFcn = ...
   @(~, ~)displayRecordedSound(hLineSignal, hLineSpectrum, hRecorder, ...
   nSamplesPerPeriod);
hRecorder.TimerPeriod = timerPeriod;

%% Start recording
record(hRecorder);

function displayRecordedSound(hLineSignal, hLineSpectrum, hRecorder, ...
   nSamplesPerPeriod)
% function is called every timerPeriod seconds
recordedSound = getaudiodata(hRecorder, 'int16');
% get last part of recorded sound
recordedPart = recordedSound(end-nSamplesPerPeriod+1:end);
hLineSignal.YData = recordedPart;

spectrumOfSignal = abs(fft(recordedPart - mean(recordedPart)));
hLineSpectrum.YData = spectrumOfSignal(1:end/2)/nSamplesPerPeriod;

end

function stopRecording(hFig, hRecorder)
% CloseRequestFcn of figure
stop(hRecorder);
delete(hFig);

end