# Measuring musical pitch with MATLAB

Matlab @ 31 December 2010

Well I don’t really have anything to say about this function other than that it measures the fundamental frequency of some given recorded audio and returns its nearest musical pitch. Maybe I’ll have more to say later. Adieu.

 
function v=voicesampler(Fs)
%Get recording
time=input('How many seconds of recording?');
v.recording = audiorecorder(Fs,8,1);
disp('Start speaking.')
recordblocking(v.recording, time);
disp('End of Recording.');
 
%Convert data
v.audio=getaudiodata(v.recording);
v.n=length(v.audio);
v.k=1:(v.n-1);
v.T=v.n/Fs;
v.freq=v.k./v.T;
v.nyquist=1/2;
v.range=ceil(v.n*v.nyquist);
v.fft=abs((fft(v.audio)./v.n));
v.power=v.fft(1:v.range);
v.fundamentalfreq=v.freq(find(v.power==max(v.power)));
 
%Pitch
pitchname=char('C0', 'C#0', 'D0', 'D#0', 'E0', 'F0', 'F#0', 'G0', 'G#0', 'A0', 'A#0', 'B0', 'C1', 'C#1', 'D1', 'D#1', 'E1', 'F1', 'F#1', 'G1', 'G#1', 'A1', 'A#1', 'B1', 'C2', 'C#2', 'D2', 'D#2', 'E2', 'F2', 'F#2', 'G2', 'G#2', 'A2', 'A#2', 'B2', 'C3', 'C#3', 'D3', 'D#3', 'E3', 'F3', 'F#3', 'G3', 'G#3', 'A3', 'A#3', 'B3', 'C4', 'C#4', 'D4', 'D#4', 'E4', 'F4', 'F#4', 'G4', 'G#4', 'A4', 'A#4', 'B4', 'C5', 'C#5', 'D5', 'D#5', 'E5', 'F5', 'F#5', 'G5', 'G#5', 'A5', 'A#5', 'B5', 'C6', 'C#6', 'D6', 'D#6', 'E6', 'F6', 'F#6', 'G6', 'G#6', 'A6', 'A#6', 'B6', 'C7', 'C#7', 'D7', 'D#7', 'E7', 'F7', 'F#7', 'G7', 'G#7', 'A7', 'A#7', 'B7', 'C8', 'C#8', 'D8', 'D#8');
pitchfreq=[16.35 17.32 18.35 19.45 20.6 21.83 23.12 24.5 25.96 27.5 29.14 30.87 32.7 34.65 36.71 38.89 41.2 43.65 46.25 49 51.91 55 58.27 61.74 65.41 69.3 73.42 77.78 82.41 87.31 92.5 98 103.83 110 116.54 123.47 130.81 138.59 146.83 155.56 164.81 174.61 185 196 207.65 220 233.08 246.94 261.63 277.18 293.66 311.13 329.63 349.23 369.99 392 415.3 440 466.16 493.88 523.25 554.37 587.33 622.25 659.26 698.46 739.99 783.99 830.61 880 932.33 987.77 1046.5 1108.73 1174.66 1244.51 1318.51 1396.91 1479.98 1567.98 1661.22 1760 1864.66 1975.53 2093 2217.46 2349.32 2489.02 2637.02 2793.83 2959.96 3135.96 3322.44 3520 3729.31 3951.07 4186.01 4434.92 4698.64 4978.03];
pitchcloseness=abs(pitchfreq-v.fundamentalfreq);
v.closestpitch=pitchname(find(pitchcloseness==min(pitchcloseness)),:);
disp(['Your pitch was closest to: ' v.closestpitch])