forked from ctrager/pitch_detector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpitch.html
873 lines (727 loc) · 32 KB
/
pitch.html
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
<!DOCTYPE html>
<html>
<head>
<meta name="Description"
content="Pitch detector, to improve intonation (violin, viola, etc) written by Corey Trager in HTML and Javascript">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pitch Detector</title>
<link rel="icon" type="image/x-icon"
href="data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAB2UlEQVRYR8XXT4hOURjH8c9oZMMskSJMk2RhYWOnKMaKUJrtxAILoRRZEEoSZTOJhZUsrKwldmpqUqSkLPyXlBUz/vfoKN3uO/e+17ndU+/ivuee5/c9z79z7oD/H5+wGm+bmBposqiw5htW4XkTW7kAduJ2lwDXsK9LgJmUBy/7hcgVgkHcxWb86AciJ0DoXsbBLgFC+wgu1oXI5YEowRGEvZ/YjVt1IHIBrMQQjmMMn7Eej6sgcgB8RQC8SmIbcQMfsA4x33PkAIgSHP4HIMTW4AFO4UIXAKF5FIexFNGuS0dbHgix+XiDHbjTBUBo3sRDnGsbIJLwdYnIgZSg0RtaDcGK5O6iyCg24FibANNplxHv4tiUkvB6mwBfUhmWAezBfTxrGyByoOxKdhLxa7URhQciB94VVOalk/F8VwC78AhPuwI4hEuzicdcjk5YFoIlWIypnAALsBfbsQwhHNew+C+eizlQpf1nvq4HtuEKFvWwGrt9X0ux8FIdgHFcxZxZBBam879vhiqAqO8niJLqNV5gOX71rV4jBCdwusJwnPmV2d60E55N97xe6yMJt+B7k93XScK1mMTcEoE4YPanamiqX6sKtuJM+gL+iHuYSHe+xsJ/F/4G8jBjIfCBJUEAAAAASUVORK5CYII=" />
<style>
#canvas_el {
background-color: lightgoldenrodyellow;
border: 1px solid gray;
}
body {
font-family: verdana, arial;
font-size: 14px;
margin: 20px;
}
#start_button {
font-size: 16px;
background-color: lightgreen;
}
div {
margin-top: 8px;
margin-bottom: 8px;
}
</style>
<script type="text/javascript">
"use strict"
// web audio stuff
var audioCtx
var analyser
var media_stream_source
var fft_array
var running = false
var ready = false
var first_time = true
// html elements
var note_el
var cents_threshold_input
var steady_factor_input
var fftsize_input
var transpose_octave_input
var canvas_el
var start_button
var prev_note = {
letter: "",
accidental: ""
}
// configurable stuff
var queue = []
var cents_threshold
var queue_length
var fftSize
var yin_buffer
var sharps_or_flats
var clef
var high_ledger_line_indexes
var low_ledger_line_indexes
// get_freq_via_yin constants
const yin_threshold = 0.1
const yin_probabilityThreshold = 0.1
// canvas context
var ctx
function on_load() {
note_el = document.getElementById("note_el")
cents_threshold_input = document.getElementById("cents_threshold_input")
steady_factor_input = document.getElementById("steady_factor_input")
fftsize_input = document.getElementById("fftsize_input")
transpose_octave_input = document.getElementById("transpose_octave_input")
start_button = document.getElementById("start_button")
canvas_el = document.getElementById("canvas_el")
ctx = canvas_el.getContext("2d");
set_sharps_or_flats("sharps")
set_clef("treble")
draw_staff()
draw_test()
}
function init_web_audio() {
navigator.mediaDevices.getUserMedia({
audio: true,
video: false
})
.then(function (stream) {
media_stream_source = audioCtx.createMediaStreamSource(stream);
media_stream_source.connect(analyser);
ready = true
console.log("ready")
})
.catch(function (err) {
console.log(err)
})
}
function set_config() {
// init the queue
queue = []
queue_length = steady_factor_input.value
for (var i = 0; i < queue_length; i++) {
queue.push(0)
}
cents_threshold = cents_threshold_input.value
}
var note_letters
function set_sharps_or_flats(val) {
sharps_or_flats = val
if (sharps_or_flats == "sharps") {
note_letters = sharp_note_letters
} else {
note_letters = flat_note_letters
}
calc_ledger_line_boundaries()
//draw_test()
}
var offset_to_middle_c
function set_clef(val) {
clef = val
if (clef == "treble") {
offset_to_middle_c = line_height // 2 half steps down from bottom line to middle c
} else if (clef == "alto") {
offset_to_middle_c = -2 * line_height // four half steps up from bottom line to middle c
}
calc_ledger_line_boundaries()
restart()
//draw_test()
}
function calc_ledger_line_boundaries() {
high_ledger_line_indexes = []
low_ledger_line_indexes = []
if (clef == "treble") {
if (sharps_or_flats == "sharps") {
high_ledger_line_indexes.push(note_letters.indexOf("A5"))
high_ledger_line_indexes.push(note_letters.indexOf("C6"))
high_ledger_line_indexes.push(note_letters.indexOf("E6"))
high_ledger_line_indexes.push(note_letters.indexOf("G6"))
low_ledger_line_indexes.push(note_letters.indexOf("C#4"))
low_ledger_line_indexes.push(note_letters.indexOf("A#3"))
low_ledger_line_indexes.push(note_letters.indexOf("F#3"))
} else {
note_letters = flat_note_letters
high_ledger_line_indexes.push(note_letters.indexOf("Af5"))
high_ledger_line_indexes.push(note_letters.indexOf("C6"))
high_ledger_line_indexes.push(note_letters.indexOf("Ef6"))
high_ledger_line_indexes.push(note_letters.indexOf("G6"))
low_ledger_line_indexes.push(note_letters.indexOf("C4"))
low_ledger_line_indexes.push(note_letters.indexOf("A3"))
low_ledger_line_indexes.push(note_letters.indexOf("F3"))
}
} else if (clef == "alto") {
if (sharps_or_flats == "sharps") {
note_letters = sharp_note_letters
high_ledger_line_indexes.push(note_letters.indexOf("B4"))
high_ledger_line_indexes.push(note_letters.indexOf("D5"))
high_ledger_line_indexes.push(note_letters.indexOf("F5"))
high_ledger_line_indexes.push(note_letters.indexOf("A5"))
low_ledger_line_indexes.push(note_letters.indexOf("D#3"))
low_ledger_line_indexes.push(note_letters.indexOf("B#2"))
low_ledger_line_indexes.push(note_letters.indexOf("G#2"))
} else {
note_letters = flat_note_letters
high_ledger_line_indexes.push(note_letters.indexOf("Bf4"))
high_ledger_line_indexes.push(note_letters.indexOf("Df5"))
high_ledger_line_indexes.push(note_letters.indexOf("E5"))
high_ledger_line_indexes.push(note_letters.indexOf("Af5"))
low_ledger_line_indexes.push(note_letters.indexOf("D2"))
low_ledger_line_indexes.push(note_letters.indexOf("B2"))
low_ledger_line_indexes.push(note_letters.indexOf("G2"))
}
}
}
function draw_test() {
// for testing
draw_staff()
set_config()
var f = 440
for (var j = 0; j < 3; j++) {
f = 440
for (var i = 0; i < 12; i++) {
draw_note(frequency_to_note(f))
f *= 1.10
}
f = 440
for (var i = 0; i < 8; i++) {
draw_note(frequency_to_note(f))
f *= .9
}
}
}
function restart() {
if (running) {
running = false
start()
}
}
function toggle_start_stop() {
if (running) {
running = false
start_button.innerText = "Click to Start"
start_button.style.backgroundColor = "lightgreen"
} else {
start_button.innerText = "Running. Play your instrument. Click to Stop"
start_button.style.backgroundColor = "red"
start()
}
}
function start() {
set_config()
if (first_time) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioCtx.createAnalyser();
first_time = false
init_web_audio()
}
analyser.fftSize = fftsize_input.value
fft_array = new Float32Array(analyser.fftSize)
// Copied from yin algo function, to get mem allocation out of the loop
// Set buffer size to the highest power of two below the provided buffer's length.
let bufferSize;
for (bufferSize = 1; bufferSize < fft_array.length; bufferSize *= 2);
bufferSize /= 2;
// Set up the yinBuffer as described in step one of the YIN paper.
//yin_buffer = new Float32Array(bufferSize / 2);
// end of copy
// corey says... results of above are:
// 2048 = 512
// 4096 = 1024
// 8192 = 2048
// 16384 = 4096
// 32768 = 8192
// corey says.. i don't understand the power of 2 stuff, versus half buffer size
// so let's try divided by 2
yin_buffer = new Float32Array(fft_array.length / 2)
note_el.innerText = ""
running = true
draw_staff()
requestAnimationFrame(frame_callback)
}
function frame_callback() {
if (!running) return;
if (!ready) {
requestAnimationFrame(frame_callback)
return
}
// Get data representing the shape of the wave
analyser.getFloatTimeDomainData(fft_array);
let freq = (get_freq_via_yin(fft_array, yin_buffer, yin_threshold, yin_probabilityThreshold))
if (freq) {
// For steadier pitch detection, save the last N frequencies and then pick the most common of the last N
queue.shift()
queue.push(freq.toFixed(1))
let most_common_recent_frequency = get_mode(queue)
// convert the frequency to the note, 440 to A4
let note = frequency_to_note(most_common_recent_frequency)
if (note) {
draw_note(note)
}
}
// loop
requestAnimationFrame(frame_callback)
}
const number_of_staffs = 4
const canvas_width = 700
const canvas_height = 420
const line_height = 8
const staff_spacing = 50
const note_spacing = 30
const sharp_line_length = 10
const ledger_line_half_length = 10
const letter_array = ["C", "D", "E", "F", "G", "A", "B"]
var staff_number = 1
var current_x
function draw_note(note) {
if (!note) return
if (note.freq == prev_note.freq) {
return
}
// enhance/alter the note object
note.just_letter = note.letter.charAt(0)
if (note.letter.length == 2) {
// like A4
note.accidental = ""
note.octave = parseInt(note.letter.charAt(1))
} else {
// like A#4
note.accidental = note.letter.charAt(1)
note.octave = parseInt(note.letter.charAt(2))
}
// Transpose the octave.
// A4 can become A3 or A5, etc
note.octave = note.octave += parseInt(transpose_octave_input.value)
note.letter = note.just_letter + note.accidental + note.octave
// If it's the same note, we'll just redraw with a different color
// so don't increment x coordinate, but if it is a different note, then increment
if (note.letter != prev_note.letter) {
current_x += note_spacing
// the previous note took up more room, so move to the right more
if (prev_note.accidental != "") {
current_x += sharp_line_length * 2.5
}
// are we at the end of this staff?
if (current_x > (canvas_width - (2 * note_spacing))) {
staff_number++
if (staff_number > number_of_staffs) {
draw_staff()
}
// reset x to beginning of line
current_x = note_spacing
}
}
var y = .5 // half pixel for crisper lines, to match up with draw_staff()
y += staff_number * staff_spacing
y += staff_number * (5 * line_height)
// y is now the bottom line of the staff, or an E on the D string for violin
var first_low_ledger_line = y + line_height
var first_high_ledger_line = y - (5 * line_height)
// move to middle c, depends on which clef
y += offset_to_middle_c
var offset_from_middle_c = letter_array.indexOf(note.just_letter)
// adjust y per the note
y -= offset_from_middle_c * (line_height / 2)
// adjust y per the octave
var offset_from_octave_4 = note.octave - 4
y -= offset_from_octave_4 * (3.5 * line_height)
// color based on intonation
if (note.cents > cents_threshold) {
ctx.fillStyle = "red"
ctx.strokeStyle = "red"
} else if (Math.abs(note.cents) > cents_threshold) {
ctx.fillStyle = "dodgerblue"
ctx.strokeStyle = "dodgerblue"
} else {
ctx.fillStyle = "black"
ctx.strokeStyle = "black"
}
// draw the accidental
// to do, make this more configurable, get rid of hard-coded numbers
const sharp_horz_tilt = 2
var note_x = current_x
var acc_x = current_x - 3
var note_width = line_height * 0.8
if (note.accidental == "#") {
// draw the sharp symbol
ctx.beginPath();
var sharp_y = y - 1
// horizontal lines, slight titled
ctx.moveTo(acc_x - 2, sharp_y + sharp_horz_tilt)
ctx.lineTo(acc_x + sharp_line_length, sharp_y - sharp_horz_tilt)
var sharp_y = y + line_height / 2
ctx.moveTo(acc_x - 2, sharp_y + sharp_horz_tilt)
ctx.lineTo(acc_x + sharp_line_length, sharp_y - sharp_horz_tilt)
// vertical lines, second one is a little higher
ctx.moveTo(acc_x + 2, y - (line_height / 2) - 1)
ctx.lineTo(acc_x + 2, y + (line_height / 2) + 3)
ctx.moveTo(acc_x + 6, y - (line_height / 2) - 2)
ctx.lineTo(acc_x + 6, y + (line_height / 2) + 2)
ctx.stroke();
note_x += sharp_line_length * 2
} else {
if (note.accidental == "f") {
// draw the flat symbol
ctx.beginPath();
//vertical line
ctx.moveTo(acc_x, y - (line_height))
ctx.lineTo(acc_x, y + (line_height / 2))
ctx.stroke();
// A flat's half circle, slightly rotated. A real one is prettier than just a thin line.
ctx.ellipse(
acc_x + 3,
y,
4,
line_height * 0.35,
-3.4, // rotation
.3 * Math.PI, // start angle
1.76 * Math.PI); // end angle
ctx.stroke()
note_x += sharp_line_length * 2
}
}
// draw the note itself, an ellipse slightly rotated
ctx.beginPath()
ctx.ellipse(
note_x,
y,
note_width,
line_height * 0.45, // don't completely fill the space between the lines
-.2, // rotation
0, // start angle
2 * Math.PI) // end angle
ctx.fill()
// draw ledger lines
var this_index = note_letters.indexOf(note.letter)
if (this_index >= high_ledger_line_indexes[0]) {
y = first_high_ledger_line
draw_ledger_line(note_x, y)
if (this_index >= high_ledger_line_indexes[1]) {
y -= line_height
draw_ledger_line(note_x, y)
if (this_index >= high_ledger_line_indexes[2]) {
y -= line_height
draw_ledger_line(note_x, y)
if (this_index >= high_ledger_line_indexes[3]) {
y -= line_height
draw_ledger_line(note_x, y)
}
}
}
} else {
if (this_index <= low_ledger_line_indexes[0]) {
y = first_low_ledger_line
draw_ledger_line(note_x, y)
if (this_index <= low_ledger_line_indexes[1]) {
y += line_height
draw_ledger_line(note_x, y)
if (this_index <= low_ledger_line_indexes[2]) {
y += line_height
draw_ledger_line(note_x, y)
}
}
}
}
note_el.innerText = note.letter + " " + parseFloat(note.freq).toFixed(2) + ", cents: " + note.cents
prev_note = note
}
function draw_ledger_line(x, y) {
ctx.beginPath()
ctx.moveTo(x - ledger_line_half_length, y)
ctx.lineTo(x + ledger_line_half_length, y)
ctx.stroke()
}
function draw_staff() {
ctx.clearRect(0, 0, canvas_width, canvas_height)
ctx.lineWidth = 1
ctx.strokeStyle = "black"
var y = .5 // for crisp lines https://usefulangle.com/post/17/html5-canvas-drawing-1px-crisp-straight-lines
for (var row = 1; row < number_of_staffs + 1; row++) {
y += staff_spacing
for (var line = 0; line < 5; line++) {
y += line_height
ctx.beginPath()
ctx.moveTo(0, y)
ctx.lineTo(canvas_width, y)
ctx.stroke()
}
draw_staff
}
staff_number = 1
current_x = 0
prev_note = {
letter: "",
accidental: ""
}
}
// Corey says...
// Implementation of the algorithm described way over my head here: http://audition.ens.fr/adc/pdf/2002_JASA_YIN.pdf
// The paper has charts that explain the settings of the variables "threshold and probabilityThreshold".
// They seem to have figured out the best comprimise for their values, I guess.
//
// from https://github.com/peterkhayes/pitchfinder/blob/master/src/detectors/yin.ts
// and tweaked per https://github.com/ashokfernandez/Yin-Pitch-Tracking/blob/master/Yin.c
// One of them is copied from the other, but they differ in terms of the yinBuffer
// length. I moved the logic for creating the buffer out of the loop for efficiency.
function get_freq_via_yin(fft_array, yinBuffer, threshold, probabilityThreshold) {
let probability = 0,
tau;
let yinBufferLength = yinBuffer.length
yinBuffer.fill(0)
// Corey says...The offset has the variable name "t" for tau
// This is autocorrelation but using the square of the difference instead of the plain difference
for (let t = 1; t < yinBufferLength; t++) {
for (let i = 0; i < yinBufferLength; i++) {
const delta = fft_array[i] - fft_array[i + t];
yinBuffer[t] += delta * delta;
}
}
// Compute the cumulative mean normalized difference as described in step 3 of the paper.
yinBuffer[0] = 1;
yinBuffer[1] = 1;
let runningSum = 0;
for (let t = 1; t < yinBufferLength; t++) {
runningSum += yinBuffer[t];
yinBuffer[t] *= t / runningSum;
}
// Compute the absolute threshold as described in step 4 of the paper.
// Since the first two positions in the array are 1,
// we can start at the third position.
for (tau = 2; tau < yinBufferLength; tau++) {
if (yinBuffer[tau] < threshold) {
while (tau + 1 < yinBufferLength && yinBuffer[tau + 1] < yinBuffer[tau]) {
tau++;
}
// found tau, exit loop and return
// store the probability
// From the YIN paper: The threshold determines the list of
// candidates admitted to the set, and can be interpreted as the
// proportion of aperiodic power tolerated
// within a periodic signal.
//
// Since we want the periodicity and and not aperiodicity:
// periodicity = 1 - aperiodicity
probability = 1 - yinBuffer[tau];
break;
}
}
// if no pitch found, return null.
if (tau === yinBufferLength || yinBuffer[tau] >= threshold) {
return null;
}
// If probability too low, return -1.
if (probability < probabilityThreshold) {
return null;
}
/*
* Implements step 5 of the AUBIO_YIN paper. It refines the estimated tau
* value using parabolic interpolation. This is needed to detect higher
* frequencies more precisely. See http://fizyka.umk.pl/nrbook/c10-2.pdf and
* for more background
* http://fedc.wiwi.hu-berlin.de/xplore/tutorials/xegbohtmlnode62.html
*/
/* The 'best' shift value for autocorellation is most likely not an interger shift of the signal.
* As we only autocorellated using integer shifts we should check that there isn't a better fractional
* shift value.
*/
let betterTau, x0, x2;
if (tau < 1) {
x0 = tau;
} else {
x0 = tau - 1;
}
if (tau + 1 < yinBufferLength) {
x2 = tau + 1;
} else {
x2 = tau;
}
if (x0 === tau) {
if (yinBuffer[tau] <= yinBuffer[x2]) {
betterTau = tau;
} else {
betterTau = x2;
}
} else if (x2 === tau) {
if (yinBuffer[tau] <= yinBuffer[x0]) {
betterTau = tau;
} else {
betterTau = x0;
}
} else {
const s0 = yinBuffer[x0];
const s1 = yinBuffer[tau];
const s2 = yinBuffer[x2];
// fixed AUBIO implementation, thanks to Karl Helgason:
// (2.0f * s1 - s2 - s0) was incorrectly multiplied with -1
betterTau = tau + (s2 - s0) / (2 * (2 * s1 - s2 - s0));
}
// return frequency
return audioCtx.sampleRate / betterTau;
}
// frequency to note constants
const A4 = 440.0;
const A4_INDEX = 57;
const sharp_note_letters = [
"C0", "C#0", "D0", "D#0", "E0", "F0", "F#0", "G0", "G#0", "A0", "A#0", "B0",
"C1", "C#1", "D1", "D#1", "E1", "F1", "F#1", "G1", "G#1", "A1", "A#1", "B1",
"C2", "C#2", "D2", "D#2", "E2", "F2", "F#2", "G2", "G#2", "A2", "A#2", "B2",
"C3", "C#3", "D3", "D#3", "E3", "F3", "F#3", "G3", "G#3", "A3", "A#3", "B3",
"C4", "C#4", "D4", "D#4", "E4", "F4", "F#4", "G4", "G#4", "A4", "A#4", "B4",
"C5", "C#5", "D5", "D#5", "E5", "F5", "F#5", "G5", "G#5", "A5", "A#5", "B5",
"C6", "C#6", "D6", "D#6", "E6", "F6", "F#6", "G6", "G#6", "A6", "A#6", "B6",
"C7", "C#7", "D7", "D#7", "E7", "F7", "F#7", "G7", "G#7", "A7", "A#7", "B7",
"C8", "C#8", "D8", "D#8", "E8", "F8", "F#8", "G8", "G#8", "A8", "A#8", "B8",
"C9", "C#9", "D9", "D#9", "E9", "F9", "F#9", "G9", "G#9", "A9", "A#9", "B9"
];
const flat_note_letters = [
"C0", "Df0", "D0", "Ef0", "E0", "F0", "Gf0", "G0", "Af0", "A0", "Bf0", "B0",
"C1", "Df1", "D1", "Ef1", "E1", "F1", "Gf1", "G1", "Af1", "A1", "Bf1", "B1",
"C2", "Df2", "D2", "Ef2", "E2", "F2", "Gf2", "G2", "Af2", "A2", "Bf2", "B2",
"C3", "Df3", "D3", "Ef3", "E3", "F3", "Gf3", "G3", "Af3", "A3", "Bf3", "B3",
"C4", "Df4", "D4", "Ef4", "E4", "F4", "Gf4", "G4", "Af4", "A4", "Bf4", "B4",
"C5", "Df5", "D5", "Ef5", "E5", "F5", "Gf5", "G5", "Af5", "A5", "Bf5", "B5",
"C6", "Df6", "D6", "Ef6", "E6", "F6", "Gf6", "G6", "Af6", "A6", "Bf6", "B6",
"C7", "Df7", "D7", "Ef7", "E7", "F7", "Gf7", "G7", "Af7", "A7", "Bf7", "B7",
"C8", "Df8", "D8", "Ef8", "E8", "F8", "Gf8", "G8", "Af8", "A8", "Bf8", "B8",
"C9", "Df9", "D9", "Ef9", "E9", "F9", "Gf9", "G9", "Af9", "A9", "Bf9", "B9"
];
const MINUS = -1;
const PLUS = 1;
const r = Math.pow(2.0, 1.0 / 12.0);
const cent = Math.pow(2.0, 1.0 / 1200.0);
// Corey says...from https://newt.phys.unsw.edu.au/music/note/, then I tweaked it
function frequency_to_note(input) {
// if ((input < 27.5) || (input > 14080))
// Corey says...low end, viola C string, high end violin high b on e string
// We want to filter out more extreme notes which tend to be noise, harmonics
if ((input < 124) || (input > 2000))
return null
var frequency;
var r_index = 0;
var cent_index = 0;
var side;
frequency = A4;
if (input >= frequency) {
while (input >= r * frequency) {
frequency = r * frequency;
r_index++;
}
while (input > cent * frequency) {
frequency = cent * frequency;
cent_index++;
}
if ((cent * frequency - input) < (input - frequency))
cent_index++;
if (cent_index > 50) {
r_index++;
cent_index = 100 - cent_index;
if (cent_index != 0)
side = MINUS;
else
side = PLUS;
} else
side = PLUS;
} else {
while (input <= frequency / r) {
frequency = frequency / r;
r_index--;
}
while (input < frequency / cent) {
frequency = frequency / cent;
cent_index++;
}
if ((input - frequency / cent) < (frequency - input))
cent_index++;
if (cent_index >= 50) {
r_index--;
cent_index = 100 - cent_index;
side = PLUS;
} else {
if (cent_index != 0)
side = MINUS;
else
side = PLUS;
}
}
var letter = note_letters[A4_INDEX + r_index];
return {
letter: letter,
cents: side * cent_index,
freq: input,
}
}
// get most frequencly occuring value in an array, aka, the mode. from stackoverflow
function get_mode(array) {
if (array.length == 0)
return null;
var modeMap = {};
var maxEl = array[0],
maxCount = 1;
for (var i = 0; i < array.length; i++) {
var el = array[i];
if (modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if (modeMap[el] > maxCount) {
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}
</script>
</head>
<body onload="on_load()">
<div>
<button id="start_button" onclick="toggle_start_stop()">Click to Start</button>
</div>
<div>Sensitivity - Smaller is less forgiving to out of tune notes (2 to 40):
<input id="cents_threshold_input" onchange="restart()" value="12" type="number" min="2" max="40"></input>
</div>
<div>
Accidentals:
<label><input type="radio" name="sharps_or_flats" value="sharps" onchange="set_sharps_or_flats(this.value)"
checked>sharps</input></label>
<label><input type="radio" name="sharps_or_flats" value="flats"
onchange="set_sharps_or_flats(this.value)">flats</input></label>
</div>
<div>
Clef:
<label><input type="radio" name="clef" value="treble" onchange="set_clef(this.value)"
checked>treble</input></label>
<label><input type="radio" name="clef" value="alto" onchange="set_clef(this.value)">alto</input></label>
Transpose octave:
<select id="transpose_octave_input" onchange="restart">
<option value="0">Don't transpose (violin, flute)</option>
<option value="1">Up 1 octave (viola, guitar)</option>
<option value="2">Up 2 octaves</option>
<option value="-1">Down 1 octave (whistling)</option>
<option value="-2">Down 2 octaves</option>
</select>
</div>
<div>
<span style="color: red;">Red = out of tune sharp.</span>
<span style="color: dodgerblue;">Blue = out of tune flat.</span>
<span id="note_el"></span>
</div>
<div><canvas id="canvas_el" width=700 height=420></canvas></div>
<div>Tweak the performance:</div>
<div>Steady factor - Bigger is maybe more accurate at pitch detection but slower to respond.
<br>The app takes the most frequently occuring pitch from the last N samples (3 to 60):
<input id="steady_factor_input" onchange="restart()" value="12" type="number" min="3" max="60"></input>
</div>
<div>fftSize - Bigger is more accurate but slower to respond. Fast Fourier Transform window size:
<select id="fftsize_input" onchange="restart()">
<option value="2048">2048</option>
<option value="4096" selected>4096</option>
<option value="8192">8192</option>
<option value="16384">16384</option>
<option value="32768">32768</option>
</select>
</div>
<div>
by <a href="https://ctrager.github.io">Corey Trager</a> - <a
href="https://github.com/ctrager/pitch_detector">https://github.com/ctrager/pitch_detector</a>
</div>
</body>
</html>