-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmidiControlledSynth.js
116 lines (99 loc) · 2.47 KB
/
midiControlledSynth.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
class MIDIControlledSynth {
#type;
#releaseTime;
#gain;
constructor() {
this.oscillatorTypes = [ "sine", "square", "triangle", "sawtooth" ];
this.#type = "sine";
this.#releaseTime = 0.1;
this.#gain = 1;
this.audioContext = new AudioContext();
this.initializeMidiAccess();
}
createNewOscillator = () => {
if(this.gain) {
this.gain.disconnect(this.audioContext.destination);
}
if(this.oscillator) {
this.oscillator.stop();
}
this.oscillator = this.audioContext.createOscillator();
this.oscillator.type = this.#type;
this.gain = this.audioContext.createGain();
this.gain.gain.value = this.#gain;
this.oscillator.connect(this.gain);
this.oscillator.start();
}
setOscillatorType(type) {
if(this.oscillatorTypes.indexOf(type) !== -1 ) {
this.#type = type;
}
}
setReleaseTime(time) {
if(time > 0) {
this.stopSound();
this.#releaseTime = parseFloat(time);
}
}
setGain(gain) {
if(gain >= 0) {
this.stopSound();
this.#gain = parseFloat(gain);
}
}
parseMessage = (message) => {
return {
command: message.data[0] >> 4,
channel: message.data[0] & 0xf,
note: message.data[1],
velocity: message.data[2]
};
}
convertNoteToFrequency = (note) => {
return 440 * Math.pow(2, (note - 69) / 12 );
}
initializeMidiAccess = () => {
console.log("Initializing MIDI Access...");
navigator.requestMIDIAccess({sysex: false}).then((midiAccess) => {
const inputs = midiAccess.inputs.values();
for(let input = inputs.next(); input && !input.done; input = inputs.next()) {
if(input.value) {
input.value.onmidimessage = this.processMidiMessage;
}
}
}, (error) => {
console.log("No MIDI support");
});
}
processMidiMessage = (message) => {
let parsedMessage = this.parseMessage(message);
switch(parsedMessage.command) {
case 8:
this.stopSound();
break;
case 9:
this.playSound(this.convertNoteToFrequency(parsedMessage.note));
break;
default:
console.log("Unsupported command");
break;
}
}
playSound = (frequency) => {
this.createNewOscillator();
this.gain.connect(this.audioContext.destination);
this.oscillator.frequency.value = frequency;
}
stopSound = () => {
try {
if(this.gain) {
this.gain.gain.exponentialRampToValueAtTime(0.0001, this.audioContext.currentTime + this.#releaseTime);
}
}
catch(err) {
console.log("Couldn't disconnect");
console.log(err);
}
}
}
export default MIDIControlledSynth;