-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
sonantx.js
360 lines (300 loc) · 9.49 KB
/
sonantx.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
// Oscillators
function osc_sin (value) {
return Math.sin(value * Math.PI * 2)
}
function osc_square (value) {
if (osc_sin(value) < 0) {
return -1
}
return 1
}
function osc_saw (value) {
return (value % 1) - 0.5
}
function osc_tri (value) {
const v2 = (value % 1) * 4
if (v2 < 2) {
return v2 - 1
}
return 3 - v2
}
// Array of oscillator functions
const oscillators =
[
osc_sin,
osc_square,
osc_saw,
osc_tri
]
function getnotefreq44100 (n) {
const val = 0.00390625 * Math.pow(1.059463094, n - 128)
return val
}
function getnotefreq (audioCtx, n) {
const x = getnotefreq44100(n)
const val = (x / audioCtx.sampleRate) * 44100
return val
}
function effectiveRowLen (audioCtx, bpm) {
return Math.round((60 * audioCtx.sampleRate / 4) / bpm)
}
class SoundWriter {
constructor (audioCtx, instr, n, bpm) {
this.audioCtx = audioCtx
this.instr = instr
this.n = n
this.bpm = bpm
this.c1 = 0
this.c2 = 0
this.low = 0
this.band = 0
this.j = 0
}
write (lchan, rchan, from) {
const instr = this.instr
const n = this.n
let c = from
const osc_lfo = oscillators[instr.lfo_waveform]
const osc1 = oscillators[instr.osc1_waveform]
const osc2 = oscillators[instr.osc2_waveform]
const panFreq = Math.pow(2, instr.fx_pan_freq - 8) / effectiveRowLen(this.audioCtx, this.bpm)
const lfoFreq = Math.pow(2, instr.lfo_freq - 8) / effectiveRowLen(this.audioCtx, this.bpm)
const attackTime = instr.env_attack / 44100
const releaseTime = instr.env_release / 44100
const sustainTime = instr.env_sustain / 44100
const env_attack = attackTime * this.audioCtx.sampleRate
const env_release = releaseTime * this.audioCtx.sampleRate
const env_sustain = sustainTime * this.audioCtx.sampleRate
// Precalculate frequencues
const o1t = getnotefreq(this.audioCtx, n + (instr.osc1_oct - 8) * 12 + instr.osc1_det) * (1 + 0.0008 * instr.osc1_detune)
const o2t = getnotefreq(this.audioCtx, n + (instr.osc2_oct - 8) * 12 + instr.osc2_det) * (1 + 0.0008 * instr.osc2_detune)
// State variable init
const q = instr.fx_resonance / 255
while (this.j < env_attack + env_sustain + env_release && c < lchan.length) {
// LFO
const lfor = osc_lfo(this.j * lfoFreq) * instr.lfo_amt / 512 + 0.5
// Envelope
let e = 1
if (this.j < env_attack) {
e = this.j / env_attack
} else if (this.j >= env_attack + env_sustain) {
e -= (this.j - env_attack - env_sustain) / env_release
}
// Oscillator 1
let t = o1t
if (instr.lfo_osc1_freq) {
t += lfor
}
if (instr.osc1_xenv) {
t *= e * e
}
this.c1 += t
let rsample = osc1(this.c1) * instr.osc1_vol
// Oscillator 2
t = o2t
if (instr.osc2_xenv) {
t *= e * e
}
this.c2 += t
rsample += osc2(this.c2) * instr.osc2_vol
// Noise oscillator
if (instr.noise_fader) {
rsample += (2 * Math.random() - 1) * instr.noise_fader * e
}
rsample *= e / 255
// State variable filter
let f = instr.fx_freq
if (instr.lfo_fx_freq) {
f *= lfor
}
f = 1.5 * Math.sin(f * Math.PI / this.audioCtx.sampleRate)
this.low += f * this.band
const high = q * (rsample - this.band) - this.low
this.band += f * high
switch (instr.fx_filter) {
case 1: // Hipass
rsample = high
break
case 2: // Lopass
rsample = this.low
break
case 3: // Bandpass
rsample = this.band
break
case 4: // Notch
rsample = this.low + high
break
default:
}
// Panning & master volume
t = osc_sin(this.j * panFreq) * instr.fx_pan_amt / 512 + 0.5
rsample *= 39 * instr.env_master
let x = 32768 + rsample * (1 - t)
let x1 = x & 255
let x2 = (x >> 8) & 255
let y = 4 * (x1 + (x2 << 8) - 32768)
y = y < -32768 ? -32768 : (y > 32767 ? 32767 : y)
lchan[c] = lchan[c] + (y / 32768)
x = 32768 + rsample * (t)
x1 = x & 255
x2 = (x >> 8) & 255
y = 4 * (x1 + (x2 << 8) - 32768)
y = y < -32768 ? -32768 : (y > 32767 ? 32767 : y)
rchan[c] = rchan[c] + (y / 32768)
this.j++
c++
}
// returns true if the sound finished
if (c < lchan.length) {
return true
}
return false
}
}
class TrackGenerator {
constructor (audioCtx, instr, bpm, endPattern) {
bpm = bpm || 118
endPattern = endPattern || instr.p.length - 1
this.audioCtx = audioCtx
this.instr = instr
this.bpm = bpm
this.endPattern = endPattern
const source = this.audioCtx.createOscillator()
const nullGain = this.audioCtx.createGain()
nullGain.gain.value = 0
source.connect(nullGain)
const scriptNode = this.audioCtx.createScriptProcessor(512, 2, 2)
nullGain.connect(scriptNode)
let currentSample = 0
let nextNote = 0
let sounds = []
scriptNode.onaudioprocess = (audioProcessingEvent) => {
const inputData = audioProcessingEvent.inputBuffer
const outputData = audioProcessingEvent.outputBuffer
const lchan = outputData.getChannelData(0)
const rchan = outputData.getChannelData(1)
lchan.set(inputData.getChannelData(0))
rchan.set(inputData.getChannelData(1))
sounds.slice().forEach((el) => {
const finished = el.write(lchan, rchan, 0)
if (finished) {
sounds = sounds.filter((el2) => {
return el2 !== el
})
}
})
let nextNoteSample = nextNote * effectiveRowLen(this.audioCtx, this.bpm)
while (nextNoteSample >= currentSample &&
nextNoteSample < currentSample + inputData.length) {
const pattern = instr.p[Math.floor(nextNote / 32) % (this.endPattern + 1)] || 0
const note = pattern === 0 ? 0 : (instr.c[pattern - 1] || { n: [] }).n[nextNote % 32] || 0
if (note !== 0) {
const sw = new SoundWriter(this.audioCtx, instr, note, this.bpm)
sw.write(lchan, rchan, nextNoteSample - currentSample)
sounds.push(sw)
}
nextNote += 1
nextNoteSample = nextNote * effectiveRowLen(this.audioCtx, this.bpm)
}
currentSample += inputData.length
}
const delayTime = instr.fx_delay_time * ((1 / (this.bpm / 60)) / 8)
const delayAmount = instr.fx_delay_amt / 255
const delayGain = this.audioCtx.createGain()
delayGain.gain.value = delayAmount
scriptNode.connect(delayGain)
const delay = this.audioCtx.createDelay()
delay.delayTime.value = delayTime
delayGain.connect(delay)
delay.connect(delayGain)
const mixer = this.audioCtx.createGain()
mixer.gain.value = 1
scriptNode.connect(mixer)
delay.connect(mixer)
this.chain = [source, nullGain, scriptNode, delayGain, delay, mixer]
}
start (when) {
this.chain[0].start(when)
}
stop (when) {
this.chain[0].stop(when)
this.chain[this.chain.length - 1].disconnect()
}
connect (target) {
this.chain[this.chain.length - 1].connect(target)
}
}
class MusicGenerator {
constructor (audioCtx, song) {
this.audioCtx = audioCtx
this.song = song
const mixer = this.audioCtx.createGain()
mixer.gain.value = 1
this.tracks = []
this.song.songData.forEach((el) => {
const track = new TrackGenerator(this.audioCtx, el, this.bpm, this.song.endPattern)
track.connect(mixer)
this.tracks.push(track)
})
this.chain = [this.tracks, mixer]
}
get bpm () {
// rowLen is a number of samples when using 44100hz
return Math.round((60 * 44100 / 4) / this.song.rowLen)
}
start (when) {
when = when || this.audioCtx.currentTime
this.tracks.forEach((t) => t.start(when))
}
stop (when) {
when = when || this.audioCtx.currentTime
this.tracks.forEach((t) => t.stop(when))
this.chain[this.chain.length - 1].disconnect()
}
connect (target) {
this.chain[this.chain.length - 1].connect(target)
}
}
/**
* Generates a single note from an instrument.
*
* @param {*} instr The instrument descriptor
* @param {*} n The note as a midi note
* @param {*} sampleRate The sample rate
* @param {*} bpm The bpm of the song
* @returns {AudioBuffer} The generated audio buffer
*/
export async function generateSound (instr, n, sampleRate, bpm = 120) {
const attackTime = instr.env_attack / 44100
const releaseTime = instr.env_release / 44100
const sustainTime = instr.env_sustain / 44100
const soundLenSeconds = attackTime + releaseTime + sustainTime + (8 * (1 / (bpm / 60)))
const nInstr = Object.assign({}, instr)
nInstr.p = [1, 0, 0, 0]
nInstr.c = [{
n: new Array(32).map(() => 0)
}]
nInstr.c[0].n[0] = n + 75
const audioCtx = new OfflineAudioContext(2, soundLenSeconds * sampleRate, sampleRate)
const soundGen = new TrackGenerator(audioCtx, nInstr, bpm, 0)
soundGen.connect(audioCtx.destination)
soundGen.start()
const buf = await audioCtx.startRendering()
return buf
}
/**
* Generates a complete song from a song description.
*
* @param {*} song The song description
* @param {*} options `sampleRate`: the sample rate
* @returns {AudioBuffer} The generated audio buffer
*/
export async function generateSong (song, sampleRate) {
const songLenSeconds = song.songLen
const audioCtx = new OfflineAudioContext(2, songLenSeconds * sampleRate, sampleRate)
const soundGen = new MusicGenerator(audioCtx, song)
soundGen.connect(audioCtx.destination)
soundGen.start()
const buf = await audioCtx.startRendering()
return buf
}