-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththeremin_auxiliary.js
56 lines (51 loc) · 1.22 KB
/
theremin_auxiliary.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
"use strict";
let notenames = {
0: "C",
1: "C#",
2: "D",
3: "Eb",
4: "E",
5: "F",
6: "F#",
7: "G",
8: "Ab",
9: "A",
10: "Bb",
11: "B"
}
function interval(frequency, semitones) {
// Assuming equal temperament
return frequency * Math.pow(2, semitones / 12);
}
function midiToFrequency(midinumber, concertA = 440) {
const A4 = 69
if (midinumber === A4) {
return concertA;
}
let semitones = midinumber - A4;
return interval(440, semitones);
}
function midiFromFrequency(frequency) {
let minDiff = Number.MAX_VALUE;
let midinumber = -1;
for (let midi = 0; midi < 128; midi++) {
let midiFreq = midiToFrequency(midi);
let freqDiff = Math.abs(midiFreq - frequency);
if (freqDiff < minDiff) {
minDiff = freqDiff;
midinumber = midi;
}
}
return midinumber
}
function noteFromFrequency(frequency, withOctave=false) {
const midinumber = midiFromFrequency(frequency);
const pitchclass = midinumber % 12;
let octave = (midinumber - pitchclass) / 12;
let notename = notenames[pitchclass];
if (withOctave) {
octave--;
notename += octave;
}
return notename;
}