Note
Go to the end to download the full example code.
Pitch tracking with YIN and pYIN
yin gives one estimate per frame. pyin adds a voiced or unvoiced decision
per frame, so silence is marked rather than given a meaningless pitch.
import matplotlib.pyplot as plt
import numpy as np
import audio_samples as aus
A vibrato tone around 220 Hz, then silence.
f0_yin = audio.yin(fmin=65.0, fmax=800.0)[0]
f0_pyin, voiced, _ = audio.pyin(fmin=65.0, fmax=800.0)
f0_pyin, voiced = f0_pyin[0], voiced[0]
frames = np.arange(f0_yin.size) * 512 / sr
fig, ax = plt.subplots(figsize=(7, 3.5))
ax.plot(frames, f0_yin, label="YIN", color="0.7")
ax.plot(frames, f0_pyin, label="pYIN (voiced frames)", lw=2)
ax.set(xlabel="Time (s)", ylabel="Frequency (Hz)", ylim=(0, 450), title="Pitch track")
ax.legend()

<matplotlib.legend.Legend object at 0x7efd0442bcb0>
pYIN marks the trailing silence as unvoiced and finds 220 Hz in the tone.
assert not voiced[-5:].any()
assert abs(np.nanmedian(f0_pyin) - 220.0) < 5.0
Total running time of the script: (0 minutes 0.257 seconds)