surmenage · · seedling · audio · python · tools · music
singing practice in semitones, against a separated vocal
I wanted something to sing along to that would tell me, concretely, where I was flat. Karaoke apps give you a backing track and a score; I wanted the original vocal’s pitch drawn as a line and my own voice drawn on top of it. So I wrote a small desktop tool, about 1,250 lines of Python in five files, that does that for any YouTube URL. It is a personal tool, not a product, and it has no README. This note is read off the code.
what you see
The window has a URL box and a “Load song” button, a dropdown of previously loaded songs, mic and speaker pickers, and a small level bar for the microphone input. The main area is a pyqtgraph plot with time on the x axis and pitch on the y axis, fixed to MIDI notes 36 to 84 (C2 to C6). The original vocal is a thick blue line. My live pitch is a thinner red line. A dashed white line marks the playhead.
The view scrolls with the playhead, which sits 35% of the way across a 6 second window, so you see a little of what just happened and most of what is coming. Dragging the x axis turns off the following; a button turns it back on. Below the plot are three readouts: the target note at the current time, the note I am singing, and a delta in cents, coloured green under 20 cents, amber under 50, red beyond. There is also a session range label that tracks the lowest and highest note I have hit since loading the song.
Transport is what you would expect: play/pause, skip back and forward 5 seconds, restart, a scrubber, and an A to B loop with “Set A”, “Set B” and a checkbox. Two sliders mix the instrumental and the original vocal. The vocal gain starts at 0 and the instrumental at 0.9, so by default it is a plain karaoke track.
the pipeline
Everything slow happens in a QThread worker so the window stays responsive. Three stages:
download.pyusesyt-dlpto fetch the best audio and convert it to a 192 kbps mp3 atsongs/<slug>/source.mp3. Playlist URLs are treated as the single video they point at. Before any network call,library.pyextracts the 11-character video id from watch,youtu.be, embed, shorts and live URLs, and checks alibrary.jsonindex. If the id is there and the mp3 still exists, nothing is downloaded.separate.pyshells out topython -m demucs.separatewith thehtdemucsmodel and--two-stems vocals, which givesvocals.wavandno_vocals.wav. It writes to a temporary directory, moves the two files next to the mp3, and deletes the rest. If both files already exist it returns immediately. The comment in the code calls htdemucs state of the art; I have not benchmarked it against anything, so take that as the reason I picked it, not a finding.pitch.pycomputes the reference contour fromvocals.wavonce and caches it aspitch.npznext to the audio. The cache stores a version number and the wav’s modification time, and is recomputed if either is stale or the file will not load.
The second load of a song hits all three caches; the first is dominated by Demucs on CPU (the status line says it can take a minute, which is the code’s estimate, not mine).
the reference contour
The reference uses librosa.pyin at 22,050 Hz, with a frame length of 2048 samples and a hop of 256 samples, so one point every 11.6 ms. The search range is C2 to C7 (about 65 Hz to 2093 Hz). Unvoiced frames come back as NaN, and the plot is drawn with connect="finite", so gaps in the voice are gaps in the line rather than a line dragged through silence.
pYIN is slow, which is fine here because it runs once per song and is cached. The module docstring explains the split: pYIN offline for accuracy, plain YIN online for speed.
Running on the Demucs output rather than the full mix is the point. Whether the separated vocal is clean enough depends on the song, and I have not measured how much backing vocals or reverb bleed through.
the live tracker
The microphone is opened at the device’s own default sample rate and channel count, not at 22,050 Hz mono. The code comment says why: some mics will not open at the preferred 22,050 Hz mono and otherwise deliver no callbacks. Stereo input is averaged to mono. Callbacks on macOS can be as small as 256 to 512 samples, so each callback shifts new samples into a rolling 4096-sample buffer.
The GUI timer fires every 33 ms. On each tick, if any audio arrived, the code takes the latest 2048 samples from the buffer and calls detect_live:
- fewer than 1024 samples: no pitch
- RMS below 0.005: no pitch, treated as silence or noise floor
- otherwise
librosa.yinover the same C2 to C7 range, then the median of the per-frame estimates in that window
The median is there to suppress octave errors, per the comment. Note that detect_live is given the mic’s own sample rate, so frequencies are right whatever the device runs at; the reference contour is always at 22,050.
the comparison
All comparison is done in semitones, using 69 + 12 * log2(f / 440) to turn Hz into fractional MIDI note numbers. Both lines share that axis, so “how far off am I” is a vertical distance on the plot.
The reference lookup is searchsorted of the current time into the reference time array. “Current time” is the playback position when music is playing. When paused, it is the position at the moment of pausing plus wall-clock time elapsed, so the playhead stays still while the live curve sweeps rightward across the reference. That gives a practice mode: pause, then sing a phrase against the static contour. Pressing play, pausing, or seeking clears the live history so old attempts do not overlap.
Before plotting, each live estimate goes through octave_snap. If my pitch is a whole octave or more away from the reference at that moment, it is shifted by whole octaves to land nearest the reference. The docstring says it cures YIN’s half and double errors while letting octave-displaced singing register within 6 semitones. Reading the code, the shift is -round(semitones / 12), so it triggers only once the difference exceeds 6 semitones, and then moves the pitch by whole octaves. The docstring’s “7” and the code’s 6 do not quite agree. A consequence worth stating: it also silently removes real octave differences, such as singing an octave below a female vocal, because that is exactly what it is designed to hide. That may be what you want when practising across voice types, but it is an implicit choice.
The plotted live line additionally passes through a 3-point median filter over the visible history, which collapses single-frame spikes. NaN neighbours leave the centre sample alone.
what is rough
- The delta shown in cents is not a comparison with the target.
cents_offmeasures how far my pitch is from my own nearest semitone. If I sing a clean C when the target is D, it reads about 0 cents and green. The plot shows the real error; the number does not. This is the largest flaw and the thing I would change first. - There is no tuning meter in the sense of a needle. What exists is a level bar for input volume and the coloured cents text.
- Latency is deliberately generous. Both streams are opened with
latency="high"and a PortAudio-chosen block size, which the comments describe as about 30 ms of lag traded for not starving the audio thread. Combined with a 33 ms timer and a 2048-sample analysis window (about 93 ms at 22,050 Hz), the red line lags my voice by a visible amount. I have not measured it. - The reference lookup uses the time on the playback clock, and the live estimate is stamped with that same time. Any output or input latency shifts my line relative to the reference by that much. Nothing compensates for it.
- The tool depends on
yt-dlpworking against YouTube as it currently behaves; the download code enables a remote challenge-solver component that needs deno or node installed. - No tests.
- audio
- python
- tools
- music