data = csvread("VoiceTest1.csv");
data = data(46746:end,:);

% Down sample data, 44.1 kHz to 544.4Hz
reducedData = resample(data, 1,81); 

% Create an approximate guaussian curve filter
GaussianFilter = [1/2 1/2];
for i = 1:15
  GaussianFilter = conv(GaussianFilter, GaussianFilter); 
end

% Get RMS values and use the kernel to smooth the data 
RMSData=zeros(size(reducedData,1),1);

for i = 137:size(RMSData,1) % 1/4th of a second is 136 samples
  RMSData(i) = rms(reducedData(i-136:i)); 
end

RMSData = 4*log10(RMSData+1);

RMSDataFiltered = conv(RMSData, GaussianFilter, "same");

% get derivative of rms data (multiply by 150 to visualize it)
Derivative = conv(RMSDataFiltered, [1 -1], "same")*150;

% Set treshold. RMS treshold based on "silence" at the beggining
DerThresh = .004; RMSThresh = max(reducedData(1:250))*1.5;

% Set variables to visualize talking status
talk=zeros(size(reducedData,1),1);
talking = .03; smallPause = .02; stop = .01; status = stop;

%test for status
for i = 1: size(reducedData,1)
    if (status ~= talking && Derivative(i) > DerThresh)
        status = talking; 
    end
    if (status == talking && Derivative(i) < -DerThresh && RMSDataFiltered(i) < RMSThresh)
        PauseStart = i;
        status = smallPause;
    end
    if (status == smallPause && (i - PauseStart) > 1088)
        status = stop;
    end
    talk(i) = status;
end


figure(2)
plot(reducedData,'color',[0.6 0.6 0.6],'LineWidth',.3); hold on
plot(RMSDataFiltered, 'LineWidth',1.5); hold on
plot(Derivative, 'LineWidth',1.5); hold on
plot(talk, 'LineWidth',2); hold on
plot(zeros(size(talk,1),1)+ RMSThresh)
legend({"Positive Amplitude Audio","Filtered RMS","Derivative","Talking"})

