Skip to content

Commit 432f198

Browse files
Refactor cents-per-octave constants using SEMITONES
1 parent 4bef8c2 commit 432f198

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

js/utils/musicutils.js

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -842,6 +842,19 @@ const DEGREES = _("1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th");
842842
*/
843843
const SEMITONES = 12;
844844

845+
/**
846+
* Number of cents per semitone in 12-TET tuning.
847+
* @constant {number}
848+
*/
849+
const CENTS_PER_SEMITONE = 100;
850+
851+
/**
852+
* Number of cents in an octave.
853+
* Derived from SEMITONES for future temperament support.
854+
* @constant {number}
855+
*/
856+
const CENTS_PER_OCTAVE = SEMITONES * CENTS_PER_SEMITONE;
857+
845858
/**
846859
* Array representing powers of 2.
847860
* @constant {number[]}
@@ -2883,18 +2896,20 @@ const frequencyToPitch = hz => {
28832896

28842897
// Calculate cents to keep track of drift
28852898
let cents = 0;
2886-
for (let i = 0; i < 10 * 1200; i++) {
2899+
// Standard tuning uses CENTS_PER_OCTAVE cents per octave.
2900+
2901+
for (let i = 0; i < 10 * CENTS_PER_OCTAVE; i++) {
28872902
const f = A0 * Math.pow(TWELVEHUNDRETHROOT2, i);
28882903
if (hz < f * 1.0003 && hz > f * 0.9997) {
2889-
cents = i % 100;
2890-
let j = Math.floor(i / 100);
2904+
cents = i % CENTS_PER_SEMITONE;
2905+
let j = Math.floor(i / CENTS_PER_SEMITONE);
28912906
if (cents > 50) {
2892-
cents -= 100;
2907+
cents -= CENTS_PER_SEMITONE;
28932908
j += 1;
28942909
}
28952910
return [
2896-
PITCHES[(j + PITCHES.indexOf("A")) % 12],
2897-
Math.floor((j + PITCHES.indexOf("A")) / 12),
2911+
PITCHES[(j + PITCHES.indexOf("A")) % SEMITONES],
2912+
Math.floor((j + PITCHES.indexOf("A")) / SEMITONES),
28982913
cents
28992914
];
29002915
}

0 commit comments

Comments
 (0)