-
Notifications
You must be signed in to change notification settings - Fork 0
/
audioInterface.js
305 lines (285 loc) · 8.42 KB
/
audioInterface.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
// snyth sounds somewhat based on the the following tutorial:
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Simple_synth
import { detect } from '@tonaljs/chord-detect'
import * as Tone from 'tone'
import toastr from 'toastr'
import { CURRENT_HISTORY_WINDOW_SIZE, PREVIOUS_HISTORY_WINDOW_START, PREVIOUS_HISTORY_WINDOW_END, HISTORY_LENGTH, MULTIPLIER } from './consts'
const getNoteFrequency = node => {
const mapping = {
'A': 110.00,
'A#': 116.54,
'B': 123.47,
'C': 130.81,
'C#': 138.59,
'D': 146.83,
'D#': 155.56,
'E': 164.81,
'F': 174.61,
'F#': 185.00,
'G': 196.00,
'G#': 207.65
}
return mapping[node]
}
const getNoteForKey = key => {
const mapping = {
'a': 'A',
'w': 'A#',
's': 'B',
'd': 'C',
'r': 'C#',
'f': 'D',
't': 'D#',
'g': 'E',
'h': 'F',
'u': 'F#',
'j': 'G',
'i': 'G#'
}
return mapping[key]
}
// load drums
const bd = new Tone.Player('/www/static/Bass-Drum-1.wav').toDestination()
const snare = new Tone.Player('/www/static/Ensoniq-ESQ-1-Snare.wav').toDestination()
const hhatClosed = new Tone.Player('/www/static/Closed-Hi-Hat-1.wav').toDestination()
const hhatOpen = new Tone.Player('/www/static/Ensoniq-SQ-1-Open-Hi-Hat.wav').toDestination()
const ride = new Tone.Player('/www/static/Ensoniq-SQ-1-Ride-Cymbal.wav').toDestination()
const crash = new Tone.Player('/www/static/Crash-Cymbal-1.wav').toDestination()
const ft = new Tone.Player('/www/static/Floor-Tom.wav').toDestination()
const ttLow = new Tone.Player('/www/static/Tom-Tom-Low.wav').toDestination()
const ttHigh = new Tone.Player('/www/static/Tom-Tom-High.wav').toDestination()
const rideCrash = 'rideCrash' // e-drums only
const getDrumForKey = key => {
const mapping = {
x: bd,
z: snare,
c: ft,
n: hhatOpen,
m: hhatClosed,
v: ttLow,
b: ttHigh,
k: ride,
l: crash
}
return mapping[key]
}
const getDrumStringForKey = key => {
const mapping = {
x: 'bd',
z: 'snare',
c: 'ft',
n: 'hhatOpen',
m: 'hhatClosed',
v: 'ttLow',
b: 'ttHigh',
k: 'ride',
l: 'crash'
}
return mapping[key]
}
const getDrumForMidiId = id => {
const mapping = {
36: bd,
38: snare,
43: ft,
26: hhatOpen,
22: hhatClosed,
28: ttHigh,
45: ttLow,
51: ride,
59: rideCrash,
55: crash
}
return mapping[id]
}
const getDrumStringForMidiId = id => {
const mapping = {
36: 'bd',
38: 'snare',
43: 'ft',
26: 'hhatOpen',
22: 'hhatClosed',
28: 'ttHigh',
45: 'ttLow',
51: 'ride',
59: 'rideCrash',
55: 'crash'
}
return mapping[id]
}
window.stability = 0.8
window.beatHistory = []
window.stabilityWindow = []
let isRunning = false
setInterval(() => {
const newBeatHistory = []
const currentHistoryAggregate = {
bd: 0,
snare: 0,
ft: 0,
hhatOpen: 0,
hhatClosed: 0,
ride: 0,
rideCrash: 0,
crash: 0,
ttHigh: 0,
ttLow: 0
}
const previousHistoryAggregate = {
bd: 0,
snare: 0,
ft: 0,
hhatOpen: 0,
hhatClosed: 0,
ride: 0,
rideCrash: 0,
crash: 0,
ttHigh: 0,
ttLow: 0
}
const now = new Date().getTime()
beatHistory.forEach(beat => {
if(now - beat.time < 10000) newBeatHistory.push(beat)
if(now - beat.time < CURRENT_HISTORY_WINDOW_SIZE) {
currentHistoryAggregate[beat.drum] += 1
}
if(now - beat.time < PREVIOUS_HISTORY_WINDOW_START && now - beat.time > PREVIOUS_HISTORY_WINDOW_END) {
previousHistoryAggregate[beat.drum] += 1
}
})
console.log('Current', currentHistoryAggregate)
console.log('Previous', previousHistoryAggregate)
//window.beatHistory = newBeatHistory
// stability: shared number of beats in both windows divided by total number of beats in current window
console.log(Object.keys(currentHistoryAggregate))
let currentNumberOfBeats = 0;
let sharedNumberOfBeats = 0;
Object.keys(currentHistoryAggregate).forEach(drum => {
currentNumberOfBeats += currentHistoryAggregate[drum]
sharedNumberOfBeats += Math.abs(currentHistoryAggregate[drum] - Math.abs(currentHistoryAggregate[drum] - previousHistoryAggregate[drum]))
})
console.log(currentNumberOfBeats, sharedNumberOfBeats)
const tempStability = currentNumberOfBeats === 0 ? 0.8 : sharedNumberOfBeats / currentNumberOfBeats
if(tempStability < 0.79 || tempStability > 0.81) isRunning = true
stabilityWindow.push(tempStability)
if(isRunning && currentNumberOfBeats === 0) {
stability = 0
} else if(stabilityWindow.length < HISTORY_LENGTH || !isRunning) {
stability = 0.8
} else {
stability = (stabilityWindow.slice(-3).reduce((a, b) => a + b, 0 ) / HISTORY_LENGTH) * MULTIPLIER
}
console.log('Stability:', stability)
}, 2000)
// maintain array of currently "active" notes
let notes = []
const playTone = (frequency, masterGainNode, audioContext) => {
const oscillator = audioContext.createOscillator()
oscillator.connect(masterGainNode)
oscillator.type = 'square'
oscillator.frequency.value = frequency
oscillator.start()
return oscillator
}
const audioInterface = () => {
const audioContext = new (window.AudioContext || window.webkitAudioContext)()
let oscillatorDictionary = {}
const masterGainNode = audioContext.createGain()
masterGainNode.connect(audioContext.destination)
toastr.options.closeDuration = 5000
window.addEventListener('keydown', event => {
if(getDrumForKey(event.key)) {
getDrumForKey(event.key).start()
beatHistory.push({
drum: getDrumStringForKey(event.key),
time: new Date().getTime()
})
return
}
processSound(event)
})
window.addEventListener('keyup', event => {
const note = getNoteForKey(event.key)
if (note) {
if (notes.includes(note)) {
notes = []
}
if (oscillatorDictionary[note]) {
oscillatorDictionary[note].stop()
}
}
})
}
navigator.requestMIDIAccess()
.then(function(access) {
const inputs = access.inputs.values()
const input = inputs.next().value
if(input && input.name === 'TD-17') {
console.log('here TD')
input.onmidimessage = message => {
const drumId = message && message.data && message.data[1]
console.log(drumId)
if(drumId && getDrumForMidiId(drumId)) {
//getDrumForMidiId(drumId).start()
beatHistory.push({
drum: getDrumStringForMidiId(drumId),
time: new Date().getTime()
})
return
}
}
}
})
function processSound(event) {
const note = getNoteForKey(event.key)
if (note) {
notes.push(note)
const frequency = getNoteFrequency(note)
console.log(note, frequency)
const chord = detect(notes)[0] ? detect(notes)[0] : 'none'
console.log(notes, chord)
if (chord !== 'none') {
let currentScript = window.editor.getValue()
console.log(currentScript)
console.log(chord[1])
if (chord[1] === 'M') {
currentScript = currentScript.replace(
'(isActive && neighborActivity >= 2 && neighborActivity < 4)',
'(isActive && neighborActivity >= 1 && neighborActivity < 4)'
)
currentScript = currentScript.replace(
'neighborActivity === 3',
'(neighborActivity === 0 && Math.random() < 0.5)'
)
toastr.info(`Identified chord: ${chord}`)
window.activeAgentMode = 'major'
} else if (chord[1] === 'm') {
currentScript = currentScript.replace(
'(isActive && neighborActivity >= 1 && neighborActivity < 4)',
'(isActive && neighborActivity >= 2 && neighborActivity < 4)'
)
currentScript = currentScript.replace(
'(neighborActivity === 0 && Math.random() < 0.5)',
'neighborActivity === 3'
)
toastr.info(`Identified chord: ${chord}`)
window.activeAgentMode = 'minor'
}
setTimeout(() => {
window.editor.setValue(currentScript)
const model = window.editor.getModel()
// This will preserve the undo stack.
model.pushEditOperations(
[],
[{ range: model.getFullModelRange(), text: currentScript }],
() => null,
)
}, 1000)
}
if (oscillatorDictionary[note]) {
oscillatorDictionary[note].stop()
}
oscillatorDictionary[note] = playTone(frequency, masterGainNode, audioContext)
}
}
export default audioInterface