map pitch to note in javascript

To map pitch to note in JavaScript, we need to know the formula for converting MIDI note numbers to their corresponding note names.

First, let's define the function that will handle the conversion of MIDI note numbers to note names:

index.tsx
function midiToNoteName(midiNote) {
  const noteMapping = [
    'C', 'C#', 'D', 'D#', 'E', 'F',
    'F#', 'G', 'G#', 'A', 'A#', 'B'
  ];
  const octave = Math.floor(midiNote / 12) - 1;
  const noteIndex = midiNote % 12;

  return noteMapping[noteIndex] + octave.toString();
}
276 chars
11 lines

This function takes a MIDI note number as input and returns a string with the corresponding note name. In order to use it, we need to know what MIDI note number corresponds to the pitch we're interested in.

We can calculate the MIDI note number from the pitch using the following formula:

index.tsx
const midiNote = Math.round(69 + 12 * Math.log2(frequency / 440));
67 chars
2 lines

In this formula, frequency is the pitch we want to convert to a MIDI note number. The value 69 represents the MIDI note number for A4, which is defined to be equal to 440 Hz. We add 12 times the base-2 logarithm of the frequency ratio between the desired pitch and A4 to get the MIDI note number.

Putting the two together, we get the following code to map a frequency value to a note name:

index.tsx
const frequency = 440; // change this to the desired frequency
const midiNote = Math.round(69 + 12 * Math.log2(frequency / 440));
const noteName = midiToNoteName(midiNote);

console.log(noteName); // will output 'A4'
217 chars
6 lines

This code will output the note name corresponding to the given frequency value. Note that this method assumes that equal temperament tuning is used.

gistlibby LogSnag