@tonaljs/midi

A collection of functions to work with midi numbers.
Usage
ES6:
import { Midi } from "tonal";
nodejs:
const { Midi } = require("tonal");
API
toMidi(note: string | number) => number | null
Given a note name or number, return the midi number. Midi numbers are always in range 0..127
Examples:
Midi.toMidi("C4");
Midi.toMidi("#");
Midi.toMidi(60);
Midi.toMidi("60");
Midi.toMidi(-1);
midiToFreq(midi: number, tuning = 440) => number
Given a midi number, return the frequency:
Examples:
Midi.midiToFreq(60);
Midi.midiToFreq(69);
Midi.midiToFreq(69, 443);
midiToNoteName(midi: number) => string
Given a midi number, returns a note name. The altered notes will have flats unless explicitly set with the optional useSharps
parameter.
Examples:
Midi.midiToNoteName(61);
Midi.midiToNoteName(61, { pitchClass: true });
Midi.midiToNoteName(61, { sharps: true });
Midi.midiToNoteName(61, { pitchClass: true, sharps: true });
midiToNoteName(61.7);
freqToMidi(freq: number) => number
Given a frequency in hertz, returns the midi number. The midi number can have decimals (with two digits precision)
Example:
Midi.freqToMidi(220);
Midi.freqToMidi(261.62);
Midi.freqToMidi(261);
pcset(set: number[] | string) => number[]
Return the pitch class set from a number of midi note numbers or pcset chroma.
A pitch class set in this Midi
package refers to a unique sorted collection of notes between 0 and 11 (that represents the pitch class of the note.
Example:
Midi.pcset([62, 63, 60, 65, 70, 72]);
Midi.pcset("100100100101");
You can read more about pitch classes on Note
module.
The string is a pitch class chroma, a string with a binary representation of a set. Read more about pitch class chroma in Pcset
module documentation.
pcsetNearest(set: number[] | string) => (midi: number) => number | undefined
Returns a function that finds the nearest midi note of a pitch class set. Can be used to constrain a note to a scale, for example:
const nearest = Midi.pcsetNearest(Scale.get("D dorian").chroma);
[60, 61, 62, 63, 64, 65, 66].map(nearest);
pcsetSteps(set: number[] | string, tonic: number) => (index: number) => number
Returns a function to map a pitch class set over any note. Given a tonic a pitch class set, step 0 means the first note, step 1 the second, and so on:
const steps = Midi.pcsetSteps(Scale.get("D dorian").chroma, 60);
[-2, -1, 0, 1, 2, 3].map(steps);
A similar function called pcsetDegrees
exists that just uses 1 as first note instead of 0 (more common in music theory books). See Scale.degrees
and Chord.degrees
for more information.