How can I measure the harmonicity of an audio spectrum?
Please take a look at this previous answer.  Using the semantics and mathematical definitions from that answer...

Let $x[n]$ be the input signal from which you want to measure harmonicity or periodicity.  Assume $x[n]$ has no DC component (like it is the output of a DC blocking filter).  And $n_0$ is the sample index of the neighborhood of signal around where you want the harmonicity to be measured.  $N$ is a large integer defining how wide your rectangular window is.

Average Squared Difference Function, ASDF:

$$ Q_x[k, n_0] \triangleq \frac{1}{N} \sum\limits_{n=0}^{N-1} \left(x[n+n_0-\left\lfloor \tfrac{N+k}{2}\right\rfloor] \ - \ x[n+n_0-\left\lfloor \tfrac{N+k}{2}\right\rfloor + k] \right)^2 $$

$\left\lfloor \cdot \right\rfloor$ is the floor() function and, if $k$ is even then $ \left\lfloor \frac{k}{2}\right\rfloor = \left\lfloor \frac{k+1}{2}\right\rfloor = \frac{k}{2} $.

From that define an alternative form of Autocorrelation:

$$ R_x[k,n_0] = R_x[0,n_0] - \frac12 Q_x[k, n_0]  $$

where 

$$ R_x[0, n_0] \triangleq \frac{1}{N} \sum\limits_{n=0}^{N-1} (x[n+n_0-\left\lfloor \tfrac{N}{2}\right\rfloor])^2 $$

Since $Q_x[0, n_0] = 0$ and $Q_x[k, n_0] \ge 0$ for all lags $k$, that means that $ R_x[k, n_0] \le R_x[0, n_0] $ for all lags $k$.

You will find a period $P$ such that $P &gt; 0$ and $R_x[P, n_0] &gt; R_x[k, n_0]$ for all lags $k&gt;k_0$, other than the highest peak at $k=0$.

$k_0$ is the smallest value of $k&gt;0$ such that $ R_x[k, n_0]&lt;0 $.

Once that peak location $P$ is found, the harmonicity is

$$ r_x(n_0) \triangleq \frac{R_x[P, n_0]}{R_x[0, n_0]} $$

If $r_x(n_0) = 1$, then $x[n]$ is perfectly periodic (or "harmonic") in the vicinity of sample index $n_0$. If $r_x(n_0) = 0$, it's noise, no periodicity to be found.