Skip to content

Instantly share code, notes, and snippets.

@elijahrockers
Last active December 19, 2015 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elijahrockers/1e9f1ece4fcc546d756b to your computer and use it in GitHub Desktop.
Save elijahrockers/1e9f1ece4fcc546d756b to your computer and use it in GitHub Desktop.
% Tabber
% Elijah Rockers - 2013
% Autocorrelation
% E2 = 82.41Hz
% E6 = 1318.510Hz
% Variables
sample_rate = 48000;
window_size = 3000;
min_lag = 25;
max_lag = 800;
energy_threshold = 0;
f_tone = 170;
%x = wavread('G Major.wav');
t=0:1/sample_rate:3;
tone = sin(f_tone*2*pi*t);
x = transpose(tone);
% Roughly calculates how many iterations are needed to cover all data
j=(size(x,1)/(max_lag));
j=floor(j);
for i=1:j
% Makes sure 'x1' does not exceed valid size
if ((size(x,1)) < ((max_lag*i)+window_size-max_lag))
break
else
x1 = x(((max_lag*i)+1-max_lag):((max_lag*i)+window_size-max_lag));
% May need to 'fade window' x1 here
% This for-loop autocorrelates
for k=min_lag:max_lag
% Make sure 'x2' doesn't exceed valid size
if ((size(x,1)) < ((max_lag*i)+window_size-max_lag+k))
break
else
x2 = x(((max_lag*i)+1-max_lag+k):((max_lag*i)+window_size-max_lag+k));
r(i,k)=dot(x1,x2);
end
end
% 'n' keeps track of which sample each window started on
n(i) = (max_lag*i)+1-max_lag;
max_i(i)=0;
% THIS NEEDS TO FIND PERIOD... DOESN'T REALLY
for k=2:(size(r,2)-1)
if (size(r,1) < i)
break
else
if ((r(i,k) > r(i,k-1))&&(r(i,k) > r(i,k+1)))
max_i(i)=k;
end
end
end
if (r(i,min_lag) >= energy_threshold)
freq_i(i)=(1/(max_i(i)/sample_rate));
else
freq_i(i)=0;
end
end
end
for i=1:size(freq_i,2)
if freq_i(i) > 1320
freq_i(i)=0;
end
end
figure(1);
subplot(2,1,1), plot(1:size(x),x(1:size(x)));
xlabel('samples');
ylabel('audio');
subplot(2,1,2), plot(n,freq_i(1:size(freq_i,2)));
xlabel('samples');
ylabel('frequency');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment