Maybe this is an elementary solution.
Via the formula
\begin{equation*}
a^p-b^p = (a-b)\sum_{k=0}^{p-1}a^{p-1-k}b^{k}
\end{equation*}
and Euler's formula we get
\begin{gather*}
\sin^2(nmx) = \left(\dfrac{e^{inmx}-e^{-inmx}}{2i}\right)^{2} =\dfrac{\left(e^{inx}\right)^{m}-\left(e^{-inx}\right)^{m}}{2i}\cdot \dfrac{\left(e^{imx}\right)^{n}-\left(e^{-imx}\right)^{n}}{2i}=\\[2ex]
\dfrac{e^{inx}-e^{-inx}}{2i}\dfrac{e^{imx}-e^{-imx}}{2i}\cdot\sum_{k=0}^{m-1}e^{inx(m-1-k)}e^{-inxk}\cdot \sum_{j=0}^{n-1}e^{imx(n-1-j)}e^{-imxj}=\\[2ex]
\sin(nx)\sin(mx)\cdot \sum_{k=0}^{m-1}\sum_{j=0}^{n-1}e^{ix(2nm-n-m-2kn-2jm)}
\end{gather*}
Thus
\begin{gather*}
\cos((n-m)x)\dfrac{\sin^2(nmx)}{\sin(nx)\sin(mx)}=\\[2ex]\dfrac{e^{i(n-m)x}+e^{-i(n-m)x}}{2}\cdot\sum_{k=0}^{m-1}\sum_{j=0}^{n-1}e^{ix(2nm-n-m-2kn-2jm)}=\\[2ex]
\dfrac{1}{2}\cdot\sum_{k=0}^{m-1} \sum_{j=0}^{n-1}e^{ix(2nm-2m-2kn-2jm)}+ \dfrac{1}{2}\cdot\sum_{k=0}^{m-1} \sum_{j=0}^{n-1}e^{ix(2nm-2n-2kn-2jm)}.\tag{1}
\end{gather*}
However,
\begin{equation*}
\dfrac{1}{\pi}\int_{0}^{\pi}e^{i2px}\, \mathrm{d}x = \begin{cases}
0\text{ if } p\neq 0 \text{ and integer },\\
1 \text{ if } p=0.
\end{cases}
\end{equation*}
Now we integrate the two double sums in(1). By symmetry the two integrals will have the same value.
The integral
\begin{equation*}
\dfrac{1}{\pi}\int_{0}^{\pi}e^{ix(2nm-2m-2kn-2jm)}\, \mathrm{d}x = 1
\end{equation*}
if and only if
\begin{gather*}
nm-m-kn-jm=0 \tag{2}
\end{gather*}
which is a linear diophantine equaion.
Put $n= pd, m=qd$ where $d=\rm{gcd}(n,m)$. Then we can write (2) as
\begin{equation*}
kp+jq=pqd-q.
\end{equation*}
All solutions are
\begin{equation*}
\begin{cases}
k=qd-rq\\
j=-1+rp
\end{cases}
\end{equation*}
where $r$ is an integer. But $0 \le k \le m-1$ and $0\le j \le n-1$. Thus
\begin{equation*}
\begin{cases}
0\le qd-rq \le qd-1\\
0 \le -1+rp \le pd -1
\end{cases} \Longleftrightarrow
\begin{cases}
1\le rq \text{ and } r\le d\\
1 \le rp \text{ and } r\le d.
\end{cases}
\end{equation*}
Consequently we find $d$ solutions to (2).
If we integrate (1) we get
\begin{equation*}
\dfrac{1}{2}d+\dfrac{1}{2}d = \rm{gcd(n,m).}
\end{equation*}