d127fb8d518496bc11ca877d01c2af8259959204
[pwl6.git] / src / yuu / audio.js
1 /* Copyright 2014 Yukkuri Games
2 Licensed under the terms of the GNU GPL v2 or later
3 @license https://www.gnu.org/licenses/gpl-2.0.html
4 @source: https://yukkurigames.com/yuu/
5 */
6
7 (function (yuu) {
8 "use strict";
9
10 var yT = this.yT || require("./yT");
11 var yf = this.yf || require("./yf");
12
13 yuu.Audio = yT({
14 /** Audio context/source/buffer accessor
15
16 You probably don't need to make this yourself; one is made
17 named yuu.audio during initialization.
18
19 You can set the master volume with yuu.audio.masterVolume.
20 */
21 constructor: function () {
22 this._ctx = new window.AudioContext();
23 this._compressor = this._ctx.createDynamicsCompressor();
24 this._masterVolume = this._ctx.createGain();
25 this._masterVolume.connect(this._compressor);
26 this._compressor.connect(this._ctx.destination);
27 this._musicVolume = this._ctx.createGain();
28 this._musicVolume.connect(this._masterVolume);
29 this._masterVolume.gain.value = 0.5;
30 this._musicVolume.gain.value = 0.5;
31
32 this._bufferCache = {};
33 this._mute = false;
34 this._storage = null;
35 this._volume = this._masterVolume.gain.value;
36 },
37
38 destination: { alias: "_masterVolume", readonly: true },
39 music: { alias: "_musicVolume", readonly: true },
40
41 _readStorage: function () {
42 if (!this._storage)
43 return;
44 yf.each.call(this, function (prop) {
45 this[prop] = this._storage.getObject(prop, this[prop]);
46 }, ["volume", "musicVolume", "mute"]);
47 },
48
49 _writeStorage: yf.debounce(function () {
50 if (!this._storage)
51 return;
52 yf.each.call(this, function (prop) {
53 this._storage.setObject(prop, this[prop]);
54 }, ["volume", "musicVolume", "mute"]);
55 }),
56
57 storage: {
58 get: function () { return this._storage; },
59 set: function (v) {
60 this._storage = v;
61 this._readStorage();
62 }
63 },
64
65 mute: {
66 get: function () { return this._mute; },
67 set: function (v) {
68 this._mute = !!v;
69 this.volume = this.volume;
70 }
71 },
72
73 volume: {
74 get: function () { return this._volume; },
75 set: function (v) {
76 this._volume = v;
77 v = this._mute ? 0 : v;
78 this._masterVolume.gain.value = v;
79 this._writeStorage();
80 }
81 },
82
83 musicVolume: {
84 get: function () { return this._musicVolume.gain.value; },
85 set: function (v) {
86 this._musicVolume.gain.value = v;
87 this._writeStorage();
88 }
89 },
90
91 currentTime: { alias: "_ctx.currentTime" },
92
93 decodeAudioData: function (data) {
94 var ctx = this._ctx;
95 try {
96 return ctx.decodeAudioData(data);
97 } catch (exc) {
98 return new Promise(function (resolve, reject) {
99 ctx.decodeAudioData(data, function (buffer) {
100 resolve(buffer);
101 }, function () {
102 reject(new Error("Error decoding audio buffer"));
103 });
104 });
105 }
106 },
107
108 createBufferSource: function (path) {
109 var source = this._ctx.createBufferSource();
110 var sample = yf.isString(path)
111 ? new yuu.AudioSample(path, this)
112 : path;
113 if ((source.buffer = sample.buffer) === null) {
114 sample.ready.then(function () {
115 source.buffer = sample.buffer;
116 });
117 }
118 return source;
119 },
120
121 sampleRate: { alias: "_ctx.sampleRate" },
122 createGain: { proxy: "_ctx.createGain" },
123 createOscillator: { proxy: "_ctx.createOscillator" },
124 });
125
126 // FIXME: This parsing is garbagey, would be better to parse when
127 // first handed a dfn and turn everything into a function.
128 function applyMod (s, v) {
129 if (yf.isFunction(s))
130 return s(v);
131 else if (s === +s)
132 return s;
133 else if (s[0] === "-" || s[0] === "+")
134 return v + (+s);
135 else if (s[0] === "x" || s[0] === "*")
136 return v * +s.substring(1);
137 else if (s[s.length - 1] === "%")
138 return v * (parseFloat(s) / 100);
139 else
140 return +s;
141 }
142
143 var Envelope = yuu.Envelope = yT({
144 constructor: function (timeline) {
145 timeline = timeline || { 0: 1 };
146 this.ts = Object.keys(timeline);
147 this.vs = yf.map.call(timeline, yf.getter, this.ts);
148 var ts = this.ts.filter(isFinite);
149 this.duration = (Math.max.apply(Math, ts)
150 - Math.min.apply(Math, ts));
151 this.unlimited = !this.duration || ts.length !== this.ts.length;
152 },
153
154 clampDuration: function (duration) {
155 return this.unlimited
156 ? Math.max(duration, this.duration)
157 : this.duration;
158 },
159
160 schedule: function (param, t0, scale, duration) {
161 yf.each(function (s, v) {
162 v = v * scale;
163 var t = t0 + applyMod(s, duration);
164 if (t === t0)
165 param.setValueAtTime(v, t);
166 else
167 param.linearRampToValueAtTime(v, t);
168 }, this.ts, this.vs);
169 }
170 });
171
172 yuu.AudioSample = yuu.Caching(yT({
173 constructor: function (path, ctx) {
174 ctx = ctx || yuu.audio;
175 var url = yuu.resourcePath(path, "sound", "wav");
176 this.data = null;
177 this.ready = yuu.GET(url, { responseType: "arraybuffer" })
178 .then(ctx.decodeAudioData.bind(ctx))
179 .then(yf.setter.bind(this, "buffer"))
180 .then(yf.K(this));
181 }
182 }), function (args) { return args.length <= 2 ? args[0] : null; });
183
184 yuu.Modulator = yT({
185 constructor: function (dfn) {
186 this.envelope = new Envelope(dfn.envelope);
187 this.frequency = dfn.frequency;
188 this.index = dfn.index || 1.0;
189 },
190
191 createModulator: function (ctx, t0, fundamental, duration) {
192 var modulator = ctx.createOscillator();
193 modulator.frequency.value = applyMod(
194 this.frequency, fundamental);
195 modulator.start(t0);
196 modulator.stop(t0 + duration);
197 var modulatorG = ctx.createGain();
198 modulator.connect(modulatorG);
199 this.envelope.schedule(
200 modulatorG.gain, t0, this.index * fundamental, duration);
201 return modulatorG;
202 }
203 });
204
205 var BaseInstrument = yT({
206 play: yf.argcd(
207 function () {
208 return this.play(null, 0, 0, 1, 1);
209 },
210 function (ctx, t, freq, amp, duration) {
211 ctx = ctx || yuu.audio;
212 t = t || ctx.currentTime;
213 var g = this.createSound(ctx, t, freq, amp, duration);
214 g.connect(ctx.destination);
215 return g;
216 }
217 )
218 });
219
220 var FastInstrument = yT(BaseInstrument, {
221 constructor: function (dfn) {
222 this.sample = new yuu.AudioSample(dfn);
223 this.ready = this.sample.ready.then(yf.K(this));
224 },
225
226 createSound: function (ctx, t0, fundamental, amplitude, duration) {
227 var src = ctx.createBufferSource(this.sample);
228 var ret = src;
229 src.start(t0, 0);
230 src.stop(t0 + duration);
231 if (amplitude !== 1.0) {
232 ret = ctx.createGain();
233 src.connect(ret);
234 ret.gain.value = amplitude;
235 }
236 return ret;
237 }
238 });
239
240 var Instrument = yT(BaseInstrument, {
241 constructor: function (dfn) {
242 this.envelope = new yuu.Envelope(dfn.envelope);
243 this.frequency = dfn.frequency || (dfn.sample ? {} : { "x1": 1.0 });
244 this.modulator = yf.map(
245 yf.new_(yuu.Modulator), yf.arrayify(dfn.modulator || []));
246 this.sample = dfn.sample || {};
247 this.ready = yuu.ready(
248 yf.map(yf.new_(yuu.AudioSample), Object.keys(this.sample)),
249 this);
250 },
251
252 createSound: function (ctx, t0, fundamental, amplitude, duration) {
253 duration = this.envelope.clampDuration(duration || 0);
254 var ret = ctx.createGain();
255 var dst = ret;
256
257 yf.ipairs(function (name, params) {
258 var buffer = new yuu.AudioSample(name).buffer;
259 if (buffer && !params.loop)
260 duration = Math.max(buffer.duration, duration);
261 }, this.sample);
262
263 var modulators = yf.map(function (modulator) {
264 return modulator.createModulator(
265 ctx, t0, fundamental, duration);
266 }, this.modulator);
267
268 yf.ipairs(function (name, params) {
269 var src = ctx.createBufferSource(name);
270 src.loop = params.loop || false;
271 src.playbackRate.value = applyMod(
272 params.playbackRate || 1, fundamental || ctx.sampleRate);
273 yf.each(function (mod) { mod.connect(src.playbackRate); },
274 modulators);
275 if (params.duration)
276 src.start(t0, params.offset || 0, params.duration);
277 else
278 src.start(t0, params.offset || 0);
279 src.stop(t0 + duration);
280 src.connect(dst);
281 }, this.sample);
282
283 yf.ipairs(function (mfreq, mamp) {
284 var osc = ctx.createOscillator();
285 osc.frequency.value = applyMod(mfreq, fundamental);
286 osc.start(t0);
287 osc.stop(t0 + duration);
288 yf.each(function (mod) { mod.connect(osc.frequency); },
289 modulators);
290 if (mamp !== 1) {
291 var gain = ctx.createGain();
292 gain.gain.value = mamp;
293 osc.connect(gain);
294 gain.connect(dst);
295 } else {
296 osc.connect(dst);
297 }
298 }, this.frequency);
299
300 ret.gain.value = 0;
301 this.envelope.schedule(ret.gain, t0, amplitude, duration);
302 return ret;
303 }
304 });
305
306 yuu.Instrument = function (dfn) {
307 return yf.isString(dfn)
308 ? new FastInstrument(dfn)
309 : new Instrument(dfn);
310 };
311
312 yuu.Instruments = yf.mapValues(yf.new_(yuu.Instrument), {
313 SINE: {
314 envelope: { "0": 0, "0.016": 1, "-0.016": 1, "100%": 0 },
315 },
316
317 ORGAN: {
318 envelope: { "0": 0, "0.016": 1, "-0.016": 1, "100%": 0 },
319 frequency: { "x1": 0.83, "x1.5": 0.17 }
320 },
321
322 SIREN: {
323 envelope: { "0": 1 },
324 modulator: {
325 envelope: { "0": 1 },
326 frequency: "1",
327 index: 0.2
328 }
329 },
330
331 BELL: {
332 envelope: { "0": 1, "2.5": 0.2, "5": 0 },
333 modulator: {
334 envelope: { "0": 1, "2.5": 0.2, "5": 0 },
335 frequency: "x1.5",
336 }
337 },
338
339 BRASS: {
340 envelope: { "0": 0, "0.2": 1, "0.4": 0.6, "-0.1": 0.5, "100%": 0 },
341 modulator: {
342 envelope: { "0": 0, "0.2": 1, "0.4": 0.6,
343 "-0.1": 0.5, "100%": 0 },
344 frequency: "x1",
345 index: 5.0
346 }
347 },
348 });
349
350 // Tune to A440 by default, although every interface should provide
351 // some ways to work around this. This gives C4 = ~261.63 Hz.
352 // https://en.wikipedia.org/wiki/Scientific_pitch_notation
353 yuu.C4_HZ = 440 * Math.pow(2, -9/12);
354
355 yuu.Scale = yT({
356 constructor: function (intervals) {
357 this.intervals = intervals;
358 this.length = this.intervals.length;
359 this.span = yf.foldl(function (a, b) { return a + b; }, intervals);
360 },
361
362 hz: function (tonic, degree, accidental) {
363 accidental = accidental || 0;
364 var s = this.span * ((degree / this.intervals.length) | 0)
365 + accidental;
366 degree %= this.intervals.length;
367 if (degree < 0) {
368 degree += this.intervals.length;
369 s -= this.span;
370 }
371 var i = 0;
372 while (degree >= 1) {
373 degree -= 1;
374 s += this.intervals[i];
375 i++;
376 }
377 if (degree > 0)
378 s += this.intervals[i] * degree;
379 return tonic * Math.pow(2, s / 1200.0);
380 }
381 });
382
383 yuu.Scales = yf.mapValues(yf.new_(yuu.Scale), {
384 CHROMATIC: yf.repeat(100, 12),
385 MINOR: [200, 100, 200, 200, 100, 200, 200],
386 MAJOR: [200, 200, 100, 200, 200, 200, 100],
387 WHOLE_TONE: [200, 200, 200, 200, 200, 200],
388 AUGMENTED: [300, 100, 300, 100, 300, 100],
389 _17ET: yf.repeat(1200 / 17, 17),
390 DOUBLE_HARMONIC: [100, 300, 100, 200, 100, 300, 100],
391 });
392
393 var DURATION = { T: 1/8, S: 1/4, I: 1/2, Q: 1, H: 2, W: 4,
394 ".": 1.5, "/": 1/3, "<": -1 };
395 var ACCIDENTAL = { b: -1, "#": 1, t: 0.5, d: -0.5 };
396
397 var NOTE = /([TSIQHW][<.\/]*)?(?:([XZ]|(?:[A-G][b#dt]*[0-9]+))|([+-]?[0-9.]+)([b#dt]*))|([-+<>{]|(?:[TSIQHW][.\/]?))/g;
398
399 var LETTERS = { Z: null, X: null };
400
401 yuu.parseNote = function (note, scale, C4) {
402 return (C4 || yuu.C4_HZ) * Math.pow(2, LETTERS[note] / 12);
403 };
404
405 yuu.parseScore = function (score, scale, tonic, C4) {
406 // Note language:
407 //
408 // To play a scientific pitch note and advance the time, just
409 // use its name: G4, Cb2, A#0
410 //
411 // To adjust the length of the note, use T, S, I, Q (default),
412 // H, W for 32nd through whole. Append . to do
413 // time-and-a-half. Append / to cut into a third. Append < to
414 // go back in time.
415 //
416 // To play a note on the provided scale, use a 0-based number
417 // (which can be negative). To move the current scale up or
418 // down, use + or -. For example, in C major, 0 and C4 produce
419 // the same note; after a -, 0 and C3 produce the same note.
420 //
421 // To rest, use Z or X.
422 //
423 // To play multiple notes at the same time, enclose them all with
424 // < ... >. The time will advance in accordance with the shortest
425 // one.
426 //
427 // To reset the time, scale offset, and duration, use a {.
428 // This can be more convenient when writing pieces with
429 // multiple parts than grouping, e.g.
430 // H < 1 8 > < 2 7 > < 3 6 > < 4 5 >
431 // is easier to understand when split into multiple lines:
432 // H 1 2 3 4
433 // { H 8 7 6 5
434
435 scale = scale || yuu.Scales.MAJOR;
436 C4 = C4 || yuu.C4_HZ;
437 tonic = tonic || scale.tonic || C4;
438 if (yf.isString(tonic))
439 tonic = yuu.parseNote(tonic, C4);
440
441 var t = 0;
442 var notes = [];
443 var degree = 0;
444 var groupLength = 0;
445 var defaultDuration = "Q";
446 var match;
447
448 function calcDuration (d, m) { return d * DURATION[m]; }
449 function calcAccidental (d, m) { return d * ACCIDENTAL[m]; }
450
451 while ((match = NOTE.exec(score))) {
452 switch (match[5]) {
453 case "<":
454 groupLength = Infinity;
455 break;
456 case ">":
457 t += groupLength === Infinity ? 0 : groupLength;
458 groupLength = 0;
459 break;
460 case "+":
461 degree += scale.length;
462 break;
463 case "-":
464 degree -= scale.length;
465 break;
466 case "{":
467 t = 0;
468 degree = 0;
469 groupLength = 0;
470 defaultDuration = "Q";
471 break;
472 default:
473 if (match[5]) {
474 defaultDuration = match[5];
475 continue;
476 }
477 var letter = match[2];
478 var duration = yf.foldl(
479 calcDuration, match[1] || defaultDuration, 1);
480 if (LETTERS[letter] !== null) {
481 var offset = match[3];
482 var accidental = yf.foldl(
483 calcAccidental, match[4] || "", 0) * 100;
484 notes.push({
485 time: t,
486 duration: duration,
487 hz: letter
488 ? C4 * Math.pow(2, LETTERS[letter]/12.0)
489 : scale.hz(tonic, degree + (+offset || 0), accidental)
490 });
491 }
492 if (groupLength && duration > 0)
493 groupLength = Math.min(groupLength, duration);
494 else
495 t += duration;
496 }
497 }
498
499 notes.sort(function (a, b) { return a.time - b.time; });
500 return notes;
501 };
502
503 yf.irange.call(LETTERS, function (i) {
504 yf.ipairs.call(this, function (l, o) {
505 var b = o + 12 * (i - 4);
506 this[l + i] = b;
507 yf.ipairs.call(this, function (s, m) {
508 this[l + s + i] = b + m;
509 }, ACCIDENTAL);
510 }, { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 });
511 }, 11);
512
513 yuu.registerInitHook(function () {
514 if (!window.AudioContext)
515 throw new Error("Web Audio isn't supported.");
516 yuu.audio = new yuu.Audio();
517 yuu.defaultCommands.volume = yuu.propcmd(
518 yuu.audio, "volume",
519 "get/set the current master audio volume", "0...1");
520 yuu.defaultCommands.musicVolume = yuu.propcmd(
521 yuu.audio, "musicVolume",
522 "get/set the current music volume", "0...1");
523 yuu.defaultCommands.mute = yuu.propcmd(
524 yuu.audio, "mute", "mute or unmute audio");
525 });
526
527 }).call(typeof exports === "undefined" ? this : exports,
528 typeof exports === "undefined"
529 ? this.yuu : (module.exports = require('./core')));