-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
491 lines (399 loc) · 16.7 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/*
Generalized N equal divisions of X microtonal pitch monitor.
*/
/// Any arbitrary frequency of any particular note in the scale.
let baseFreq = 440;
/// The number of equal divisions of the interval given by the repeatingInterval.
let steps = 22;
/// This number is the '2' in '12ED2', where it represents the just ratio of
/// the interval that will be divided by `steps` number of equal divisions.
let repeatingIntervalType = 2;
/// The root note of the scale to be highlighted is this many steps away from the given `baseFreq`
let rootNoteStepsFromBaseFreq = 0;
let scalePattern = [4, 3, 2, 4, 3, 4, 2];
/// The distance between two notes an octave apart on the screen in px.
/// The metric can be used as a zoom measure (higher px distance = more vertically zoomed in)
let pxDistanceBetweenOctaves = 700;
/// This number represents the number of octaves from the base frequency the bottom of the screen is.
let lowestDisplayedPitch = 0;
/// This number represents the number of octaves from the base frequency the top of the screen is.
let highestDisplayedPitch = lowestDisplayedPitch + window.innerHeight / pxDistanceBetweenOctaves;
let nFrequenciesToStore = Math.ceil(window.innerWidth / 2);
let frequencies = [];
const displayScrollSmoothing = 6;
const ampThreshold = -50;
/// A frequency will only be accepted if the average of the last n unfiltered frequencies is within a
/// factor of `frequencyDeviationThreshold` of the current frequency.
const frequencyDeviationThreshold = 1.6;
const nUnfilteredFrequenciesToStore = 15;
const centOffsetSmoothing = 12;
window.oncontextmenu = function (event) {
event.preventDefault();
event.stopPropagation();
return false;
};
$('#play')[0].oncontextmenu = function (e) {
e.preventDefault();
e.stopPropagation();
return false;
};
window.onload = ev => {
// Redirect to scale builder config if no config in the location hash.
if (location.hash.trim().length === 0) {
window.location.href = 'builder.html';
return;
}
$('#builder').click(() => {
window.location.href = `builder.html${location.hash}`;
});
{
let configStr = location.hash.substr(1);
let [divisionsStr, baseFreqStr, scaleStr, offsetStr] = configStr.split(",");
let [stepsStr, repeatingIntervalStr] = divisionsStr.split(/ed/i);
try {
steps = parseInt(stepsStr);
} catch (e) {
alert('Error parsing config: steps')
}
try {
repeatingIntervalType = eval(repeatingIntervalStr);
} catch (e) {
alert('Error parsing config: repeating interval')
}
try {
baseFreq = parseFloat(baseFreqStr);
} catch (e) {
alert('Error parsing config: base frequency')
}
try {
scalePattern = scaleStr.split('-').map(x => parseInt(x));
} catch (e) {
alert('Error parsing config: scale pattern')
}
let scalePatternSteps = scalePattern.reduce((a, b) => a + b);
if (scalePatternSteps !== steps) {
alert(`Scale pattern has ${scalePatternSteps} steps, expected ${steps} instead`);
}
try {
rootNoteStepsFromBaseFreq = parseInt(offsetStr);
} catch (e) {
alert('Error parsing config: root note offset')
}
console.log(steps, repeatingIntervalType, baseFreq, scalePattern, rootNoteStepsFromBaseFreq);
}
// This will contain the notes to be highlighted as 'white notes' of the scale.
// e.g. a 12ED2 major scale would make scaleNotes hold the value [0, 2, 4, 5, 7, 9, 11, 12]
let scaleNotes = [0];
scalePattern.forEach(x => {
scaleNotes.push(scaleNotes[scaleNotes.length - 1] + x);
});
let $cv = $('#cv')[0];
$cv.height = window.innerHeight;
$cv.width = window.innerWidth;
nFrequenciesToStore = Math.ceil(window.innerWidth / 2);
frequencies = new Array(nFrequenciesToStore).fill(baseFreq);
let ctx = $cv.getContext('2d');
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
let $freqtext = $('#freqtext');
let $centstext = $('#centstext');
let tuner = new Microphone();
// Contains the last few raw frequencies from the algorithm to test for high deviations.
let lastUnfilteredFrequencies = new Array(nUnfilteredFrequenciesToStore).fill(rootNoteStepsFromBaseFreq);
// Stores the closest tempered note that is picked up by the mic.
// Units are in steps from base frequency.
let correctNote = 0;
let AC = window.AudioContext || window.webkitAudioContext;
let actx = new AC();
let gain = actx.createGain();
gain.gain.value = 0;
gain.connect(actx.destination);
let osc = actx.createOscillator();
osc.type = 'triangle';
osc.frequency.value = baseFreq;
osc.connect(gain);
let oscStarted = false;
let $playBtn = $('#play');
$playBtn[0].onpointerdown = (e) => {
e.preventDefault();
if (!oscStarted) {
osc.start();
oscStarted = true;
}
gain.gain.value = 0.5;
$playBtn.css({
filter: 'invert(100%) blur(1px)'
})
};
$playBtn[0].onpointerup = () => {
gain.gain.value = 0;
$playBtn.css({
filter: 'invert(70%)'
})
};
let snapToScale = false;
let $snapBtn = $('#snap');
$snapBtn.click(() => {
if (!snapToScale) {
snapToScale = true;
$snapBtn.css({
backgroundColor: '#ffaa00aa',
color: 'black',
fontWeight: 500
});
} else {
snapToScale = false;
$snapBtn.css({
backgroundColor: 'transparent',
color: '#ffaa00aa',
fontWeight: 300
});
}
});
let $zoominBtn = $('#zoomin');
let $zoomoutBtn = $('#zoomout');
$zoominBtn.click(() => {
pxDistanceBetweenOctaves += 100;
if (pxDistanceBetweenOctaves > 1400)
pxDistanceBetweenOctaves = 1400;
lowestDisplayedPitch = highestDisplayedPitch - $cv.height / pxDistanceBetweenOctaves;
});
$zoomoutBtn.click(() => {
pxDistanceBetweenOctaves -= 100;
if (pxDistanceBetweenOctaves < 300)
pxDistanceBetweenOctaves = 300;
lowestDisplayedPitch = highestDisplayedPitch - $cv.height / pxDistanceBetweenOctaves;
});
let $autoscrollBtn = $('#autoscroll');
let autoscroll = true;
$autoscrollBtn.click(() => {
if (autoscroll) {
autoscroll = false;
$autoscrollBtn.css({
backgroundColor: '#0044ffaa',
filter: 'invert(100%)',
borderColor: '#0044ffaa'
});
} else {
autoscroll = true;
$autoscrollBtn.css({
borderColor: '#ffaa00aa',
filter: 'invert(0%)',
backgroundColor: 'transparent'
});
}
});
const frame = () => {
// Method 1: Autocorrelation
// Method 2: FFT
let freq = tuner.getFreq(1);
let amp = tuner.getMaxInputAmplitude();
// Manage unfiltered frequencies in order to detect frequency jump anomalies.
if (!!freq) {
lastUnfilteredFrequencies.push(freq);
if (lastUnfilteredFrequencies.length > nUnfilteredFrequenciesToStore)
lastUnfilteredFrequencies.splice(0, lastUnfilteredFrequencies.length - nUnfilteredFrequenciesToStore);
}
let avgUnfilteredFreq = lastUnfilteredFrequencies.reduce((a, b) => a + b) / lastUnfilteredFrequencies.length;
if (freq === Infinity || isNaN(freq) || !freq || amp < ampThreshold)
freq = null;
if (freq / avgUnfilteredFreq > frequencyDeviationThreshold || avgUnfilteredFreq / freq > frequencyDeviationThreshold) {
freq = null;
// console.log('Frequency anomaly detected');
}
// Average out frequencies
if (freq) {
let smoothFreq = freq * 5;
let nonNullCount = 0;
for (let i = frequencies.length - 1; nonNullCount < 4 && i >= 0; i--) {
let f = frequencies[i];
if (f) {
smoothFreq += frequencies[i];
nonNullCount++;
}
}
freq = smoothFreq / (nonNullCount + 5);
}
$freqtext.text(`${freq ? freq.toFixed(2) : 'nil'}Hz, ${amp.toFixed(2)}dB`);
frequencies.push(freq);
if (frequencies.length > nFrequenciesToStore)
frequencies.splice(0, frequencies.length - nFrequenciesToStore);
ctx.clearRect(0, 0, $cv.width, $cv.height);
// Auto scroll according to pitch.
if (freq !== null && autoscroll) {
let currPitchYCoord = convertFreqToYCoord(freq);
if (currPitchYCoord < 100) {
highestDisplayedPitch += 0.001 + (100 - currPitchYCoord) / pxDistanceBetweenOctaves / displayScrollSmoothing;
lowestDisplayedPitch = highestDisplayedPitch - $cv.height / pxDistanceBetweenOctaves;
} else if (currPitchYCoord > $cv.height - 100) {
lowestDisplayedPitch -= 0.001 + (currPitchYCoord - ($cv.height - 100)) / pxDistanceBetweenOctaves / displayScrollSmoothing;
highestDisplayedPitch = lowestDisplayedPitch + $cv.height / pxDistanceBetweenOctaves;
}
}
// Draw note lines
// First convert the repeatingIntervalSize into octaves.
// If system is n EDO, then repeatingIntervalType is 2
// If system is in n ED3 (tritaves), then repeatingIntervalType is 3.
let repeatingIntervalSizeInOctaves = Math.log2(repeatingIntervalType);
// Calculating the fraction of an octave each step spans is trivial...
let stepSize = repeatingIntervalSizeInOctaves / steps;
// The pitch of the bottom-most horizontal pitch line marker in units of steps from the base frequency.
let lowestNoteLine = Math.ceil(lowestDisplayedPitch / stepSize);
for (let s = lowestNoteLine; s * stepSize < highestDisplayedPitch; s++) {
ctx.beginPath();
if (mod((s - rootNoteStepsFromBaseFreq), steps) === 0) {
// This line represents the root of the scale
ctx.strokeStyle = '#55FFFFCC';
ctx.lineWidth = 5;
} else if (scaleNotes.includes(mod((s - rootNoteStepsFromBaseFreq), steps))) {
ctx.strokeStyle = '#00AAFFAA';
ctx.lineWidth = 3;
} else {
ctx.strokeStyle = '#AAAAAAAA';
ctx.lineWidth = 2;
}
if (s === correctNote) {
ctx.strokeStyle = ctx.strokeStyle.substr(0, 7);
ctx.lineWidth = 7;
}
let yCoord = convertFreqToYCoord(baseFreq * repeatingIntervalType ** (s / steps));
ctx.moveTo($cv.width, yCoord);
ctx.lineTo(0, yCoord);
ctx.stroke();
}
// Draw pitch line
// Flag to toggle between moveTo and lineTo.
let draw = false;
ctx.beginPath();
ctx.lineWidth = 3;
ctx.strokeStyle = '#FF9900BB';
frequencies.forEach((f, idx) => {
if (f !== null) {
if (draw)
ctx.lineTo(idx * 2, convertFreqToYCoord(f));
else {
ctx.moveTo(idx * 2, convertFreqToYCoord(f));
draw = true;
}
} else {
draw = false;
}
});
ctx.stroke();
// Find intended note & calculate cent offset
// Use average frequencies to make display less haphazard
let recentFreqs = [];
for (let i = frequencies.length; recentFreqs.length < centOffsetSmoothing && i >= 0; i--) {
let f = frequencies[i];
if (f)
recentFreqs.push(f);
}
if (recentFreqs.length !== 0) {
let avgFreq = recentFreqs.reduce((a, b) => a + b) / recentFreqs.length;
let octsFromBaseFreq = Math.log2(avgFreq / baseFreq);
let stepsFromBaseFreq = octsFromBaseFreq / stepSize;
if (!snapToScale)
correctNote = Math.round(stepsFromBaseFreq);
else {
// Snap to scale:
// Get the modulo of the steps from the root of the scale (Not base freq!)
let modStepsFromRoot = mod(stepsFromBaseFreq - rootNoteStepsFromBaseFreq, steps);
// Go through all the scale notes and find the two scale notes the modStepsFromRoot resides between
let lower = 0;
let higher = null;
scaleNotes.some(x => {
if (x > modStepsFromRoot) {
higher = x;
return true;
}
lower = x;
});
if (higher === null) {
console.log('ERROR: unable to find scale note to snap to.');
}
let lowerDiff = modStepsFromRoot - lower;
let higherDiff = higher - modStepsFromRoot;
if (lowerDiff < higherDiff) {
// The correct note is the lower of the two scale notes the current frequency resides in
// Subtract off the error from the stepsFromBaseFreq in order to keep the absolute frequency
// the same. (the mod operation defaults the octave to that of the base frequency)
// Math.round is used in case of floating point errors.
correctNote = Math.round(stepsFromBaseFreq - lowerDiff);
} else {
// The correct note is the higher of the two scale notes.
correctNote = Math.round(stepsFromBaseFreq + higherDiff);
}
}
// Note: If snap to scale is used, the cents offset will show the cent offset to the next scale note
// instead of to the next closest step.
let centsOffset = (stepsFromBaseFreq - correctNote) * stepSize * 1200;
$centstext.text(`${centsOffset > 0 ? '+' : ''}${centsOffset.toFixed(2)} ¢`)
}
// Set oscillator freq to correct note
osc.frequency.value = baseFreq * repeatingIntervalType ** (correctNote / steps);
requestAnimationFrame(frame);
};
let startedInitialise = false;
let started = false;
let pointerDown = false;
let pointerX, pointerY;
$cv.onpointerdown = (e) => {
e.preventDefault();
if (!started) {
if (!startedInitialise)
tuner.initialize();
setTimeout(() => {
if (tuner.isInitialized() && !started) {
started = true;
tuner.startListening();
$('#msg').css('display', 'none');
frame();
} else {
alert('Not yet loaded... please try again');
}
}, startedInitialise ? 0 : 600);
startedInitialise = true;
} else {
console.log('pointer down');
pointerDown = true;
pointerX = e.clientX;
pointerY = e.clientY;
}
};
$cv.onpointerup = e => {
e.preventDefault();
console.log('pointer up');
pointerDown = false;
};
$cv.onpointermove = e => {
e.preventDefault();
if (pointerDown) {
let dx = e.clientX - pointerX;
let dy = e.clientY - pointerY;
console.log(dy);
pointerX = e.clientX;
pointerY = e.clientY;
lowestDisplayedPitch += dy / pxDistanceBetweenOctaves;
highestDisplayedPitch = lowestDisplayedPitch + window.innerHeight / pxDistanceBetweenOctaves;
}
};
};
function mod(n, m) {
return ((n % m) + m) % m;
}
function convertFreqToYCoord(freq) {
let octavesFromBaseFreq = Math.log2(freq / baseFreq);
return (highestDisplayedPitch - octavesFromBaseFreq) * pxDistanceBetweenOctaves;
}
window.onresize = () => {
let cv = $('#cv')[0];
cv.height = window.innerHeight;
cv.width = window.innerWidth;
nFrequenciesToStore = window.innerWidth / 2;
// update lowest and highest displayed pitches so that the pitch at the center of the screen
// remains constant through the old and new screen sizes.
let previousHeight = (highestDisplayedPitch - lowestDisplayedPitch) * pxDistanceBetweenOctaves;
let heightDiff = window.innerHeight - previousHeight;
lowestDisplayedPitch += heightDiff / pxDistanceBetweenOctaves / 2;
highestDisplayedPitch = lowestDisplayedPitch + window.innerHeight / pxDistanceBetweenOctaves;
};