Convert string to pitch notation in javascript

214 views Asked by At

I have for ex. string t0 means in treble clef on 0 position. In pitch notation is B4

So t1 = C5 , t-1 = A4 , t-2 = G4...

Should I create every single string in array to map all notes, or could be done easily? Thx.

2

There are 2 answers

2
Zevgon On BEST ANSWER

Is this what you're looking for?

let curT = -22;
const letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
let result = {};

for (let i=0; i < 52; i++) {
  const letNum = `${letters[i % 7]}${(parseInt(i / 7) + 1)}`;
  result[`t${curT}`] = letNum;
  curT += 1;
}
console.log(result);

0
csebal On

My musical theory is definitely not up to standards either, but if I get what you are asking for, it is more about how to approach the identification of the note itself and the transformation into a different format.

You definitely do not need to map all notes. I would go about by creating an array of notes, then calculating the octave and the offset from the base note. From there it is a simple array lookup and string concatenation to get the octave going.

Something like this:

var notes = ['B','C','D','E','F','G','A'];
function stringtopitch(input)
{
    // get the base value
    num = parseInt(input.substr(1));
    mod = 0
    // correct for octaves as needed and identify them
    while (num < 0) { num+=7; mod -=1; }
    while (num > 7) { num-=7; mod +=1; }
    return notes[num] + (mod+4);
}