function demo_pitch %khw2016 sept 24
close all
clearvars
%test1
%when no clipping is used, flute is ok but not oboe
 %clip_factor 1.5 for violin, 2 for oboe and flut, found by by exprimenent
%[raw_y,fs]=audioread('A5_flute.wav'); clip_factor=4 
[raw_y,fs]=audioread('A4_oboe.wav'); clip_factor=4
%[raw_y,fs]=audioread('A4_violin.wav'); clip_factor=2.5

clipping_tag=0 %1 use clipping, 0 no clipping

    
frame_begin=round(1.5/(1/fs))
frame_size=round(0.03/(1/fs)) %0.03=30ms etc

y=raw_y(frame_begin:frame_begin+frame_size);
%y=raw_y(1000:40000);
    %central
    peak_to_peak=max(y)-min(y);
    %mean_y=mean(y)
    %pause
    thresold_high=peak_to_peak/clip_factor
    thresold_low=-peak_to_peak/clip_factor
    

figure(1)
clf
subplot(4,1,1)
plot(raw_y)
title('input sound')

sound(raw_y,fs)

subplot(4,1,2)
%text1=figure(1)
plot(y)
    hold on
    plot([0,length(y)], [ thresold_high,thresold_high],'r-'); 
    plot([0,length(y)], [ thresold_low,thresold_low],'g-'); 
title('a segment of sound');
text1=sprintf('time in samples, sampling freq=%d Hz, frame begin=%d,frame size=%d',fs,frame_begin,frame_size);
%legend(text1);
xlabel(text1) ;
ylabel('amplitude')


if clipping_tag ==1
    

    for n=1:length(y)
        if y(n)< thresold_high && y(n)> thresold_low
            y(n)=0;
        end
    end
    subplot(4,1,3)
    plot(y)
    hold on
    plot([0,length(y)], [ thresold_high,thresold_high],'r-'); 
    plot([0,length(y)], [ thresold_low,thresold_low],'g-'); 
    
    title('central clipped , a segment of sound');
    ylabel('amplitude')
   
else
    subplot(4,1,3)
     plot(y)
    title('no central clipping , a segment of sound');
    ylabel('amplitude')
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
pitch_period = func_pitch (y,fs);

% min_freq = 80;
% max_freq = 300;
%
% period_max = round(fs / min_freq);
% period_min = round(fs / max_freq);

function pitch_period = func_pitch (y,fs)

clear pitch_period;

%period_min = round (fs .* 2e-3);  %=total data points in 2ms of "x"
period_min = 200 %round (fs .* 2e-3);  %=total data points in 2ms of "x"
%as, min period of a female voice frame = 2ms
%period_max = round (fs .* 20e-3);   %as, max period of a male voice frame = 20ms
period_max = 900%round (fs .* 20e-3);   %as, max period of a male voice frame = 20ms

%BODY OF PROGRAM
R=xcorr(y);


[R_max , R_mid]=max(R); %R_max is the peak of "R", R_mid=(index of R_max)=the
%midpoint of "R"
pitch_per_range = R ( R_mid + period_min : R_mid + period_max );
[R_max, R_mid] = max(pitch_per_range);
pitch_period = R_mid + period_min;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
min_peak_height=0.1; %make sure it is positive or high enough
[pks,locs] =findpeaks(R,'MinPeakHeight',min_peak_height)
subplot(4,1,4)
plot(R)
hold on
plot(locs,pks,'ro');

dd=diff(locs);
pitch=fs*(1/mean(dd))
%Average  pitch

text1=sprintf('peaks are red o, pitch=%3.2f, pitch/2=%3.2f',pitch,pitch/2);
%legend(text1);
xlabel(text1)
ylabel('xcorr')

'finished '

