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