# Pitch Calculation Error via Autocorrelation Method

### Source Code

library("tuneR")
library("seewave")

#0: Acquisition of sample sound
from = 0, to = 1, units = "seconds")
dur_smpl = duration(snd_smpl)
len_smpl = length(snd_smpl)

#1 : Pre-Processing Stage

#1.1 : Application of Hanning Window
n = 1:len_smpl
han_win = 0.5-0.5*cos(2*pi*n/(len_smpl-1))
wind_sig = han_win*snd_smpl@left

#2.1 : Auto-Correlation Calculation
rev_wind_sig = rev(wind_sig)    #Reversing the windowed signal

acorr_1 = convolve(wind_sig, rev_wind_sig, type = "open")
# Obtaining the 2nd half of the correlation, to simplify calculation
n = 2*len_smpl-1
acorr_2 = (1/len_smpl)*acorr_1[len_smpl:n]

#2.2 : Note Calculation
min_index = which.min(acorr_2)
print(min_index)
fs = 44100
fo = fs/min_index #To obtain fundamental frequency

print(fo)
print(notenames(noteFromFF(fo)))


### Output

> print(min_index)
[1] 37
> fs = 44100
> fo = fs/min_index
> print(fo)
[1] 1191.892
> print(notenames(noteFromFF(fo)))
[1] "d'''"


The entire calculation is performed in the Time Domain. I'm currently using autocorrelation as a base to understand more about Pitch Detection & Analysis. I've tried to analyse the sample with 'Audacity' and the result is 'C5'. Hence, I'm wondering where actually the issue is. Can you all help me find it?

Also, there are a few but important doubts:

1. How small should actually my analysis window be (20ms, 1s,..)?
2. Will reinforcement of the Autocorrelation Algorithm with AMDF and other similar algorithms make this Pitch Detection module more robust?
• i have a couple of answers about how i would suggest approaching pitch detection in the time domain. 1, 2. there is a relationship between autocorrelation (ACF) and the average squared difference function (ASDF) as an alternative to average magnitude difference function (AMDF). also, if you do ACF of a finite length with convolution, you get a tapering effect. – robert bristow-johnson Oct 11 '18 at 6:19

In the latest image you can see the periodicity of the autocorrelation, and in order to identify the period of the signal I used a treshold of $$0.3 r_c[0]$$ (where r_c[0] is the maximum value of the autocorrelation), and find the first peak that is higher than the threshold inside a "known" region (in my case it was between the samples 20 and 200 because of the nature of the signal).