Currently developing a guitar tuning tool and facing some hurdles.
Striving to create a function that can take a musical note, an octave, and a direction (up or down), then produce a transposed note by a half step based on the traditional piano layout (i.e., transitioning from B to C will involve adjusting octaves).
The functionality should also handle sharps.
Some examples:
const tunedNoteUp = pitchShiftNoteByHalfStep({note: "B", octave: 3}, "up")
console.log(tunedNoteUp) // {note: "C", octave: 4}
const secondCase = pitchShiftNoteByHalfStep({note:"G#", octave: 4}, "up")
console.log(secondCase) // {note: "A", octave: 4}
const thirdCase = pitchShiftNoteByHalfStep({note: "A#", octave: 4}, "down")
console.log(thirdCase) // {note: "A", octave: 4}
Open to utilizing libraries but haven't found any suitable ones yet.
Current progress:
function pitchShiftNoteByHalfStep(note, octave, direction) {
const notes = [ 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'];
const index = notes.indexOf(note);
const newIndex = direction === 'up' ? index + 1 : index - 1;
const newNote = notes[newIndex >= 0 ? newIndex : 11];
const newOctave = (octave + Math.floor((newIndex + (direction === 'up' ? 0 : 11)) / 12));
return `${newNote}${newOctave}`
}
Encountering issues in certain scenarios like shifting G# upwards.
Thank you!