DEV Community

Cover image for Fixing octave ghost notes when running Spotify Basic Pitch in the browser
Hu Kosan
Hu Kosan

Posted on

Fixing octave ghost notes when running Spotify Basic Pitch in the browser

Drop an acoustic piano recording or an iPhone voice memo into a raw audio-to-MIDI converter and you almost always get the same mess. The main chords come through okay, then the piano roll fills up with tiny 20 to 60 ms dots sitting an octave above the actual notes.

Acoustic pianos and human voices carry strong 2nd and 3rd harmonics. When a neural pitch tracker runs on generic thresholds, those overtones and sustain-pedal tails cross the activation line for a couple of frames and turn into stray notes. Cleaning them out by hand in FL Studio or Logic takes longer than just replaying the part.

I got tired of doing that cleanup inside a DAW, and I did not want to upload unfinished demos to cloud sites that cut free clips off at 60 seconds. So I put together Audio-to-MIDI.net on top of Spotify's Apache-2.0 Basic Pitch model (@spotify/basic-pitch + TensorFlow.js). Everything decodes and runs locally in the browser tab, and you can filter out ghost notes on a Canvas piano roll before exporting the .mid file.

A few practical things I ran into while building it.

1. Resampling to 22,050 Hz mono with Web Audio

Basic Pitch expects single-channel PCM audio at 22,050 Hz. If you pass a normal 44.1 kHz or 48 kHz stereo MP3, WAV, or M4A straight from a file input, evaluateModel throws a sample-rate or channel error.

You do not need FFmpeg WASM for this. OfflineAudioContext handles both downmixing to mono and resampling to 22,050 Hz right in the browser:

const TARGET_SAMPLE_RATE = 22050;

export async function decodeAndResampleFile(file: File): Promise<AudioBuffer> {
  const arrayBuffer = await file.arrayBuffer();
  const decodeCtx = new AudioContext();
  let decoded: AudioBuffer;
  try {
    decoded = await decodeCtx.decodeAudioData(arrayBuffer.slice(0));
  } finally {
    await decodeCtx.close().catch(() => {});
  }

  const targetLength = Math.max(1, Math.ceil(decoded.duration * TARGET_SAMPLE_RATE));
  const offlineCtx = new OfflineAudioContext(1, targetLength, TARGET_SAMPLE_RATE);

  const monoBuffer = offlineCtx.createBuffer(1, decoded.length, decoded.sampleRate);
  const monoData = monoBuffer.getChannelData(0);
  const weight = 1 / decoded.numberOfChannels;

  for (let ch = 0; ch < decoded.numberOfChannels; ch++) {
    const channelData = decoded.getChannelData(ch);
    for (let i = 0; i < channelData.length; i++) {
      monoData[i] += channelData[i] * weight;
    }
  }

  const source = offlineCtx.createBufferSource();
  source.buffer = monoBuffer;
  source.connect(offlineCtx.destination);
  source.start(0);

  return offlineCtx.startRendering();
}
Enter fullscreen mode Exit fullscreen mode

The self-hosted TF.js weights (model.json plus the single shard binary) weigh about 917 KB total, so they download once and stay cached. On a normal laptop this handles clips up to 10 minutes without needing a server GPU.

2. Caching raw frames and the outputToNotesPoly mutation bug

Running TF.js inference takes a few seconds, while turning the output matrices into MIDI note events takes a few milliseconds. If you keep the raw { frames, onsets, contours } arrays in memory, you can let the user move onset threshold, sustain threshold, min note length, frequency bounds, and a velocity gate live on the piano roll without running inference again.

One thing that bit me while reading @spotify/basic-pitch/src/toMidi.ts: outputToNotesPoly() calls constrainFrequency(onsets, frames, maxFreq, minFreq), which mutates frames and onsets in place. If you pass your cached arrays straight in and lower maxFreq once, those upper frequency bins stay zeroed out permanently even when you drag the slider back up.

Cloning the rows before each decode pass fixes it, and minNoteLen has to be converted from milliseconds into model frames (Math.floor(22050 / 256) = 86 fps):

const ANNOTATIONS_FPS = Math.floor(22050 / 256);

const framesCopy = raw.frames.map((row) => row.slice());
const onsetsCopy = raw.onsets.map((row) => row.slice());
const minNoteLenFrames = Math.max(1, Math.round((params.minNoteLenMs / 1000) * ANNOTATIONS_FPS));

const rawEvents = outputToNotesPoly(
  framesCopy,
  onsetsCopy,
  params.onsetThreshold,
  params.frameThreshold,
  minNoteLenFrames,
  true,
  params.maxFreqHz,
  params.minFreqHz,
  params.melodiaTrick,
  11
);
Enter fullscreen mode Exit fullscreen mode

Also worth noting: evaluateModel fires its onComplete callback once per 2-second window batch rather than once at the end, so you have to push chunks into an accumulator array as batches finish.

3. Different recordings need different defaults

One preset does not work well for everything:

  • On piano recordings, clamping low frequencies at 60 or 80 Hz cuts off left-hand bass notes. Opening the band to the full 88-key range (27.5 Hz to 4,186 Hz) keeps the bass intact, and nudging the frame threshold up trims muddy sustain-pedal tails.
  • On lossy 128 to 192 kbps MP3s, compression pre-echo triggers double hits right before sharp attacks. Starting with a stricter onset threshold (0.56) and a 110 ms minimum note floor removes most of that chatter.
  • On humming, vocals, or 808 basslines, polyphonic mode turns vocal formants into phantom chords. Locking the range to 80 to 1,100 Hz and running a monophonic pass (keeping only the loudest overlapping pitch and trimming the previous note tail right before the next onset) leaves a usable single lead track.

On the built-in 8.7-second piano chord sample, default polyphonic decoding gives 34 notes (F2 to E5). Flipping Monophonic Lock on drops it to 15 melody notes right away, and you can play the result back through a small Web Audio synth before exporting a .mid file with your DAW's BPM written into the header via @tonejs/midi.

Where it still falls short

Pitch-only models work well on solo piano, guitar, synth stems, bass, and dry vocal memos. If you drop a loud, mastered pop or rock mix with heavy drums into it, kick and snare transients will still bleed into the MIDI unless you split stems first.

If you want to poke at it without hunting for an audio file, there are three synthesized samples built into the page at Audio-to-MIDI.net, plus a side-by-side breakdown against Spotify's original demo at audio-to-midi.net/alternatives/basic-pitch-alternative.

Top comments (0)