Skip to main content

Using @webgamekit/bass-midi

@webgamekit/bass-midi turns a bass guitar plugged into an audio interface into MIDI notes, live, in the browser. It is the library behind the editor's Instrument tab, described in Bass to MIDI together with how the detection works inside.

This page covers what you need to build on it: setting it up, how notes map to MIDI, how one note relates to several places on the fretboard, the whole API, and recipes for logging, recording, practising and a rhythm game.

Bass or guitar​

The library listens for a 4-string bass unless told otherwise. For a 6-string guitar in standard tuning, MIDI 40 (E2) to 88 (E6), pass instrument: 'guitar' to createBassMidi, and the same value to the position, tuner and string helpers:

await createBassMidi({ instrument: 'guitar', onNoteOn: (note) => console.info(note.midi) })

fretPositions(64, 'guitar') // E24, A19, D14, G9, B5, e0
tuneString(329.63, 440, 'guitar') // the high e string

Like the bass, a guitar is heard one note at a time, so chords are not detected. isInstrument(value) checks a value from outside, such as a query parameter.

Install and requirements​

pnpm add @webgamekit/bass-midi
  • A bundler that understands new URL('./file', import.meta.url), such as Vite, webpack 5 or Rollup. The package ships its AudioWorklet as a separate file and finds it that way; the WebAssembly module is inlined, so there is nothing else to copy.
  • A secure page (https:// or http://localhost), because the browser only grants microphone input there.
  • A click or key press before starting. Browsers only start audio after the user interacts with the page, so call createBassMidi from a button handler.
  • Called without a tap, as a host that starts listening by itself does, a phone keeps the audio suspended. The next tap or key press anywhere on the page resumes it. resumeOnTap(audioContext) does the same for an audio context of your own.
  • A browser with AudioWorklet: current Chrome, Edge, Firefox and Safari all have it.
  • A clean signal. Plug the bass into an audio interface rather than holding it near a microphone. The library turns off the browser's echo cancellation, noise suppression and automatic gain, which would otherwise smear the pitch.

Quick start​

import { createBassMidi } from '@webgamekit/bass-midi'

startButton.addEventListener('click', async () => {
const bassMidi = await createBassMidi({
onNoteOn: (note) => console.info('on', note.midi, note.time),
onNoteOff: (note) => console.info('off', note.midi, note.duration),
onLog: (line) => console.info(line)
})
stopButton.addEventListener('click', () => bassMidi.stop(), { once: true })
})

Each finished note logs a line such as 12.345s A2 (45) vel 0.72 dur 0.410s.

Notes and MIDI​

How a pitch becomes a MIDI number​

MIDI numbers count semitones, with A4 (440 Hz) as 69 and middle C (C4) as 60. The library reads the pitch in hertz and converts it:

midi = round(69 + 12 × log2(frequency / 440))

Before rounding it averages a few readings, so a note played a little sharp still lands on the right semitone. The 440 is the a4Hz parameter, for a band that tunes elsewhere.

A 4-string bass in standard tuning covers MIDI 28 to 67:

StringOpen noteMIDIFrequency12th fret24th fret
E (4)E12841.20 HzE2, MIDI 40E3, MIDI 52
A (3)A13355.00 HzA2, MIDI 45A3, MIDI 57
D (2)D23873.42 HzD3, MIDI 50D4, MIDI 62
G (1)G24398.00 HzG3, MIDI 55G4, MIDI 67

Names use scientific pitch with sharps: midiToNoteName(37) is C#2. Notes outside 28 to 67 are not reported.

Note that a bass is written an octave above where it sounds. Sheet music for bass shows the open E on the first ledger line below the bass clef staff, which is E2 on paper; the string really sounds E1. This library uses the pitch you hear, so the open E is MIDI 28, which is also what a DAW expects for a bass track.

Timing​

Every time is in seconds on the AudioContext clock (bassMidi.audioContext.currentTime).

  • onNoteOn fires about 20 ms after a pluck on the high strings and about 50 ms after a pluck on the low E: the detector needs one and a half cycles of the wave to read its pitch, and a low E cycle lasts 24 ms. The event's time is still the moment of the pluck, worked out from the level rise, so timing can be scored precisely even though the event arrives late.
  • onNoteOff fires when the note ends: the string is muted, a new pluck starts, or the pitch moves to another note (a slide or a hammer-on). It carries the duration.

Velocity​

velocity runs from 0 to 1, from how loud the pluck was: the gate level maps to 0 and full scale (0 dBFS) to 1, never below 0.05. Multiply by 127 and round for a MIDI velocity byte.

One note at a time​

The detector is monophonic: it follows the strongest single note. Chords and double stops come out as one of their notes, or as nothing.

One note, several frets​

On the instrument​

Each fret raises a string by one semitone, and in standard tuning (E A D G) each string is five semitones above the one below. So moving up one string and back five frets gives the same note, and most notes can be played in two, three or four places. A2, MIDI 45, is on all four strings:

PositionStringFretSound
E17E17Thick string, short vibrating length: darker, tight
A12A12
D7D7
G2G2Thin string, nearly full length: brighter, rounder

The pitch is identical; the tone changes a little, and so does what the hand has to do. Players pick the place that keeps the hand still, keeps a line on one string, or gives the tone they want.

Positions are written as in tablature: the string's letter, then the fret, with 0 for an open string. E17 is the 17th fret of the E string; A0 is the open A string. Read this way, A2 means the A string at the 2nd fret (which sounds B1), not the note A2. That is why the Instrument tab shows a note as its position and its MIDI number (E17 · MIDI 45) rather than its note name.

In the code​

fretPositions(midi) lists every place a note can be played, low string first. For each open string it subtracts the open string's MIDI number from the note and keeps the result when it is a fret from 0 to 24:

fretPositions(45)
// [
// { stringIndex: 0, fret: 17 }, // E17
// { stringIndex: 1, fret: 12 }, // A12
// { stringIndex: 2, fret: 7 }, // D7
// { stringIndex: 3, fret: 2 } // G2
// ]

stringIndex 0 is the lowest string. INSTRUMENTS.bass.openStringMidi ([28, 33, 38, 43]) and FRET_COUNT (24) are the tuning and neck it uses.

Which one did the player use? A pitch reading cannot tell: E17 and G2 produce the same frequency. So the library offers one default, lowestStringPosition(midi), the position on the lowest string that reaches the note (E17 for A2). It matches a player working up one string, and is the same answer every time, which a game or a lesson can rely on. Show fretPositions(midi) when you want every option, as the Instrument tab's All frets does.

Guessing the string from the sound (prototype)​

A stiff string's overtones sit sharp of exact multiples of its pitch: partial n rings at n · f0 · sqrt(1 + B · n²). The inharmonicity B is large on a thick string stopped short and small on a thin, long one, so A2 at E17 has a B roughly five times that of A12, which has about five times that of D7, and so on. The detector measures it:

  1. Once 85 ms of a note have been heard, counted from the pluck (the pitch window already holds its start), the Rust code searches for partials 1 to 12 near where the partials found so far predict them, refines each peak between grid points, and fits B by least squares of (f_n / n)² against n². Fewer than four clear partials, or a note that ends sooner, gives 0.
  2. onInharmonicity receives that B as soon as it is measured, while the note still rings, and the note off carries it again as inharmonicity on the BassNoteEvent.
  3. A calibration fixes B along the neck: the player plucks each open string and its 12th fret (stringCalibrationSteps()), and buildStringModel(measurements) fits, per string, B(fret) = B(open) · e^(growth · fret). With only the open strings it assumes the ideal growth, fourfold over 12 frets.
  4. guessStringPosition(midi, inharmonicity, model) picks the position whose predicted B is closest on a log scale, with a confidence from 0 to 1. It falls back to lowestStringPosition with confidence 0 when the note was too short or the value sits between two strings.
const model = buildStringModel(measurements) // after the eight calibration plucks
const guess = guessStringPosition(note.midi, note.inharmonicity ?? 0, model!)
formatBassNote(note.midi, [guess!.position]) // such as "A12 · MIDI 45"

The Instrument tab is compact by default, with the fretboard, the calibration notes and the input; add ?advanced=1 to the editor's address (strudel.cnotv.xyz/?tab=instrument&advanced=1) for the whole tab with the log, export, import and delay. It does this for the note shown, the fretboard and the log, always: it starts with a default calibration (the open strings and the 12th frets of one bass), so a string is guessed from the first note, and your own measurements replace it note by note. A note appears only once its string has been guessed, so it never jumps from one string to another. With All frets on, the other places the note could be played are drawn fainter. The Calibration collapsible, always on the tab and remembered open or closed, holds everything about it: the status, one button per pluck (E0, E12, A0 and so on): choose one, pluck that note within 3 seconds and it is measured and remembered, with its B shown on the button. Click it again to stop early, or later to measure that one note again without touching the others. Its Delay slider sets stringGuessMs: lower shows each note sooner, higher guesses its string more precisely. Export saves the calibration and its delay as bass-calibration.json, and Import loads one back, for another browser or after clearing site data. A calibration that was saved empty stays empty and asks to be measured; nothing saved means the default.

A game can show this tab and read the same calibration: StrudelBassTab is exported from @webgamekit/strudel-editor, and readBassStringSetup() from its helpers returns the saved model (null until every open string has a measurement) and stringGuessMs. See Embedding the Strudel editor.

How well it works: on synthetic stiff strings (partials exactly on the formula, higher ones decaying faster, light noise) B comes back within 5 % from 2e-5 to 2e-3 (15 % for the G string's B with a pitch glide after the pluck), and A2 is put on the right string every time. That is the easy case. A real bass still has to show how much its partials stray from the formula (the winding, the bridge and nut, the pickup's position, fret buzz), how much B scatters between two plucks of the same note, and whether the thin strings' small B (around 2e-5 on the G) stands clear of that scatter. Until it is checked on a real instrument, treat a guess as a hint, and expect the low frets of the D and G strings to be the first to blur.

formatFretPosition({ stringIndex: 0, fret: 17 }) gives E17, and formatBassNote(midi, positions, withMidi) the label the Instrument tab shows:

formatBassNote(45, [lowestStringPosition(45)!]) // "E17 · MIDI 45"
formatBassNote(45, fretPositions(45), false) // "E17, A12, D7, G2"
formatBassNote(20, [], false) // "MIDI 20", no string reaches it

API​

Listening​

createBassMidi(options?) → Promise<BassMidiHandle> opens the input, asks for microphone permission if needed, and starts detecting.

OptionTypeMeaning
instrument'bass' | 'guitar'Whose pitch range to listen for; bass if unset
streamMediaStreamAudio to listen to instead of an input, such as a test signal
deviceIdstringAn input from listAudioInputs(); the default input if not
inputChannelnumberWhich input of the interface the bass is on, from 0
paramsPartial<BassMidiParameters>Starting calibration, see below
onNoteOn(note: BassNoteOnEvent) => voidA note was recognised: { midi, time, velocity }
onNoteOff(note: BassNoteEvent) => voidA note ended: { midi, time, duration, velocity }
onInharmonicity(event: BassInharmonicityEvent) => voidAbout 85 ms after the pluck: { midi, time, inharmonicity }, 0 when unclear
onLog(line: string) => voidOne readable line per finished note
onPitch(frequency: number | null) => voidThe pitch in hertz about 50 times a second, null if silent
monitorVolumenumberVolume, 0 to 1, of the raw bass passed to the default output; 0 if unset

The handle:

MemberMeaning
audioContextThe AudioContext whose clock every time uses
inputChannelCountHow many channels the chosen input delivers
setParams(params)Changes calibration while listening
setMonitorVolume(volume)Changes the monitor volume while listening
stop()Stops listening, releases the input and closes the context

listAudioInputs() → Promise<MediaDeviceInfo[]> lists audio inputs. Their names are empty until the page has microphone permission, so list them again after createBassMidi starts.

Calibration (BassMidiParameters)​

ParameterDefaultMeaning
gateDb-45Level a silent string must rise above to start a note
releaseDb-55Level a sounding note must fall below to end
clarity0.8How periodic the signal must be to count as a pitch (0 to 1)
stableHops35 ms readings that must agree before a note starts
a4Hz440Tuning reference
minNoteMs60How long a note lasts before a re-pluck or slide can end it
repluckJumpDb6Level rise that counts as a new pluck of the same note
stringGuessMs85How long a note is measured from its pluck before its inharmonicity is reported, 40 to 400: longer is more precise but later

Raise the gate if string noise or hum starts notes; lower it if soft notes are missed.

Notes, positions and tuning​

Each function that depends on the strings takes the instrument as its last argument, bass if left out.

FunctionReturns
midiToNoteName(midi)"C#2"
isInstrument(value)Whether the value is 'bass' or 'guitar'
fretPositions(midi, instrument?)Every FretPosition for the note, low string first
lowestStringPosition(midi, instrument?)The position on the lowest string that reaches it, or null
stringCalibrationSteps(instrument?)The calibration plucks: each open string and its 12th fret
buildStringModel(measurements, instrument?)B along the neck per string, or null until every open string
guessStringPosition(midi, b, model, instrument?){ position, confidence } from a note's measured inharmonicity
formatFretPosition(position, instrument?)"E17"; a guitar's high E string is e
formatBassNote(midi, positions, withMidi?, instrument?)"E17 · MIDI 45", "E17, A12, D7, G2" or "MIDI 20"
tuneString(frequency, a4Hz?, instrument?){ stringIndex, stringName, cents } for the nearest open string
formatNoteLog(note, label?)"12.345s A2 (45) vel 0.72 dur 0.410s"
alignNotesToStart(notes)The same notes, timed from the first one

Lower level​

ExportUse
createWasmDetector(wasmModule, sampleRate, instrument?)The detector without the browser audio graph: feed it samples yourself, for instance to analyse a recording
createNotePairer()Turns the detector's on and off events into finished notes
INSTRUMENTS, FRET_COUNTThe tuning and neck the position functions use

Every type is exported too: BassNoteEvent, BassNoteOnEvent, BassMidiOptions, BassMidiHandle, BassMidiParameters, FretPosition, StringTuning and the rest.

Recipes​

Log what you play​

The quick start above is the whole recipe. To show positions instead of note names, label each note yourself:

import {
createBassMidi,
formatBassNote,
formatNoteLog,
lowestStringPosition
} from '@webgamekit/bass-midi'

await createBassMidi({
onNoteOff: (note) => {
const position = lowestStringPosition(note.midi)
console.info(formatNoteLog(note, formatBassNote(note.midi, position ? [position] : [])))
}
})
// 0.515s E0 · MIDI 28 vel 0.74 dur 0.704s

Record a take and save it​

Collect finished notes, then save them as JSON or as a standard MIDI file. The MIDI file here uses @tonejs/midi, which takes times in seconds.

import { Midi } from '@tonejs/midi'
import { alignNotesToStart, createBassMidi, type BassNoteEvent } from '@webgamekit/bass-midi'

const take: BassNoteEvent[] = []
const bassMidi = await createBassMidi({ onNoteOff: (note) => take.push(note) })

// later, when the player stops
await bassMidi.stop()
const notes = alignNotesToStart(take)

const json = JSON.stringify(notes) // [{ "midi": 28, "time": 0, "duration": 0.7, "velocity": 0.74 }, ...]

const midi = new Midi()
midi.header.setTempo(120) // set before adding notes: seconds become ticks at this tempo
const track = midi.addTrack()
track.name = 'bass'
notes.forEach(({ midi: key, time, duration, velocity }) =>
track.addNote({ midi: key, time, duration, velocity })
)
const bytes = midi.toArray() // a .mid file, ready to download or upload

The Instrument tab's Download MIDI and Copy JSON do exactly this. The tempo only sets the grid a DAW shows; the notes keep their real timing.

Practise​

Tune up. Smooth the pitch over a few readings and compare it with the nearest open string:

import { createBassMidi, tuneString } from '@webgamekit/bass-midi'

const readings: number[] = []
await createBassMidi({
onPitch: (frequency) => {
if (frequency === null) return
readings.splice(0, readings.length, frequency, ...readings.slice(0, 4))
const median = [...readings].sort((a, b) => a - b)[Math.floor(readings.length / 2)]
const { stringName, cents } = tuneString(median)
showTuner(stringName, Math.round(cents)) // in tune within about ±3 cents
}
})

Check an exercise. Compare each note with what was asked. Compare MIDI numbers, not positions: the player may use any string.

import { createBassMidi, formatBassNote, fretPositions } from '@webgamekit/bass-midi'

const exercise = [28, 31, 33, 35] // E1, G1, A1, B1
let step = 0
await createBassMidi({
onNoteOn: (note) => {
const correct = note.midi === exercise[step]
showResult(correct, formatBassNote(exercise[step], fretPositions(exercise[step]), false))
if (correct) step = (step + 1) % exercise.length
}
})

A rhythm game​

A rhythm game asks for notes at given times and scores how close the player gets. Three things matter: the clock, the latency, and the matching.

Use one clock. Note times are on bassMidi.audioContext's clock. Schedule the backing track and the falling notes on the same clock, so a chart time and a played time can be subtracted directly. If the game already has its own AudioContext, convert with the difference between the two contexts' currentTime taken at the same moment.

Score onNoteOn, by its time. onNoteOn arrives 20 to 50 ms after the pluck, but its time is the pluck itself, so the score is fair even on the low E. Use the arrival only to show feedback; never score the arrival time.

Calibrate once. Interfaces and cables add a few milliseconds before the sound reaches the browser. Ask the player to pluck along to a click a few times, average how late the notes' time is, and subtract that offset from every note.

import { createBassMidi, type BassNoteOnEvent } from '@webgamekit/bass-midi'

interface ChartNote {
midi: number
time: number
hit: boolean
}

const PERFECT_SECONDS = 0.05
const GOOD_SECONDS = 0.12

const createScorer =
(chart: ChartNote[], songStart: number, inputOffset: number) => (played: BassNoteOnEvent) => {
const playedTime = played.time - inputOffset - songStart
const target = chart
.filter((note) => !note.hit && note.midi === played.midi)
.find((note) => Math.abs(note.time - playedTime) <= GOOD_SECONDS)
if (!target) return 'miss'
target.hit = true
return Math.abs(target.time - playedTime) <= PERFECT_SECONDS ? 'perfect' : 'good'
}

// The callback only runs once notes arrive, after score below exists.
const bassMidi = await createBassMidi({ onNoteOn: (note) => showJudgement(score(note)) })
const songStart = bassMidi.audioContext.currentTime + 2 // start the backing track here too
const score = createScorer(chartFromMidiFile, songStart, calibratedOffset)

A chart can come from any MIDI file (a bass track exported from a DAW, or a Strudel pattern through the editor's MIDI export), since its notes carry the same midi and time in seconds. Show where to play each note with lowestStringPosition on a fretboard or a tab lane; accept any string when scoring, as above, because the player may choose another position.

Limits​

  • One note at a time.
  • A 4-string bass (E1 to G4) or a 6-string guitar (E2 to E6), in standard tuning. A 5-string bass or a drop tuning needs other open strings, and a low one a longer analysis window.
  • The string a note was played on is a choice, not a measurement, unless the string guessing prototype is calibrated; even then it is untested on a real bass, as explained above.