@eva/plugin-sound 1.1.1-fix.1 → 1.1.1-fix.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,733 @@
1
+ function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
2
+
3
+ window.EVA = window.EVA || {};
4
+ window.EVA.plugin = window.EVA.plugin || {};
5
+
6
+ var _EVA_IIFE_sound = function (exports, eva_js) {
7
+ 'use strict';
8
+
9
+ var _extendStatics = function extendStatics(d, b) {
10
+ _extendStatics = Object.setPrototypeOf || {
11
+ __proto__: []
12
+ } instanceof Array && function (d, b) {
13
+ d.__proto__ = b;
14
+ } || function (d, b) {
15
+ for (var p in b) {
16
+ if (b.hasOwnProperty(p)) d[p] = b[p];
17
+ }
18
+ };
19
+
20
+ return _extendStatics(d, b);
21
+ };
22
+
23
+ function __extends(d, b) {
24
+ _extendStatics(d, b);
25
+
26
+ function __() {
27
+ this.constructor = d;
28
+ }
29
+
30
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31
+ }
32
+
33
+ function __decorate(decorators, target, key, desc) {
34
+ var c = arguments.length,
35
+ r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
36
+ d;
37
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {
38
+ if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
39
+ }
40
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
41
+ }
42
+
43
+ function __awaiter(thisArg, _arguments, P, generator) {
44
+ function adopt(value) {
45
+ return value instanceof P ? value : new P(function (resolve) {
46
+ resolve(value);
47
+ });
48
+ }
49
+
50
+ return new (P || (P = Promise))(function (resolve, reject) {
51
+ function fulfilled(value) {
52
+ try {
53
+ step(generator.next(value));
54
+ } catch (e) {
55
+ reject(e);
56
+ }
57
+ }
58
+
59
+ function rejected(value) {
60
+ try {
61
+ step(generator["throw"](value));
62
+ } catch (e) {
63
+ reject(e);
64
+ }
65
+ }
66
+
67
+ function step(result) {
68
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
69
+ }
70
+
71
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
72
+ });
73
+ }
74
+
75
+ function __generator(thisArg, body) {
76
+ var _ = {
77
+ label: 0,
78
+ sent: function sent() {
79
+ if (t[0] & 1) throw t[1];
80
+ return t[1];
81
+ },
82
+ trys: [],
83
+ ops: []
84
+ },
85
+ f,
86
+ y,
87
+ t,
88
+ g;
89
+ return g = {
90
+ next: verb(0),
91
+ "throw": verb(1),
92
+ "return": verb(2)
93
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
94
+ return this;
95
+ }), g;
96
+
97
+ function verb(n) {
98
+ return function (v) {
99
+ return step([n, v]);
100
+ };
101
+ }
102
+
103
+ function step(op) {
104
+ if (f) throw new TypeError("Generator is already executing.");
105
+
106
+ while (_) {
107
+ try {
108
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
109
+ if (y = 0, t) op = [op[0] & 2, t.value];
110
+
111
+ switch (op[0]) {
112
+ case 0:
113
+ case 1:
114
+ t = op;
115
+ break;
116
+
117
+ case 4:
118
+ _.label++;
119
+ return {
120
+ value: op[1],
121
+ done: false
122
+ };
123
+
124
+ case 5:
125
+ _.label++;
126
+ y = op[1];
127
+ op = [0];
128
+ continue;
129
+
130
+ case 7:
131
+ op = _.ops.pop();
132
+
133
+ _.trys.pop();
134
+
135
+ continue;
136
+
137
+ default:
138
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
139
+ _ = 0;
140
+ continue;
141
+ }
142
+
143
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
144
+ _.label = op[1];
145
+ break;
146
+ }
147
+
148
+ if (op[0] === 6 && _.label < t[1]) {
149
+ _.label = t[1];
150
+ t = op;
151
+ break;
152
+ }
153
+
154
+ if (t && _.label < t[2]) {
155
+ _.label = t[2];
156
+
157
+ _.ops.push(op);
158
+
159
+ break;
160
+ }
161
+
162
+ if (t[2]) _.ops.pop();
163
+
164
+ _.trys.pop();
165
+
166
+ continue;
167
+ }
168
+
169
+ op = body.call(thisArg, _);
170
+ } catch (e) {
171
+ op = [6, e];
172
+ y = 0;
173
+ } finally {
174
+ f = t = 0;
175
+ }
176
+ }
177
+
178
+ if (op[0] & 5) throw op[1];
179
+ return {
180
+ value: op[0] ? op[1] : void 0,
181
+ done: true
182
+ };
183
+ }
184
+ }
185
+
186
+ function __values(o) {
187
+ var s = typeof Symbol === "function" && Symbol.iterator,
188
+ m = s && o[s],
189
+ i = 0;
190
+ if (m) return m.call(o);
191
+ if (o && typeof o.length === "number") return {
192
+ next: function next() {
193
+ if (o && i >= o.length) o = void 0;
194
+ return {
195
+ value: o && o[i++],
196
+ done: !o
197
+ };
198
+ }
199
+ };
200
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
201
+ }
202
+
203
+ var SoundSystem = function (_super) {
204
+ __extends(SoundSystem, _super);
205
+
206
+ function SoundSystem(obj) {
207
+ var _this = _super.call(this) || this;
208
+
209
+ _this.autoPauseAndStart = true;
210
+ _this.components = [];
211
+ _this.pausedComponents = [];
212
+ _this.audioBufferCache = {};
213
+ _this.decodeAudioPromiseMap = {};
214
+
215
+ _extends(_this, obj);
216
+
217
+ return _this;
218
+ }
219
+
220
+ Object.defineProperty(SoundSystem.prototype, "muted", {
221
+ get: function get() {
222
+ return this.gainNode ? this.gainNode.gain.value === 0 : false;
223
+ },
224
+ set: function set(v) {
225
+ if (!this.gainNode) {
226
+ return;
227
+ }
228
+
229
+ this.gainNode.gain.setValueAtTime(v ? 0 : 1, 0);
230
+ },
231
+ enumerable: false,
232
+ configurable: true
233
+ });
234
+ Object.defineProperty(SoundSystem.prototype, "volume", {
235
+ get: function get() {
236
+ return this.gainNode ? this.gainNode.gain.value : 1;
237
+ },
238
+ set: function set(v) {
239
+ if (!this.gainNode || typeof v !== 'number' || v < 0 || v > 1) {
240
+ return;
241
+ }
242
+
243
+ this.gainNode.gain.setValueAtTime(v, 0);
244
+ },
245
+ enumerable: false,
246
+ configurable: true
247
+ });
248
+ Object.defineProperty(SoundSystem.prototype, "audioLocked", {
249
+ get: function get() {
250
+ if (!this.ctx) {
251
+ return true;
252
+ }
253
+
254
+ return this.ctx.state !== 'running';
255
+ },
256
+ enumerable: false,
257
+ configurable: true
258
+ });
259
+
260
+ SoundSystem.prototype.resumeAll = function () {
261
+ var _this = this;
262
+
263
+ var handleResume = function handleResume() {
264
+ _this.pausedComponents.forEach(function (component) {
265
+ component.play();
266
+ });
267
+
268
+ _this.pausedComponents = [];
269
+ };
270
+
271
+ this.ctx.resume().then(handleResume, handleResume);
272
+ };
273
+
274
+ SoundSystem.prototype.pauseAll = function () {
275
+ var _this = this;
276
+
277
+ this.components.forEach(function (component) {
278
+ if (component.playing) {
279
+ _this.pausedComponents.push(component);
280
+
281
+ component.pause();
282
+ }
283
+ });
284
+ this.ctx.suspend().then();
285
+ };
286
+
287
+ SoundSystem.prototype.stopAll = function () {
288
+ this.components.forEach(function (component) {
289
+ if (component.playing) {
290
+ component.stop();
291
+ }
292
+ });
293
+ this.pausedComponents = [];
294
+ this.ctx.suspend().then();
295
+ };
296
+
297
+ SoundSystem.prototype.init = function () {
298
+ this.setupAudioContext();
299
+ };
300
+
301
+ SoundSystem.prototype.update = function () {
302
+ var e_1, _a;
303
+
304
+ var changes = this.componentObserver.clear();
305
+
306
+ try {
307
+ for (var changes_1 = __values(changes), changes_1_1 = changes_1.next(); !changes_1_1.done; changes_1_1 = changes_1.next()) {
308
+ var changed = changes_1_1.value;
309
+ this.componentChanged(changed);
310
+ }
311
+ } catch (e_1_1) {
312
+ e_1 = {
313
+ error: e_1_1
314
+ };
315
+ } finally {
316
+ try {
317
+ if (changes_1_1 && !changes_1_1.done && (_a = changes_1.return)) _a.call(changes_1);
318
+ } finally {
319
+ if (e_1) throw e_1.error;
320
+ }
321
+ }
322
+ };
323
+
324
+ SoundSystem.prototype.onResume = function () {
325
+ if (!this.autoPauseAndStart) {
326
+ return;
327
+ }
328
+
329
+ this.resumeAll();
330
+ };
331
+
332
+ SoundSystem.prototype.onPause = function () {
333
+ if (!this.autoPauseAndStart) {
334
+ return;
335
+ }
336
+
337
+ this.pauseAll();
338
+ };
339
+
340
+ SoundSystem.prototype.onDestroy = function () {
341
+ this.components.forEach(function (component) {
342
+ component.onDestroy();
343
+ });
344
+ this.components = [];
345
+
346
+ if (this.ctx) {
347
+ this.gainNode.disconnect();
348
+ this.gainNode = null;
349
+ this.ctx.close();
350
+ this.ctx = null;
351
+ }
352
+ };
353
+
354
+ SoundSystem.prototype.componentChanged = function (changed) {
355
+ return __awaiter(this, void 0, void 0, function () {
356
+ return __generator(this, function (_a) {
357
+ if (changed.componentName !== 'Sound') return [2];
358
+
359
+ if (changed.type === eva_js.OBSERVER_TYPE.ADD) {
360
+ this.add(changed);
361
+ }
362
+
363
+ return [2];
364
+ });
365
+ });
366
+ };
367
+
368
+ SoundSystem.prototype.setupAudioContext = function () {
369
+ try {
370
+ var AudioContext_1 = window.AudioContext || window.webkitAudioContext;
371
+ this.ctx = new AudioContext_1();
372
+ } catch (error) {
373
+ console.error(error);
374
+
375
+ if (this.onError) {
376
+ this.onError(error);
377
+ }
378
+ }
379
+
380
+ if (!this.ctx) {
381
+ return;
382
+ }
383
+
384
+ this.gainNode = typeof this.ctx.createGain === 'undefined' ? this.ctx.createGainNode() : this.ctx.createGain();
385
+ this.gainNode.gain.setValueAtTime(this.muted ? 0 : this.volume, this.ctx.currentTime);
386
+ this.gainNode.connect(this.ctx.destination);
387
+ this.unlockAudio();
388
+ };
389
+
390
+ SoundSystem.prototype.unlockAudio = function () {
391
+ var _this = this;
392
+
393
+ if (!this.ctx || !this.audioLocked) {
394
+ return;
395
+ }
396
+
397
+ var unlock = function unlock() {
398
+ if (_this.ctx) {
399
+ var removeListenerFn = function removeListenerFn() {
400
+ document.body.removeEventListener('touchstart', unlock);
401
+ document.body.removeEventListener('touchend', unlock);
402
+ document.body.removeEventListener('click', unlock);
403
+ };
404
+
405
+ _this.ctx.resume().then(removeListenerFn, removeListenerFn);
406
+ }
407
+ };
408
+
409
+ document.body.addEventListener('touchstart', unlock);
410
+ document.body.addEventListener('touchend', unlock);
411
+ document.body.addEventListener('click', unlock);
412
+ };
413
+
414
+ SoundSystem.prototype.add = function (changed) {
415
+ var _a;
416
+
417
+ return __awaiter(this, void 0, void 0, function () {
418
+ var component, config, audio, _b, _c, error_1;
419
+
420
+ return __generator(this, function (_d) {
421
+ switch (_d.label) {
422
+ case 0:
423
+ component = changed.component;
424
+ this.components.push(component);
425
+ _d.label = 1;
426
+
427
+ case 1:
428
+ _d.trys.push([1, 5,, 6]);
429
+
430
+ config = component.config;
431
+ component.state = 'loading';
432
+ return [4, eva_js.resource.getResource(config.resource)];
433
+
434
+ case 2:
435
+ audio = _d.sent();
436
+ if (!(!this.audioBufferCache[audio.name] && ((_a = audio === null || audio === void 0 ? void 0 : audio.data) === null || _a === void 0 ? void 0 : _a.audio))) return [3, 4];
437
+ _b = this.audioBufferCache;
438
+ _c = audio.name;
439
+ return [4, this.decodeAudioData(audio.data.audio, audio.name)];
440
+
441
+ case 3:
442
+ _b[_c] = _d.sent();
443
+ _d.label = 4;
444
+
445
+ case 4:
446
+ if (this.audioBufferCache[audio.name]) {
447
+ component.systemContext = this.ctx;
448
+ component.systemDestination = this.gainNode;
449
+ component.onload(this.audioBufferCache[audio.name]);
450
+ }
451
+
452
+ return [3, 6];
453
+
454
+ case 5:
455
+ error_1 = _d.sent();
456
+
457
+ if (this.onError) {
458
+ this.onError(error_1);
459
+ }
460
+
461
+ return [3, 6];
462
+
463
+ case 6:
464
+ return [2];
465
+ }
466
+ });
467
+ });
468
+ };
469
+
470
+ SoundSystem.prototype.decodeAudioData = function (arraybuffer, name) {
471
+ var _this = this;
472
+
473
+ if (this.decodeAudioPromiseMap[name]) {
474
+ return this.decodeAudioPromiseMap[name];
475
+ }
476
+
477
+ var promise = new Promise(function (resolve, reject) {
478
+ if (!_this.ctx) {
479
+ reject(new Error('No audio support'));
480
+ }
481
+
482
+ var success = function success(decodedData) {
483
+ if (_this.decodeAudioPromiseMap[name]) {
484
+ delete _this.decodeAudioPromiseMap[name];
485
+ }
486
+
487
+ if (decodedData) {
488
+ resolve(decodedData);
489
+ } else {
490
+ reject(new Error("Error decoding audio " + name));
491
+ }
492
+ };
493
+
494
+ var error = function error(err) {
495
+ if (_this.decodeAudioPromiseMap[name]) {
496
+ delete _this.decodeAudioPromiseMap[name];
497
+ }
498
+
499
+ reject(new Error(err + ". arrayBuffer byteLength: " + (arraybuffer ? arraybuffer.byteLength : 0)));
500
+ };
501
+
502
+ var promise = _this.ctx.decodeAudioData(arraybuffer, success, error);
503
+
504
+ if (promise instanceof Promise) {
505
+ promise.catch(function (err) {
506
+ reject(new Error("catch " + err + ", arrayBuffer byteLength: " + (arraybuffer ? arraybuffer.byteLength : 0)));
507
+ });
508
+ }
509
+ });
510
+ this.decodeAudioPromiseMap[name] = promise;
511
+ return promise;
512
+ };
513
+
514
+ SoundSystem.systemName = 'SoundSystem';
515
+ SoundSystem = __decorate([eva_js.decorators.componentObserver({
516
+ Sound: []
517
+ })], SoundSystem);
518
+ return SoundSystem;
519
+ }(eva_js.System);
520
+
521
+ var SoundSystem$1 = SoundSystem;
522
+
523
+ var Sound = function (_super) {
524
+ __extends(Sound, _super);
525
+
526
+ function Sound() {
527
+ var _this = _super !== null && _super.apply(this, arguments) || this;
528
+
529
+ _this.state = 'unloaded';
530
+ _this.config = {
531
+ resource: '',
532
+ autoplay: false,
533
+ muted: false,
534
+ volume: 1,
535
+ loop: false,
536
+ seek: 0
537
+ };
538
+ _this.playTime = 0;
539
+ _this.startTime = 0;
540
+ _this.duration = 0;
541
+ _this.actionQueue = [];
542
+ return _this;
543
+ }
544
+
545
+ Object.defineProperty(Sound.prototype, "muted", {
546
+ get: function get() {
547
+ return this.gainNode ? this.gainNode.gain.value === 0 : false;
548
+ },
549
+ set: function set(v) {
550
+ if (!this.gainNode) {
551
+ return;
552
+ }
553
+
554
+ this.gainNode.gain.setValueAtTime(v ? 0 : this.config.volume, 0);
555
+ },
556
+ enumerable: false,
557
+ configurable: true
558
+ });
559
+ Object.defineProperty(Sound.prototype, "volume", {
560
+ get: function get() {
561
+ return this.gainNode ? this.gainNode.gain.value : 1;
562
+ },
563
+ set: function set(v) {
564
+ if (typeof v !== 'number' || v < 0 || v > 1) {
565
+ return;
566
+ }
567
+
568
+ this.config.volume = v;
569
+
570
+ if (!this.gainNode) {
571
+ return;
572
+ }
573
+
574
+ this.gainNode.gain.setValueAtTime(v, 0);
575
+ },
576
+ enumerable: false,
577
+ configurable: true
578
+ });
579
+
580
+ Sound.prototype.init = function (obj) {
581
+ if (!obj) {
582
+ return;
583
+ }
584
+
585
+ _extends(this.config, obj);
586
+
587
+ if (this.config.autoplay) {
588
+ this.actionQueue.push(this.play.bind(this));
589
+ }
590
+ };
591
+
592
+ Sound.prototype.play = function () {
593
+ var _this = this;
594
+
595
+ if (this.state !== 'loaded') {
596
+ this.actionQueue.push(this.play.bind(this));
597
+ }
598
+
599
+ this.destroySource();
600
+ this.createSource();
601
+
602
+ if (!this.sourceNode) {
603
+ return;
604
+ }
605
+
606
+ var when = this.systemContext.currentTime;
607
+ var offset = this.config.seek;
608
+ var duration = this.config.duration;
609
+ this.sourceNode.start(0, offset, duration);
610
+ this.startTime = when;
611
+ this.playTime = when - offset;
612
+ this.paused = false;
613
+ this.playing = true;
614
+ this.resetConfig();
615
+
616
+ this.endedListener = function () {
617
+ if (!_this.sourceNode) {
618
+ return;
619
+ }
620
+
621
+ if (_this.config.onEnd) {
622
+ _this.config.onEnd();
623
+ }
624
+
625
+ if (_this.playing) {
626
+ _this.destroySource();
627
+ }
628
+ };
629
+
630
+ this.sourceNode.addEventListener('ended', this.endedListener);
631
+ };
632
+
633
+ Sound.prototype.pause = function () {
634
+ if (this.state !== 'loaded') {
635
+ this.actionQueue.push(this.pause.bind(this));
636
+ }
637
+
638
+ if (this.paused || !this.playing) {
639
+ return;
640
+ }
641
+
642
+ this.paused = true;
643
+ this.playing = false;
644
+ this.config.seek = this.getCurrentTime();
645
+ this.destroySource();
646
+ };
647
+
648
+ Sound.prototype.stop = function () {
649
+ if (this.state !== 'loaded') {
650
+ this.actionQueue.push(this.stop.bind(this));
651
+ }
652
+
653
+ if (!this.paused && !this.playing) {
654
+ return;
655
+ }
656
+
657
+ this.playing = false;
658
+ this.paused = false;
659
+ this.destroySource();
660
+ this.resetConfig();
661
+ };
662
+
663
+ Sound.prototype.onload = function (buffer) {
664
+ this.state = 'loaded';
665
+ this.buffer = buffer;
666
+ this.duration = this.buffer.duration;
667
+ this.actionQueue.forEach(function (action) {
668
+ return action();
669
+ });
670
+ this.actionQueue.length = 0;
671
+ };
672
+
673
+ Sound.prototype.onDestroy = function () {
674
+ this.actionQueue.length = 0;
675
+ this.destroySource();
676
+ };
677
+
678
+ Sound.prototype.resetConfig = function () {
679
+ this.config.seek = 0;
680
+ };
681
+
682
+ Sound.prototype.getCurrentTime = function () {
683
+ if (this.config.loop && this.duration > 0) {
684
+ return (this.systemContext.currentTime - this.playTime) % this.duration;
685
+ }
686
+
687
+ return this.systemContext.currentTime - this.playTime;
688
+ };
689
+
690
+ Sound.prototype.createSource = function () {
691
+ if (!this.systemContext || this.state !== 'loaded') {
692
+ return;
693
+ }
694
+
695
+ this.sourceNode = this.systemContext.createBufferSource();
696
+ this.sourceNode.buffer = this.buffer;
697
+ this.sourceNode.loop = this.config.loop;
698
+
699
+ if (!this.gainNode) {
700
+ this.gainNode = this.systemContext.createGain();
701
+ this.gainNode.connect(this.systemDestination);
702
+
703
+ _extends(this, this.config);
704
+ }
705
+
706
+ this.sourceNode.connect(this.gainNode);
707
+ };
708
+
709
+ Sound.prototype.destroySource = function () {
710
+ if (!this.sourceNode) return;
711
+ this.sourceNode.removeEventListener('ended', this.endedListener);
712
+ this.sourceNode.stop();
713
+ this.sourceNode.disconnect();
714
+ this.sourceNode = null;
715
+ this.startTime = 0;
716
+ this.playTime = 0;
717
+ this.playing = false;
718
+ };
719
+
720
+ Sound.componentName = 'Sound';
721
+ return Sound;
722
+ }(eva_js.Component);
723
+
724
+ var Sound$1 = Sound;
725
+ exports.Sound = Sound$1;
726
+ exports.SoundSystem = SoundSystem$1;
727
+ Object.defineProperty(exports, '__esModule', {
728
+ value: true
729
+ });
730
+ return exports;
731
+ }({}, EVA);
732
+
733
+ window.EVA.plugin.sound = window.EVA.plugin.sound || _EVA_IIFE_sound;
@@ -0,0 +1,2 @@
1
+ var t,e;t=this,e=function(t,e){"use strict";var o=function(t,e){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(t,e)};function n(t,e){function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function i(t,e,o,n){return new(o||(o=Promise))((function(i,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function u(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){var e;t.done?i(t.value):(e=t.value,e instanceof o?e:new o((function(t){t(e)}))).then(s,u)}a((n=n.apply(t,e||[])).next())}))}function r(t,e){var o,n,i,r,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return r={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function u(r){return function(u){return function(r){if(o)throw new TypeError("Generator is already executing.");for(;s;)try{if(o=1,n&&(i=2&r[0]?n.return:r[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,r[1])).done)return i;switch(n=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,n=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!((i=(i=s.trys).length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){s=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]<i[3])){s.label=r[1];break}if(6===r[0]&&s.label<i[1]){s.label=i[1],i=r;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(r);break}i[2]&&s.ops.pop(),s.trys.pop();continue}r=e.call(t,s)}catch(t){r=[6,t],n=0}finally{o=i=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,u])}}}var s=function(t){function o(e){var o=t.call(this)||this;return o.autoPauseAndStart=!0,o.components=[],o.pausedComponents=[],o.audioBufferCache={},o.decodeAudioPromiseMap={},Object.assign(o,e),o}return n(o,t),Object.defineProperty(o.prototype,"muted",{get:function(){return!!this.gainNode&&0===this.gainNode.gain.value},set:function(t){this.gainNode&&this.gainNode.gain.setValueAtTime(t?0:1,0)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"volume",{get:function(){return this.gainNode?this.gainNode.gain.value:1},set:function(t){!this.gainNode||"number"!=typeof t||t<0||t>1||this.gainNode.gain.setValueAtTime(t,0)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"audioLocked",{get:function(){return!this.ctx||"running"!==this.ctx.state},enumerable:!1,configurable:!0}),o.prototype.resumeAll=function(){var t=this,e=function(){t.pausedComponents.forEach((function(t){t.play()})),t.pausedComponents=[]};this.ctx.resume().then(e,e)},o.prototype.pauseAll=function(){var t=this;this.components.forEach((function(e){e.playing&&(t.pausedComponents.push(e),e.pause())})),this.ctx.suspend().then()},o.prototype.stopAll=function(){this.components.forEach((function(t){t.playing&&t.stop()})),this.pausedComponents=[],this.ctx.suspend().then()},o.prototype.init=function(){this.setupAudioContext()},o.prototype.update=function(){var t,e,o=this.componentObserver.clear();try{for(var n=function(t){var e="function"==typeof Symbol&&Symbol.iterator,o=e&&t[e],n=0;if(o)return o.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}(o),i=n.next();!i.done;i=n.next()){var r=i.value;this.componentChanged(r)}}catch(e){t={error:e}}finally{try{i&&!i.done&&(e=n.return)&&e.call(n)}finally{if(t)throw t.error}}},o.prototype.onPlay=function(){this.autoPauseAndStart&&this.resumeAll()},o.prototype.onPause=function(){this.autoPauseAndStart&&this.pauseAll()},o.prototype.onDestroy=function(){this.components.forEach((function(t){t.onDestroy()})),this.components=[],this.ctx&&(this.gainNode.disconnect(),this.gainNode=null,this.ctx.close(),this.ctx=null)},o.prototype.componentChanged=function(t){return i(this,void 0,void 0,(function(){return r(this,(function(o){return"Sound"!==t.componentName||t.type===e.OBSERVER_TYPE.ADD&&this.add(t),[2]}))}))},o.prototype.setupAudioContext=function(){try{var t=window.AudioContext||window.webkitAudioContext;this.ctx=new t}catch(t){console.error(t),this.onError&&this.onError(t)}this.ctx&&(this.gainNode=void 0===this.ctx.createGain?this.ctx.createGainNode():this.ctx.createGain(),this.gainNode.gain.setValueAtTime(this.muted?0:this.volume,this.ctx.currentTime),this.gainNode.connect(this.ctx.destination),this.unlockAudio())},o.prototype.unlockAudio=function(){var t=this;if(this.ctx&&this.audioLocked){var e=function(){if(t.ctx){var o=function(){document.body.removeEventListener("touchstart",e),document.body.removeEventListener("touchend",e),document.body.removeEventListener("click",e)};t.ctx.resume().then(o,o)}};document.body.addEventListener("touchstart",e),document.body.addEventListener("touchend",e),document.body.addEventListener("click",e)}},o.prototype.add=function(t){return i(this,void 0,void 0,(function(){var o,n,i,s,u,a;return r(this,(function(r){switch(r.label){case 0:o=t.component,this.components.push(o),r.label=1;case 1:return r.trys.push([1,5,,6]),n=o.config,o.state="loading",[4,e.resource.getResource(n.resource)];case 2:return i=r.sent(),this.audioBufferCache[i.name]?[3,4]:(s=this.audioBufferCache,u=i.name,[4,this.decodeAudioData(i.data.audio,i.name)]);case 3:s[u]=r.sent(),r.label=4;case 4:return this.audioBufferCache[i.name]&&(o.systemContext=this.ctx,o.systemDestination=this.gainNode,o.onload(this.audioBufferCache[i.name])),[3,6];case 5:return a=r.sent(),console.error(a),this.onError&&this.onError(a),[3,6];case 6:return[2]}}))}))},o.prototype.decodeAudioData=function(t,e){var o=this;if(this.decodeAudioPromiseMap[e])return this.decodeAudioPromiseMap[e];var n=new Promise((function(n,i){o.ctx||i(new Error("No audio support")),o.ctx.decodeAudioData(t,(function(t){o.decodeAudioPromiseMap[e]&&delete o.decodeAudioPromiseMap[e],t?n(t):i(new Error("Error decoding audio "+e))}),(function(n){o.decodeAudioPromiseMap[e]&&delete o.decodeAudioPromiseMap[e],i(new Error(n+". arrayBuffer byteLength: "+(t?t.byteLength:0)))}))}));return this.decodeAudioPromiseMap[e]=n,n},o.systemName="SoundSystem",o=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var u=t.length-1;u>=0;u--)(i=t[u])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s}([e.decorators.componentObserver({Sound:[]})],o)}(e.System),u=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.state="unloaded",e.config={resource:"",autoplay:!1,muted:!1,volume:1,loop:!1,seek:0},e.playTime=0,e.startTime=0,e.duration=0,e.actionQueue=[],e}return n(e,t),Object.defineProperty(e.prototype,"muted",{get:function(){return!!this.gainNode&&0===this.gainNode.gain.value},set:function(t){this.gainNode&&this.gainNode.gain.setValueAtTime(t?0:this.config.volume,0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"volume",{get:function(){return this.gainNode?this.gainNode.gain.value:1},set:function(t){"number"!=typeof t||t<0||t>1||(this.config.volume=t,this.gainNode&&this.gainNode.gain.setValueAtTime(t,0))},enumerable:!1,configurable:!0}),e.prototype.init=function(t){t&&(Object.assign(this.config,t),this.config.autoplay&&this.actionQueue.push(this.play.bind(this)))},e.prototype.play=function(){var t=this;if("loaded"!==this.state&&this.actionQueue.push(this.play.bind(this)),this.destroySource(),this.createSource(),this.sourceNode){var e=this.systemContext.currentTime,o=this.config.seek,n=this.config.duration;this.sourceNode.start(0,o,n),this.startTime=e,this.playTime=e-o,this.paused=!1,this.playing=!0,this.resetConfig(),this.endedListener=function(){t.sourceNode&&(t.config.onEnd&&t.config.onEnd(),t.playing&&t.destroySource())},this.sourceNode.addEventListener("ended",this.endedListener)}},e.prototype.pause=function(){"loaded"!==this.state&&this.actionQueue.push(this.pause.bind(this)),!this.paused&&this.playing&&(this.paused=!0,this.playing=!1,this.config.seek=this.getCurrentTime(),this.destroySource())},e.prototype.stop=function(){"loaded"!==this.state&&this.actionQueue.push(this.stop.bind(this)),(this.paused||this.playing)&&(this.playing=!1,this.paused=!1,this.destroySource(),this.resetConfig())},e.prototype.onload=function(t){this.state="loaded",this.buffer=t,this.duration=this.buffer.duration,this.actionQueue.forEach((function(t){return t()})),this.actionQueue.length=0},e.prototype.onDestroy=function(){this.actionQueue.length=0,this.destroySource()},e.prototype.resetConfig=function(){this.config.seek=0},e.prototype.getCurrentTime=function(){return this.config.loop&&this.duration>0?(this.systemContext.currentTime-this.playTime)%this.duration:this.systemContext.currentTime-this.playTime},e.prototype.createSource=function(){this.systemContext&&"loaded"===this.state&&(this.sourceNode=this.systemContext.createBufferSource(),this.sourceNode.buffer=this.buffer,this.sourceNode.loop=this.config.loop,this.gainNode||(this.gainNode=this.systemContext.createGain(),this.gainNode.connect(this.systemDestination),Object.assign(this,this.config)),this.sourceNode.connect(this.gainNode))},e.prototype.destroySource=function(){this.sourceNode&&(this.sourceNode.removeEventListener("ended",this.endedListener),this.sourceNode.stop(),this.sourceNode.disconnect(),this.sourceNode=null,this.startTime=0,this.playTime=0,this.playing=!1)},e.componentName="Sound",e}(e.Component);t.Sound=u,t.SoundSystem=s,Object.defineProperty(t,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@eva/eva.js")):"function"==typeof define&&define.amd?define(["exports","@eva/eva.js"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).EVA=t.EVA||{},t.EVA.plugin=t.EVA.plugin||{},t.EVA.plugin.sound={}),t.EVA);
2
+ //# sourceMappingURL=EVA.plugin.sound.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EVA.plugin.sound.min.js","sources":["../../../node_modules/tslib/tslib.es6.js","../lib/SoundSystem.ts","../lib/Sound.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","import { System, decorators, ComponentChanged, OBSERVER_TYPE, resource } from '@eva/eva.js';\nimport SoundComponent from './Sound';\n\ninterface SoundSystemParams {\n autoPauseAndStart?: boolean;\n onError: (error: any) => void;\n}\n\n@decorators.componentObserver({\n Sound: [],\n})\nclass SoundSystem extends System {\n static systemName = 'SoundSystem';\n\n private ctx: AudioContext;\n\n private gainNode: GainNode;\n\n /** 是否和游戏同步暂停和启动 */\n private autoPauseAndStart = true;\n\n private onError: (error: any) => void;\n\n private components: SoundComponent[] = [];\n\n private pausedComponents: SoundComponent[] = [];\n\n private audioBufferCache = {};\n\n private decodeAudioPromiseMap = {};\n\n get muted(): boolean {\n return this.gainNode ? this.gainNode.gain.value === 0 : false;\n }\n\n set muted(v: boolean) {\n if (!this.gainNode) {\n return;\n }\n this.gainNode.gain.setValueAtTime(v ? 0 : 1, 0);\n }\n\n get volume(): number {\n return this.gainNode ? this.gainNode.gain.value : 1;\n }\n\n set volume(v: number) {\n if (!this.gainNode || typeof v !== 'number' || v < 0 || v > 1) {\n return;\n }\n this.gainNode.gain.setValueAtTime(v, 0);\n }\n\n get audioLocked(): boolean {\n if (!this.ctx) {\n return true;\n }\n return this.ctx.state !== 'running';\n }\n\n constructor(obj?: SoundSystemParams) {\n super();\n Object.assign(this, obj);\n }\n\n /**\n * 恢复播放所有被暂停的音频\n */\n resumeAll() {\n const handleResume = () => {\n this.pausedComponents.forEach(component => {\n component.play();\n });\n // 清理之前缓存的暂停列表\n this.pausedComponents = [];\n };\n this.ctx.resume().then(handleResume, handleResume);\n }\n\n /**\n * 暂停所有正在播放的音频\n */\n pauseAll() {\n this.components.forEach(component => {\n if (component.playing) {\n this.pausedComponents.push(component);\n component.pause();\n }\n });\n this.ctx.suspend().then();\n }\n\n /**\n * 停止所有正在播放的音频\n */\n stopAll() {\n this.components.forEach(component => {\n if (component.playing) {\n component.stop();\n }\n });\n // 清理之前缓存的暂停列表\n this.pausedComponents = [];\n this.ctx.suspend().then();\n }\n\n /**\n * System 初始化用,可以配置参数,游戏未开始\n *\n * System init, set params, game is not begain\n */\n init() {\n this.setupAudioContext();\n }\n\n update() {\n const changes = this.componentObserver.clear();\n for (const changed of changes) {\n this.componentChanged(changed);\n }\n }\n\n /**\n * 游戏开始和游戏暂停后开始播放的时候调用。\n *\n * Called while the game to play when game pause.\n */\n onPlay() {\n if (!this.autoPauseAndStart) {\n return;\n }\n this.resumeAll();\n }\n\n /**\n * 游戏暂停的时候调用。\n *\n * Called while the game paused.\n */\n onPause() {\n if (!this.autoPauseAndStart) {\n return;\n }\n this.pauseAll();\n }\n\n /**\n * System 被销毁的时候调用。\n * Called while the system be destroyed.\n */\n onDestroy() {\n this.components.forEach(component => {\n component.onDestroy();\n });\n this.components = [];\n if (this.ctx) {\n this.gainNode.disconnect();\n this.gainNode = null;\n this.ctx.close();\n this.ctx = null;\n }\n }\n\n async componentChanged(changed: ComponentChanged) {\n if (changed.componentName !== 'Sound') {\n return;\n }\n if (changed.type === OBSERVER_TYPE.ADD) {\n this.add(changed);\n }\n }\n\n private setupAudioContext() {\n try {\n const AudioContext = window.AudioContext || (window as any).webkitAudioContext;\n this.ctx = new AudioContext();\n } catch (error) {\n console.error(error);\n if (this.onError) {\n this.onError(error);\n }\n }\n\n if (!this.ctx) {\n return;\n }\n this.gainNode =\n typeof this.ctx.createGain === 'undefined' ? (this.ctx as any).createGainNode() : this.ctx.createGain();\n this.gainNode.gain.setValueAtTime(this.muted ? 0 : this.volume, this.ctx.currentTime);\n this.gainNode.connect(this.ctx.destination);\n this.unlockAudio();\n }\n\n private unlockAudio() {\n if (!this.ctx || !this.audioLocked) {\n return;\n }\n\n const unlock = () => {\n if (this.ctx) {\n const removeListenerFn = () => {\n document.body.removeEventListener('touchstart', unlock);\n document.body.removeEventListener('touchend', unlock);\n document.body.removeEventListener('click', unlock);\n };\n this.ctx.resume().then(removeListenerFn, removeListenerFn);\n }\n };\n document.body.addEventListener('touchstart', unlock);\n document.body.addEventListener('touchend', unlock);\n document.body.addEventListener('click', unlock);\n }\n\n private async add(changed: ComponentChanged) {\n const component = changed.component as SoundComponent;\n this.components.push(component);\n try {\n const { config } = component;\n component.state = 'loading';\n\n const audio = await resource.getResource(config.resource);\n if (!this.audioBufferCache[audio.name]) {\n this.audioBufferCache[audio.name] = await this.decodeAudioData(audio.data.audio, audio.name);\n }\n if (this.audioBufferCache[audio.name]) {\n component.systemContext = this.ctx;\n component.systemDestination = this.gainNode;\n component.onload(this.audioBufferCache[audio.name]);\n }\n } catch (error) {\n console.error(error);\n if (this.onError) {\n this.onError(error);\n }\n }\n }\n\n private decodeAudioData(arraybuffer: ArrayBuffer, name: string) {\n if (this.decodeAudioPromiseMap[name]) {\n return this.decodeAudioPromiseMap[name];\n }\n const promise = new Promise<AudioBuffer>((resolve, reject) => {\n if (!this.ctx) {\n reject(new Error('No audio support'));\n }\n const error = (err: DOMException) => {\n if (this.decodeAudioPromiseMap[name]) {\n delete this.decodeAudioPromiseMap[name];\n }\n reject(new Error(`${err}. arrayBuffer byteLength: ${arraybuffer ? arraybuffer.byteLength : 0}`));\n };\n const success = (decodedData: AudioBuffer) => {\n if (this.decodeAudioPromiseMap[name]) {\n delete this.decodeAudioPromiseMap[name];\n }\n if (decodedData) {\n resolve(decodedData);\n } else {\n reject(new Error(`Error decoding audio ${name}`));\n }\n };\n\n this.ctx.decodeAudioData(arraybuffer, success, error);\n });\n this.decodeAudioPromiseMap[name] = promise;\n return promise;\n }\n}\n\nexport default SoundSystem;\n","import { Component } from '@eva/eva.js';\n\nexport interface SoundParams {\n resource: string;\n autoplay?: boolean;\n muted?: boolean;\n volume?: number;\n loop?: boolean;\n seek?: number;\n duration?: number;\n onEnd?: () => void;\n}\n\nclass Sound extends Component<SoundParams> {\n static componentName = 'Sound';\n\n systemContext: AudioContext;\n\n systemDestination: GainNode;\n\n playing: boolean;\n\n state: 'unloaded' | 'loading' | 'loaded' = 'unloaded';\n\n config: SoundParams = {\n resource: '',\n autoplay: false,\n muted: false,\n volume: 1,\n loop: false,\n seek: 0,\n };\n\n private buffer: AudioBuffer;\n\n private sourceNode: AudioBufferSourceNode;\n\n private gainNode: GainNode;\n\n private paused: boolean;\n\n private playTime: number = 0;\n\n // @ts-ignore\n private startTime: number = 0;\n\n private duration: number = 0;\n\n private actionQueue: (() => void)[] = [];\n\n private endedListener: () => void;\n\n get muted(): boolean {\n return this.gainNode ? this.gainNode.gain.value === 0 : false;\n }\n\n set muted(v: boolean) {\n if (!this.gainNode) {\n return;\n }\n this.gainNode.gain.setValueAtTime(v ? 0 : this.config.volume, 0);\n }\n\n get volume(): number {\n return this.gainNode ? this.gainNode.gain.value : 1;\n }\n\n set volume(v: number) {\n if (typeof v !== 'number' || v < 0 || v > 1) {\n return;\n }\n this.config.volume = v;\n if (!this.gainNode) {\n return;\n }\n this.gainNode.gain.setValueAtTime(v, 0);\n }\n\n init(obj?: SoundParams) {\n if (!obj) {\n return;\n }\n\n Object.assign(this.config, obj);\n if (this.config.autoplay) {\n this.actionQueue.push(this.play.bind(this));\n }\n }\n\n play() {\n if (this.state !== 'loaded') {\n this.actionQueue.push(this.play.bind(this));\n }\n this.destroySource();\n this.createSource();\n\n if (!this.sourceNode) {\n return;\n }\n const when = this.systemContext.currentTime;\n const offset = this.config.seek;\n const duration = this.config.duration;\n\n this.sourceNode.start(0, offset, duration);\n\n this.startTime = when;\n this.playTime = when - offset;\n this.paused = false;\n this.playing = true;\n this.resetConfig();\n this.endedListener = () => {\n if (!this.sourceNode) {\n return;\n }\n if (this.config.onEnd) {\n this.config.onEnd();\n }\n // 非交互事件播放完成需要销毁资源\n if (this.playing) {\n this.destroySource();\n }\n };\n this.sourceNode.addEventListener('ended', this.endedListener);\n }\n\n pause() {\n if (this.state !== 'loaded') {\n this.actionQueue.push(this.pause.bind(this));\n }\n if (this.paused || !this.playing) {\n return;\n }\n this.paused = true;\n this.playing = false;\n this.config.seek = this.getCurrentTime();\n this.destroySource();\n }\n\n stop() {\n if (this.state !== 'loaded') {\n this.actionQueue.push(this.stop.bind(this));\n }\n if (!this.paused && !this.playing) {\n return;\n }\n this.playing = false;\n this.paused = false;\n this.destroySource();\n this.resetConfig();\n }\n\n onload(buffer: AudioBuffer) {\n this.state = 'loaded';\n this.buffer = buffer;\n this.duration = this.buffer.duration;\n this.actionQueue.forEach(action => action());\n this.actionQueue.length = 0;\n }\n\n onDestroy() {\n this.actionQueue.length = 0;\n this.destroySource();\n }\n\n private resetConfig() {\n this.config.seek = 0;\n }\n\n private getCurrentTime() {\n if (this.config.loop && this.duration > 0) {\n return (this.systemContext.currentTime - this.playTime) % this.duration;\n }\n\n return this.systemContext.currentTime - this.playTime;\n }\n\n private createSource() {\n if (!this.systemContext || this.state !== 'loaded') {\n return;\n }\n this.sourceNode = this.systemContext.createBufferSource();\n this.sourceNode.buffer = this.buffer;\n this.sourceNode.loop = this.config.loop;\n\n if (!this.gainNode) {\n this.gainNode = this.systemContext.createGain();\n this.gainNode.connect(this.systemDestination);\n Object.assign(this, this.config);\n }\n this.sourceNode.connect(this.gainNode);\n }\n\n private destroySource() {\n if (!this.sourceNode) return;\n this.sourceNode.removeEventListener('ended', this.endedListener);\n this.sourceNode.stop();\n this.sourceNode.disconnect();\n this.sourceNode = null;\n\n this.startTime = 0;\n this.playTime = 0;\n this.playing = false;\n }\n}\n\nexport default Sound;\n"],"names":["extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","hasOwnProperty","__extends","__","this","constructor","prototype","create","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply","__generator","body","f","y","t","g","_","label","sent","trys","ops","verb","throw","return","Symbol","iterator","n","v","op","TypeError","call","pop","length","push","obj","_super","_this","assign","SoundSystem","gainNode","gain","setValueAtTime","ctx","state","handleResume","pausedComponents","forEach","component","play","resume","components","playing","pause","suspend","stop","setupAudioContext","changes","componentObserver","clear","changes_1","o","s","m","i","__values","changed","componentChanged","autoPauseAndStart","resumeAll","pauseAll","onDestroy","disconnect","close","componentName","type","OBSERVER_TYPE","ADD","add","AudioContext_1","window","AudioContext","webkitAudioContext","error","console","onError","createGain","createGainNode","muted","volume","currentTime","connect","destination","unlockAudio","audioLocked","unlock","removeListenerFn","document","removeEventListener","addEventListener","config","resource","getResource","audio","_c","audioBufferCache","name","_a","_b","decodeAudioData","data","systemContext","systemDestination","onload","error_1","arraybuffer","decodeAudioPromiseMap","promise","Error","decodedData","err","byteLength","decorators","target","key","desc","c","arguments","r","getOwnPropertyDescriptor","Reflect","decorate","defineProperty","Sound","System","autoplay","loop","seek","actionQueue","bind","destroySource","createSource","sourceNode","when","offset","duration","start","startTime","playTime","paused","resetConfig","endedListener","onEnd","getCurrentTime","buffer","action","createBufferSource","Component"],"mappings":"4CAgBA,IAAIA,EAAgB,SAASC,EAAGC,GAI5B,OAHAF,EAAgBG,OAAOC,gBAClB,CAAEC,UAAW,cAAgBC,OAAS,SAAUL,EAAGC,GAAKD,EAAEI,UAAYH,IACvE,SAAUD,EAAGC,GAAK,IAAK,IAAIK,KAAKL,EAAOA,EAAEM,eAAeD,KAAIN,EAAEM,GAAKL,EAAEK,MACpDN,EAAGC,IAGrB,SAASO,EAAUR,EAAGC,GAEzB,SAASQ,IAAOC,KAAKC,YAAcX,EADnCD,EAAc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BAAR,WACOhJ,KAAKyJ,aACVzJ,KAAKyJ,WAAW5C,oBAAoB,QAAS7G,KAAKkK,eAClDlK,KAAKyJ,WAAWvF,OAChBlE,KAAKyJ,WAAWtE,aAChBnF,KAAKyJ,WAAa,KAElBzJ,KAAK8J,UAAY,EACjB9J,KAAK+J,SAAW,EAChB/J,KAAK+D,SAAU,IA3LViF,gBAAgB,WADLwB"}
@@ -185,7 +185,7 @@ var SoundSystem = (function (_super) {
185
185
  finally { if (e_1) throw e_1.error; }
186
186
  }
187
187
  };
188
- SoundSystem.prototype.onPlay = function () {
188
+ SoundSystem.prototype.onResume = function () {
189
189
  if (!this.autoPauseAndStart) {
190
190
  return;
191
191
  }
@@ -212,9 +212,8 @@ var SoundSystem = (function (_super) {
212
212
  SoundSystem.prototype.componentChanged = function (changed) {
213
213
  return __awaiter(this, void 0, void 0, function () {
214
214
  return __generator(this, function (_a) {
215
- if (changed.componentName !== 'Sound') {
215
+ if (changed.componentName !== 'Sound')
216
216
  return [2];
217
- }
218
217
  if (changed.type === eva_js.OBSERVER_TYPE.ADD) {
219
218
  this.add(changed);
220
219
  }
@@ -262,28 +261,29 @@ var SoundSystem = (function (_super) {
262
261
  document.body.addEventListener('click', unlock);
263
262
  };
264
263
  SoundSystem.prototype.add = function (changed) {
264
+ var _a;
265
265
  return __awaiter(this, void 0, void 0, function () {
266
- var component, config, audio, _a, _b, error_1;
267
- return __generator(this, function (_c) {
268
- switch (_c.label) {
266
+ var component, config, audio, _b, _c, error_1;
267
+ return __generator(this, function (_d) {
268
+ switch (_d.label) {
269
269
  case 0:
270
270
  component = changed.component;
271
271
  this.components.push(component);
272
- _c.label = 1;
272
+ _d.label = 1;
273
273
  case 1:
274
- _c.trys.push([1, 5, , 6]);
274
+ _d.trys.push([1, 5, , 6]);
275
275
  config = component.config;
276
276
  component.state = 'loading';
277
277
  return [4, eva_js.resource.getResource(config.resource)];
278
278
  case 2:
279
- audio = _c.sent();
280
- if (!!this.audioBufferCache[audio.name]) return [3, 4];
281
- _a = this.audioBufferCache;
282
- _b = audio.name;
279
+ audio = _d.sent();
280
+ if (!(!this.audioBufferCache[audio.name] && ((_a = audio === null || audio === void 0 ? void 0 : audio.data) === null || _a === void 0 ? void 0 : _a.audio))) return [3, 4];
281
+ _b = this.audioBufferCache;
282
+ _c = audio.name;
283
283
  return [4, this.decodeAudioData(audio.data.audio, audio.name)];
284
284
  case 3:
285
- _a[_b] = _c.sent();
286
- _c.label = 4;
285
+ _b[_c] = _d.sent();
286
+ _d.label = 4;
287
287
  case 4:
288
288
  if (this.audioBufferCache[audio.name]) {
289
289
  component.systemContext = this.ctx;
@@ -292,8 +292,7 @@ var SoundSystem = (function (_super) {
292
292
  }
293
293
  return [3, 6];
294
294
  case 5:
295
- error_1 = _c.sent();
296
- console.error(error_1);
295
+ error_1 = _d.sent();
297
296
  if (this.onError) {
298
297
  this.onError(error_1);
299
298
  }
@@ -312,12 +311,6 @@ var SoundSystem = (function (_super) {
312
311
  if (!_this.ctx) {
313
312
  reject(new Error('No audio support'));
314
313
  }
315
- var error = function (err) {
316
- if (_this.decodeAudioPromiseMap[name]) {
317
- delete _this.decodeAudioPromiseMap[name];
318
- }
319
- reject(new Error(err + ". arrayBuffer byteLength: " + (arraybuffer ? arraybuffer.byteLength : 0)));
320
- };
321
314
  var success = function (decodedData) {
322
315
  if (_this.decodeAudioPromiseMap[name]) {
323
316
  delete _this.decodeAudioPromiseMap[name];
@@ -329,7 +322,18 @@ var SoundSystem = (function (_super) {
329
322
  reject(new Error("Error decoding audio " + name));
330
323
  }
331
324
  };
332
- _this.ctx.decodeAudioData(arraybuffer, success, error);
325
+ var error = function (err) {
326
+ if (_this.decodeAudioPromiseMap[name]) {
327
+ delete _this.decodeAudioPromiseMap[name];
328
+ }
329
+ reject(new Error(err + ". arrayBuffer byteLength: " + (arraybuffer ? arraybuffer.byteLength : 0)));
330
+ };
331
+ var promise = _this.ctx.decodeAudioData(arraybuffer, success, error);
332
+ if (promise instanceof Promise) {
333
+ promise.catch(function (err) {
334
+ reject(new Error("catch " + err + ", arrayBuffer byteLength: " + (arraybuffer ? arraybuffer.byteLength : 0)));
335
+ });
336
+ }
333
337
  });
334
338
  this.decodeAudioPromiseMap[name] = promise;
335
339
  return promise;
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("@eva/eva.js"),e=function(t,o){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])},e(t,o)};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("@eva/eva.js"),e=function(t,o){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(t,o)};
2
2
  /*! *****************************************************************************
3
3
  Copyright (c) Microsoft Corporation. All rights reserved.
4
4
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
@@ -12,4 +12,5 @@ MERCHANTABLITY OR NON-INFRINGEMENT.
12
12
 
13
13
  See the Apache Version 2.0 License for specific language governing permissions
14
14
  and limitations under the License.
15
- ***************************************************************************** */function o(t,o){function n(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}function n(t,e,o,n){return new(o||(o=Promise))((function(i,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function u(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){t.done?i(t.value):new o((function(e){e(t.value)})).then(s,u)}a((n=n.apply(t,e||[])).next())}))}function i(t,e){var o,n,i,r,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return r={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function u(r){return function(u){return function(r){if(o)throw new TypeError("Generator is already executing.");for(;s;)try{if(o=1,n&&(i=2&r[0]?n.return:r[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,r[1])).done)return i;switch(n=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,n=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){s=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]<i[3])){s.label=r[1];break}if(6===r[0]&&s.label<i[1]){s.label=i[1],i=r;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(r);break}i[2]&&s.ops.pop(),s.trys.pop();continue}r=e.call(t,s)}catch(t){r=[6,t],n=0}finally{o=i=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,u])}}}var r=function(e){function r(t){var o=e.call(this)||this;return o.autoPauseAndStart=!0,o.components=[],o.pausedComponents=[],o.audioBufferCache={},o.decodeAudioPromiseMap={},Object.assign(o,t),o}return o(r,e),Object.defineProperty(r.prototype,"muted",{get:function(){return!!this.gainNode&&0===this.gainNode.gain.value},set:function(t){this.gainNode&&this.gainNode.gain.setValueAtTime(t?0:1,0)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"volume",{get:function(){return this.gainNode?this.gainNode.gain.value:1},set:function(t){!this.gainNode||"number"!=typeof t||t<0||t>1||this.gainNode.gain.setValueAtTime(t,0)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"audioLocked",{get:function(){return!this.ctx||"running"!==this.ctx.state},enumerable:!1,configurable:!0}),r.prototype.resumeAll=function(){var t=this,e=function(){t.pausedComponents.forEach((function(t){t.play()})),t.pausedComponents=[]};this.ctx.resume().then(e,e)},r.prototype.pauseAll=function(){var t=this;this.components.forEach((function(e){e.playing&&(t.pausedComponents.push(e),e.pause())})),this.ctx.suspend().then()},r.prototype.stopAll=function(){this.components.forEach((function(t){t.playing&&t.stop()})),this.pausedComponents=[],this.ctx.suspend().then()},r.prototype.init=function(){this.setupAudioContext()},r.prototype.update=function(){var t,e,o=this.componentObserver.clear();try{for(var n=function(t){var e="function"==typeof Symbol&&t[Symbol.iterator],o=0;return e?e.call(t):{next:function(){return t&&o>=t.length&&(t=void 0),{value:t&&t[o++],done:!t}}}}(o),i=n.next();!i.done;i=n.next()){var r=i.value;this.componentChanged(r)}}catch(e){t={error:e}}finally{try{i&&!i.done&&(e=n.return)&&e.call(n)}finally{if(t)throw t.error}}},r.prototype.onPlay=function(){this.autoPauseAndStart&&this.resumeAll()},r.prototype.onPause=function(){this.autoPauseAndStart&&this.pauseAll()},r.prototype.onDestroy=function(){this.components.forEach((function(t){t.onDestroy()})),this.components=[],this.ctx&&(this.gainNode.disconnect(),this.gainNode=null,this.ctx.close(),this.ctx=null)},r.prototype.componentChanged=function(e){return n(this,void 0,void 0,(function(){return i(this,(function(o){return"Sound"!==e.componentName||e.type===t.OBSERVER_TYPE.ADD&&this.add(e),[2]}))}))},r.prototype.setupAudioContext=function(){try{var t=window.AudioContext||window.webkitAudioContext;this.ctx=new t}catch(t){console.error(t),this.onError&&this.onError(t)}this.ctx&&(this.gainNode=void 0===this.ctx.createGain?this.ctx.createGainNode():this.ctx.createGain(),this.gainNode.gain.setValueAtTime(this.muted?0:this.volume,this.ctx.currentTime),this.gainNode.connect(this.ctx.destination),this.unlockAudio())},r.prototype.unlockAudio=function(){var t=this;if(this.ctx&&this.audioLocked){var e=function(){if(t.ctx){var o=function(){document.body.removeEventListener("touchstart",e),document.body.removeEventListener("touchend",e),document.body.removeEventListener("click",e)};t.ctx.resume().then(o,o)}};document.body.addEventListener("touchstart",e),document.body.addEventListener("touchend",e),document.body.addEventListener("click",e)}},r.prototype.add=function(e){return n(this,void 0,void 0,(function(){var o,n,r,s,u,a;return i(this,(function(i){switch(i.label){case 0:o=e.component,this.components.push(o),i.label=1;case 1:return i.trys.push([1,5,,6]),n=o.config,o.state="loading",[4,t.resource.getResource(n.resource)];case 2:return r=i.sent(),this.audioBufferCache[r.name]?[3,4]:(s=this.audioBufferCache,u=r.name,[4,this.decodeAudioData(r.data.audio,r.name)]);case 3:s[u]=i.sent(),i.label=4;case 4:return this.audioBufferCache[r.name]&&(o.systemContext=this.ctx,o.systemDestination=this.gainNode,o.onload(this.audioBufferCache[r.name])),[3,6];case 5:return a=i.sent(),console.error(a),this.onError&&this.onError(a),[3,6];case 6:return[2]}}))}))},r.prototype.decodeAudioData=function(t,e){var o=this;if(this.decodeAudioPromiseMap[e])return this.decodeAudioPromiseMap[e];var n=new Promise((function(n,i){o.ctx||i(new Error("No audio support"));o.ctx.decodeAudioData(t,(function(t){o.decodeAudioPromiseMap[e]&&delete o.decodeAudioPromiseMap[e],t?n(t):i(new Error("Error decoding audio "+e))}),(function(n){o.decodeAudioPromiseMap[e]&&delete o.decodeAudioPromiseMap[e],i(new Error(n+". arrayBuffer byteLength: "+(t?t.byteLength:0)))}))}));return this.decodeAudioPromiseMap[e]=n,n},r.systemName="SoundSystem",r=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var u=t.length-1;u>=0;u--)(i=t[u])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s}([t.decorators.componentObserver({Sound:[]})],r),r}(t.System),s=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.state="unloaded",e.config={resource:"",autoplay:!1,muted:!1,volume:1,loop:!1,seek:0},e.playTime=0,e.startTime=0,e.duration=0,e.actionQueue=[],e}return o(e,t),Object.defineProperty(e.prototype,"muted",{get:function(){return!!this.gainNode&&0===this.gainNode.gain.value},set:function(t){this.gainNode&&this.gainNode.gain.setValueAtTime(t?0:this.config.volume,0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"volume",{get:function(){return this.gainNode?this.gainNode.gain.value:1},set:function(t){"number"!=typeof t||t<0||t>1||(this.config.volume=t,this.gainNode&&this.gainNode.gain.setValueAtTime(t,0))},enumerable:!1,configurable:!0}),e.prototype.init=function(t){t&&(Object.assign(this.config,t),this.config.autoplay&&this.actionQueue.push(this.play.bind(this)))},e.prototype.play=function(){var t=this;if("loaded"!==this.state&&this.actionQueue.push(this.play.bind(this)),this.destroySource(),this.createSource(),this.sourceNode){var e=this.systemContext.currentTime,o=this.config.seek,n=this.config.duration;this.sourceNode.start(0,o,n),this.startTime=e,this.playTime=e-o,this.paused=!1,this.playing=!0,this.resetConfig(),this.endedListener=function(){t.sourceNode&&(t.config.onEnd&&t.config.onEnd(),t.playing&&t.destroySource())},this.sourceNode.addEventListener("ended",this.endedListener)}},e.prototype.pause=function(){"loaded"!==this.state&&this.actionQueue.push(this.pause.bind(this)),!this.paused&&this.playing&&(this.paused=!0,this.playing=!1,this.config.seek=this.getCurrentTime(),this.destroySource())},e.prototype.stop=function(){"loaded"!==this.state&&this.actionQueue.push(this.stop.bind(this)),(this.paused||this.playing)&&(this.playing=!1,this.paused=!1,this.destroySource(),this.resetConfig())},e.prototype.onload=function(t){this.state="loaded",this.buffer=t,this.duration=this.buffer.duration,this.actionQueue.forEach((function(t){return t()})),this.actionQueue.length=0},e.prototype.onDestroy=function(){this.actionQueue.length=0,this.destroySource()},e.prototype.resetConfig=function(){this.config.seek=0},e.prototype.getCurrentTime=function(){return this.config.loop&&this.duration>0?(this.systemContext.currentTime-this.playTime)%this.duration:this.systemContext.currentTime-this.playTime},e.prototype.createSource=function(){this.systemContext&&"loaded"===this.state&&(this.sourceNode=this.systemContext.createBufferSource(),this.sourceNode.buffer=this.buffer,this.sourceNode.loop=this.config.loop,this.gainNode||(this.gainNode=this.systemContext.createGain(),this.gainNode.connect(this.systemDestination),Object.assign(this,this.config)),this.sourceNode.connect(this.gainNode))},e.prototype.destroySource=function(){this.sourceNode&&(this.sourceNode.removeEventListener("ended",this.endedListener),this.sourceNode.stop(),this.sourceNode.disconnect(),this.sourceNode=null,this.startTime=0,this.playTime=0,this.playing=!1)},e.componentName="Sound",e}(t.Component);exports.Sound=s,exports.SoundSystem=r;
15
+ ***************************************************************************** */function o(t,o){function n(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}function n(t,e,o,n){return new(o||(o=Promise))((function(i,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function u(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){t.done?i(t.value):new o((function(e){e(t.value)})).then(s,u)}a((n=n.apply(t,e||[])).next())}))}function i(t,e){var o,n,i,r,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return r={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function u(r){return function(u){return function(r){if(o)throw new TypeError("Generator is already executing.");for(;s;)try{if(o=1,n&&(i=2&r[0]?n.return:r[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,r[1])).done)return i;switch(n=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,n=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){s=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]<i[3])){s.label=r[1];break}if(6===r[0]&&s.label<i[1]){s.label=i[1],i=r;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(r);break}i[2]&&s.ops.pop(),s.trys.pop();continue}r=e.call(t,s)}catch(t){r=[6,t],n=0}finally{o=i=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,u])}}}var r=function(e){function r(t){var o=e.call(this)||this;return o.autoPauseAndStart=!0,o.components=[],o.pausedComponents=[],o.audioBufferCache={},o.decodeAudioPromiseMap={},Object.assign(o,t),o}return o(r,e),Object.defineProperty(r.prototype,"muted",{get:function(){return!!this.gainNode&&0===this.gainNode.gain.value},set:function(t){this.gainNode&&this.gainNode.gain.setValueAtTime(t?0:1,0)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"volume",{get:function(){return this.gainNode?this.gainNode.gain.value:1},set:function(t){!this.gainNode||"number"!=typeof t||t<0||t>1||this.gainNode.gain.setValueAtTime(t,0)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"audioLocked",{get:function(){return!this.ctx||"running"!==this.ctx.state},enumerable:!1,configurable:!0}),r.prototype.resumeAll=function(){var t=this,e=function(){t.pausedComponents.forEach((function(t){t.play()})),t.pausedComponents=[]};this.ctx.resume().then(e,e)},r.prototype.pauseAll=function(){var t=this;this.components.forEach((function(e){e.playing&&(t.pausedComponents.push(e),e.pause())})),this.ctx.suspend().then()},r.prototype.stopAll=function(){this.components.forEach((function(t){t.playing&&t.stop()})),this.pausedComponents=[],this.ctx.suspend().then()},r.prototype.init=function(){this.setupAudioContext()},r.prototype.update=function(){var t,e,o=this.componentObserver.clear();try{for(var n=function(t){var e="function"==typeof Symbol&&t[Symbol.iterator],o=0;return e?e.call(t):{next:function(){return t&&o>=t.length&&(t=void 0),{value:t&&t[o++],done:!t}}}}(o),i=n.next();!i.done;i=n.next()){var r=i.value;this.componentChanged(r)}}catch(e){t={error:e}}finally{try{i&&!i.done&&(e=n.return)&&e.call(n)}finally{if(t)throw t.error}}},r.prototype.onPlay=function(){this.autoPauseAndStart&&this.resumeAll()},r.prototype.onPause=function(){this.autoPauseAndStart&&this.pauseAll()},r.prototype.onDestroy=function(){this.components.forEach((function(t){t.onDestroy()})),this.components=[],this.ctx&&(this.gainNode.disconnect(),this.gainNode=null,this.ctx.close(),this.ctx=null)},r.prototype.componentChanged=function(e){return n(this,void 0,void 0,(function(){return i(this,(function(o){return"Sound"!==e.componentName||e.type===t.OBSERVER_TYPE.ADD&&this.add(e),[2]}))}))},r.prototype.setupAudioContext=function(){try{var t=window.AudioContext||window.webkitAudioContext;this.ctx=new t}catch(t){console.error(t),this.onError&&this.onError(t)}this.ctx&&(this.gainNode=void 0===this.ctx.createGain?this.ctx.createGainNode():this.ctx.createGain(),this.gainNode.gain.setValueAtTime(this.muted?0:this.volume,this.ctx.currentTime),this.gainNode.connect(this.ctx.destination),this.unlockAudio())},r.prototype.unlockAudio=function(){var t=this;if(this.ctx&&this.audioLocked){var e=function(){if(t.ctx){var o=function(){document.body.removeEventListener("touchstart",e),document.body.removeEventListener("touchend",e),document.body.removeEventListener("click",e)};t.ctx.resume().then(o,o)}};document.body.addEventListener("touchstart",e),document.body.addEventListener("touchend",e),document.body.addEventListener("click",e)}},r.prototype.add=function(e){return n(this,void 0,void 0,(function(){var o,n,r,s,u,a;return i(this,(function(i){switch(i.label){case 0:o=e.component,this.components.push(o),i.label=1;case 1:return i.trys.push([1,5,,6]),n=o.config,o.state="loading",[4,t.resource.getResource(n.resource)];case 2:return r=i.sent(),this.audioBufferCache[r.name]?[3,4]:(s=this.audioBufferCache,u=r.name,[4,this.decodeAudioData(r.data.audio,r.name)]);case 3:s[u]=i.sent(),i.label=4;case 4:return this.audioBufferCache[r.name]&&(o.systemContext=this.ctx,o.systemDestination=this.gainNode,o.onload(this.audioBufferCache[r.name])),[3,6];case 5:return a=i.sent(),console.error(a),this.onError&&this.onError(a),[3,6];case 6:return[2]}}))}))},r.prototype.decodeAudioData=function(t,e){var o=this;if(this.decodeAudioPromiseMap[e])return this.decodeAudioPromiseMap[e];var n=new Promise((function(n,i){o.ctx||i(new Error("No audio support"));o.ctx.decodeAudioData(t,(function(t){o.decodeAudioPromiseMap[e]&&delete o.decodeAudioPromiseMap[e],t?n(t):i(new Error("Error decoding audio "+e))}),(function(n){o.decodeAudioPromiseMap[e]&&delete o.decodeAudioPromiseMap[e],i(new Error(n+". arrayBuffer byteLength: "+(t?t.byteLength:0)))}))}));return this.decodeAudioPromiseMap[e]=n,n},r.systemName="SoundSystem",r=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var u=t.length-1;u>=0;u--)(i=t[u])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s}([t.decorators.componentObserver({Sound:[]})],r)}(t.System),s=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.state="unloaded",e.config={resource:"",autoplay:!1,muted:!1,volume:1,loop:!1,seek:0},e.playTime=0,e.startTime=0,e.duration=0,e.actionQueue=[],e}return o(e,t),Object.defineProperty(e.prototype,"muted",{get:function(){return!!this.gainNode&&0===this.gainNode.gain.value},set:function(t){this.gainNode&&this.gainNode.gain.setValueAtTime(t?0:this.config.volume,0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"volume",{get:function(){return this.gainNode?this.gainNode.gain.value:1},set:function(t){"number"!=typeof t||t<0||t>1||(this.config.volume=t,this.gainNode&&this.gainNode.gain.setValueAtTime(t,0))},enumerable:!1,configurable:!0}),e.prototype.init=function(t){t&&(Object.assign(this.config,t),this.config.autoplay&&this.actionQueue.push(this.play.bind(this)))},e.prototype.play=function(){var t=this;if("loaded"!==this.state&&this.actionQueue.push(this.play.bind(this)),this.destroySource(),this.createSource(),this.sourceNode){var e=this.systemContext.currentTime,o=this.config.seek,n=this.config.duration;this.sourceNode.start(0,o,n),this.startTime=e,this.playTime=e-o,this.paused=!1,this.playing=!0,this.resetConfig(),this.endedListener=function(){t.sourceNode&&(t.config.onEnd&&t.config.onEnd(),t.playing&&t.destroySource())},this.sourceNode.addEventListener("ended",this.endedListener)}},e.prototype.pause=function(){"loaded"!==this.state&&this.actionQueue.push(this.pause.bind(this)),!this.paused&&this.playing&&(this.paused=!0,this.playing=!1,this.config.seek=this.getCurrentTime(),this.destroySource())},e.prototype.stop=function(){"loaded"!==this.state&&this.actionQueue.push(this.stop.bind(this)),(this.paused||this.playing)&&(this.playing=!1,this.paused=!1,this.destroySource(),this.resetConfig())},e.prototype.onload=function(t){this.state="loaded",this.buffer=t,this.duration=this.buffer.duration,this.actionQueue.forEach((function(t){return t()})),this.actionQueue.length=0},e.prototype.onDestroy=function(){this.actionQueue.length=0,this.destroySource()},e.prototype.resetConfig=function(){this.config.seek=0},e.prototype.getCurrentTime=function(){return this.config.loop&&this.duration>0?(this.systemContext.currentTime-this.playTime)%this.duration:this.systemContext.currentTime-this.playTime},e.prototype.createSource=function(){this.systemContext&&"loaded"===this.state&&(this.sourceNode=this.systemContext.createBufferSource(),this.sourceNode.buffer=this.buffer,this.sourceNode.loop=this.config.loop,this.gainNode||(this.gainNode=this.systemContext.createGain(),this.gainNode.connect(this.systemDestination),Object.assign(this,this.config)),this.sourceNode.connect(this.gainNode))},e.prototype.destroySource=function(){this.sourceNode&&(this.sourceNode.removeEventListener("ended",this.endedListener),this.sourceNode.stop(),this.sourceNode.disconnect(),this.sourceNode=null,this.startTime=0,this.playTime=0,this.playing=!1)},e.componentName="Sound",e}(t.Component);exports.Sound=s,exports.SoundSystem=r;
16
+ //# sourceMappingURL=plugin-sound.cjs.prod.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin-sound.cjs.prod.js","sources":["../lib/SoundSystem.ts","../lib/Sound.ts"],"sourcesContent":["import { System, decorators, ComponentChanged, OBSERVER_TYPE, resource } from '@eva/eva.js';\nimport SoundComponent from './Sound';\n\ninterface SoundSystemParams {\n autoPauseAndStart?: boolean;\n onError: (error: any) => void;\n}\n\n@decorators.componentObserver({\n Sound: [],\n})\nclass SoundSystem extends System {\n static systemName = 'SoundSystem';\n\n private ctx: AudioContext;\n\n private gainNode: GainNode;\n\n /** 是否和游戏同步暂停和启动 */\n private autoPauseAndStart = true;\n\n private onError: (error: any) => void;\n\n private components: SoundComponent[] = [];\n\n private pausedComponents: SoundComponent[] = [];\n\n private audioBufferCache = {};\n\n private decodeAudioPromiseMap = {};\n\n get muted(): boolean {\n return this.gainNode ? this.gainNode.gain.value === 0 : false;\n }\n\n set muted(v: boolean) {\n if (!this.gainNode) {\n return;\n }\n this.gainNode.gain.setValueAtTime(v ? 0 : 1, 0);\n }\n\n get volume(): number {\n return this.gainNode ? this.gainNode.gain.value : 1;\n }\n\n set volume(v: number) {\n if (!this.gainNode || typeof v !== 'number' || v < 0 || v > 1) {\n return;\n }\n this.gainNode.gain.setValueAtTime(v, 0);\n }\n\n get audioLocked(): boolean {\n if (!this.ctx) {\n return true;\n }\n return this.ctx.state !== 'running';\n }\n\n constructor(obj?: SoundSystemParams) {\n super();\n Object.assign(this, obj);\n }\n\n /**\n * 恢复播放所有被暂停的音频\n */\n resumeAll() {\n const handleResume = () => {\n this.pausedComponents.forEach(component => {\n component.play();\n });\n // 清理之前缓存的暂停列表\n this.pausedComponents = [];\n };\n this.ctx.resume().then(handleResume, handleResume);\n }\n\n /**\n * 暂停所有正在播放的音频\n */\n pauseAll() {\n this.components.forEach(component => {\n if (component.playing) {\n this.pausedComponents.push(component);\n component.pause();\n }\n });\n this.ctx.suspend().then();\n }\n\n /**\n * 停止所有正在播放的音频\n */\n stopAll() {\n this.components.forEach(component => {\n if (component.playing) {\n component.stop();\n }\n });\n // 清理之前缓存的暂停列表\n this.pausedComponents = [];\n this.ctx.suspend().then();\n }\n\n /**\n * System 初始化用,可以配置参数,游戏未开始\n *\n * System init, set params, game is not begain\n */\n init() {\n this.setupAudioContext();\n }\n\n update() {\n const changes = this.componentObserver.clear();\n for (const changed of changes) {\n this.componentChanged(changed);\n }\n }\n\n /**\n * 游戏开始和游戏暂停后开始播放的时候调用。\n *\n * Called while the game to play when game pause.\n */\n onPlay() {\n if (!this.autoPauseAndStart) {\n return;\n }\n this.resumeAll();\n }\n\n /**\n * 游戏暂停的时候调用。\n *\n * Called while the game paused.\n */\n onPause() {\n if (!this.autoPauseAndStart) {\n return;\n }\n this.pauseAll();\n }\n\n /**\n * System 被销毁的时候调用。\n * Called while the system be destroyed.\n */\n onDestroy() {\n this.components.forEach(component => {\n component.onDestroy();\n });\n this.components = [];\n if (this.ctx) {\n this.gainNode.disconnect();\n this.gainNode = null;\n this.ctx.close();\n this.ctx = null;\n }\n }\n\n async componentChanged(changed: ComponentChanged) {\n if (changed.componentName !== 'Sound') {\n return;\n }\n if (changed.type === OBSERVER_TYPE.ADD) {\n this.add(changed);\n }\n }\n\n private setupAudioContext() {\n try {\n const AudioContext = window.AudioContext || (window as any).webkitAudioContext;\n this.ctx = new AudioContext();\n } catch (error) {\n console.error(error);\n if (this.onError) {\n this.onError(error);\n }\n }\n\n if (!this.ctx) {\n return;\n }\n this.gainNode =\n typeof this.ctx.createGain === 'undefined' ? (this.ctx as any).createGainNode() : this.ctx.createGain();\n this.gainNode.gain.setValueAtTime(this.muted ? 0 : this.volume, this.ctx.currentTime);\n this.gainNode.connect(this.ctx.destination);\n this.unlockAudio();\n }\n\n private unlockAudio() {\n if (!this.ctx || !this.audioLocked) {\n return;\n }\n\n const unlock = () => {\n if (this.ctx) {\n const removeListenerFn = () => {\n document.body.removeEventListener('touchstart', unlock);\n document.body.removeEventListener('touchend', unlock);\n document.body.removeEventListener('click', unlock);\n };\n this.ctx.resume().then(removeListenerFn, removeListenerFn);\n }\n };\n document.body.addEventListener('touchstart', unlock);\n document.body.addEventListener('touchend', unlock);\n document.body.addEventListener('click', unlock);\n }\n\n private async add(changed: ComponentChanged) {\n const component = changed.component as SoundComponent;\n this.components.push(component);\n try {\n const { config } = component;\n component.state = 'loading';\n\n const audio = await resource.getResource(config.resource);\n if (!this.audioBufferCache[audio.name]) {\n this.audioBufferCache[audio.name] = await this.decodeAudioData(audio.data.audio, audio.name);\n }\n if (this.audioBufferCache[audio.name]) {\n component.systemContext = this.ctx;\n component.systemDestination = this.gainNode;\n component.onload(this.audioBufferCache[audio.name]);\n }\n } catch (error) {\n console.error(error);\n if (this.onError) {\n this.onError(error);\n }\n }\n }\n\n private decodeAudioData(arraybuffer: ArrayBuffer, name: string) {\n if (this.decodeAudioPromiseMap[name]) {\n return this.decodeAudioPromiseMap[name];\n }\n const promise = new Promise<AudioBuffer>((resolve, reject) => {\n if (!this.ctx) {\n reject(new Error('No audio support'));\n }\n const error = (err: DOMException) => {\n if (this.decodeAudioPromiseMap[name]) {\n delete this.decodeAudioPromiseMap[name];\n }\n reject(new Error(`${err}. arrayBuffer byteLength: ${arraybuffer ? arraybuffer.byteLength : 0}`));\n };\n const success = (decodedData: AudioBuffer) => {\n if (this.decodeAudioPromiseMap[name]) {\n delete this.decodeAudioPromiseMap[name];\n }\n if (decodedData) {\n resolve(decodedData);\n } else {\n reject(new Error(`Error decoding audio ${name}`));\n }\n };\n\n this.ctx.decodeAudioData(arraybuffer, success, error);\n });\n this.decodeAudioPromiseMap[name] = promise;\n return promise;\n }\n}\n\nexport default SoundSystem;\n","import { Component } from '@eva/eva.js';\n\nexport interface SoundParams {\n resource: string;\n autoplay?: boolean;\n muted?: boolean;\n volume?: number;\n loop?: boolean;\n seek?: number;\n duration?: number;\n onEnd?: () => void;\n}\n\nclass Sound extends Component<SoundParams> {\n static componentName = 'Sound';\n\n systemContext: AudioContext;\n\n systemDestination: GainNode;\n\n playing: boolean;\n\n state: 'unloaded' | 'loading' | 'loaded' = 'unloaded';\n\n config: SoundParams = {\n resource: '',\n autoplay: false,\n muted: false,\n volume: 1,\n loop: false,\n seek: 0,\n };\n\n private buffer: AudioBuffer;\n\n private sourceNode: AudioBufferSourceNode;\n\n private gainNode: GainNode;\n\n private paused: boolean;\n\n private playTime: number = 0;\n\n // @ts-ignore\n private startTime: number = 0;\n\n private duration: number = 0;\n\n private actionQueue: (() => void)[] = [];\n\n private endedListener: () => void;\n\n get muted(): boolean {\n return this.gainNode ? this.gainNode.gain.value === 0 : false;\n }\n\n set muted(v: boolean) {\n if (!this.gainNode) {\n return;\n }\n this.gainNode.gain.setValueAtTime(v ? 0 : this.config.volume, 0);\n }\n\n get volume(): number {\n return this.gainNode ? this.gainNode.gain.value : 1;\n }\n\n set volume(v: number) {\n if (typeof v !== 'number' || v < 0 || v > 1) {\n return;\n }\n this.config.volume = v;\n if (!this.gainNode) {\n return;\n }\n this.gainNode.gain.setValueAtTime(v, 0);\n }\n\n init(obj?: SoundParams) {\n if (!obj) {\n return;\n }\n\n Object.assign(this.config, obj);\n if (this.config.autoplay) {\n this.actionQueue.push(this.play.bind(this));\n }\n }\n\n play() {\n if (this.state !== 'loaded') {\n this.actionQueue.push(this.play.bind(this));\n }\n this.destroySource();\n this.createSource();\n\n if (!this.sourceNode) {\n return;\n }\n const when = this.systemContext.currentTime;\n const offset = this.config.seek;\n const duration = this.config.duration;\n\n this.sourceNode.start(0, offset, duration);\n\n this.startTime = when;\n this.playTime = when - offset;\n this.paused = false;\n this.playing = true;\n this.resetConfig();\n this.endedListener = () => {\n if (!this.sourceNode) {\n return;\n }\n if (this.config.onEnd) {\n this.config.onEnd();\n }\n // 非交互事件播放完成需要销毁资源\n if (this.playing) {\n this.destroySource();\n }\n };\n this.sourceNode.addEventListener('ended', this.endedListener);\n }\n\n pause() {\n if (this.state !== 'loaded') {\n this.actionQueue.push(this.pause.bind(this));\n }\n if (this.paused || !this.playing) {\n return;\n }\n this.paused = true;\n this.playing = false;\n this.config.seek = this.getCurrentTime();\n this.destroySource();\n }\n\n stop() {\n if (this.state !== 'loaded') {\n this.actionQueue.push(this.stop.bind(this));\n }\n if (!this.paused && !this.playing) {\n return;\n }\n this.playing = false;\n this.paused = false;\n this.destroySource();\n this.resetConfig();\n }\n\n onload(buffer: AudioBuffer) {\n this.state = 'loaded';\n this.buffer = buffer;\n this.duration = this.buffer.duration;\n this.actionQueue.forEach(action => action());\n this.actionQueue.length = 0;\n }\n\n onDestroy() {\n this.actionQueue.length = 0;\n this.destroySource();\n }\n\n private resetConfig() {\n this.config.seek = 0;\n }\n\n private getCurrentTime() {\n if (this.config.loop && this.duration > 0) {\n return (this.systemContext.currentTime - this.playTime) % this.duration;\n }\n\n return this.systemContext.currentTime - this.playTime;\n }\n\n private createSource() {\n if (!this.systemContext || this.state !== 'loaded') {\n return;\n }\n this.sourceNode = this.systemContext.createBufferSource();\n this.sourceNode.buffer = this.buffer;\n this.sourceNode.loop = this.config.loop;\n\n if (!this.gainNode) {\n this.gainNode = this.systemContext.createGain();\n this.gainNode.connect(this.systemDestination);\n Object.assign(this, this.config);\n }\n this.sourceNode.connect(this.gainNode);\n }\n\n private destroySource() {\n if (!this.sourceNode) return;\n this.sourceNode.removeEventListener('ended', this.endedListener);\n this.sourceNode.stop();\n this.sourceNode.disconnect();\n this.sourceNode = null;\n\n this.startTime = 0;\n this.playTime = 0;\n this.playing = false;\n }\n}\n\nexport default Sound;\n"],"names":["obj","_super","_this","Object","assign","__extends","SoundSystem","this","gainNode","gain","value","v","setValueAtTime","ctx","state","handleResume","pausedComponents","forEach","component","play","resume","then","components","playing","push","pause","suspend","stop","setupAudioContext","changes","componentObserver","clear","changes_1","__values","changed","componentChanged","autoPauseAndStart","resumeAll","pauseAll","onDestroy","disconnect","close","componentName","type","OBSERVER_TYPE","ADD","add","AudioContext_1","window","AudioContext","webkitAudioContext","error","console","onError","createGain","createGainNode","muted","volume","currentTime","connect","destination","unlockAudio","audioLocked","unlock","removeListenerFn","document","body","removeEventListener","addEventListener","config","resource","getResource","audio","_c","audioBufferCache","name","_a","_b","decodeAudioData","data","systemContext","systemDestination","onload","error_1","arraybuffer","decodeAudioPromiseMap","promise","Promise","resolve","reject","Error","decodedData","err","byteLength","decorators","Sound","System","autoplay","loop","seek","actionQueue","bind","destroySource","createSource","sourceNode","when","offset","duration","start","startTime","playTime","paused","resetConfig","endedListener","onEnd","getCurrentTime","buffer","action","length","createBufferSource","Component"],"mappings":";;;;;;;;;;;;;;2/CAWA,kBAiDE,WAAYA,GAAZ,MACEC,0BA1CMC,qBAAoB,EAIpBA,aAA+B,GAE/BA,mBAAqC,GAErCA,mBAAmB,GAEnBA,wBAAwB,GAiC9BC,OAAOC,OAAOF,EAAMF,KA6MxB,OAhQ0BK,OAoBx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1G,KAAKiG,WAAW7E,OAChBpB,KAAKiG,WAAWhE,aAChBjC,KAAKiG,WAAa,KAElBjG,KAAKsG,UAAY,EACjBtG,KAAKuG,SAAW,EAChBvG,KAAKgB,SAAU,IA3LVwE,gBAAgB,WADLyB"}
@@ -0,0 +1,84 @@
1
+ import { Component } from '@eva/eva.js';
2
+ import { ComponentChanged } from '@eva/eva.js';
3
+ import { System } from '@eva/eva.js';
4
+
5
+ export declare class Sound extends Component<SoundParams> {
6
+ static componentName: string;
7
+ systemContext: AudioContext;
8
+ systemDestination: GainNode;
9
+ playing: boolean;
10
+ state: 'unloaded' | 'loading' | 'loaded';
11
+ config: SoundParams;
12
+ private buffer;
13
+ private sourceNode;
14
+ private gainNode;
15
+ private paused;
16
+ private playTime;
17
+ private startTime;
18
+ private duration;
19
+ private actionQueue;
20
+ private endedListener;
21
+ get muted(): boolean;
22
+ set muted(v: boolean);
23
+ get volume(): number;
24
+ set volume(v: number);
25
+ init(obj?: SoundParams): void;
26
+ play(): void;
27
+ pause(): void;
28
+ stop(): void;
29
+ onload(buffer: AudioBuffer): void;
30
+ onDestroy(): void;
31
+ private resetConfig;
32
+ private getCurrentTime;
33
+ private createSource;
34
+ private destroySource;
35
+ }
36
+
37
+ declare interface SoundParams {
38
+ resource: string;
39
+ autoplay?: boolean;
40
+ muted?: boolean;
41
+ volume?: number;
42
+ loop?: boolean;
43
+ seek?: number;
44
+ duration?: number;
45
+ onEnd?: () => void;
46
+ }
47
+
48
+ export declare class SoundSystem extends System {
49
+ static systemName: string;
50
+ private ctx;
51
+ private gainNode;
52
+ private autoPauseAndStart;
53
+ private onError;
54
+ private components;
55
+ private pausedComponents;
56
+ private audioBufferCache;
57
+ private decodeAudioPromiseMap;
58
+ get muted(): boolean;
59
+ set muted(v: boolean);
60
+ get volume(): number;
61
+ set volume(v: number);
62
+ get audioLocked(): boolean;
63
+ constructor(obj?: SoundSystemParams);
64
+ resumeAll(): void;
65
+ pauseAll(): void;
66
+ stopAll(): void;
67
+ init(): void;
68
+ update(): void;
69
+ onPlay(): void;
70
+ onPause(): void;
71
+ onDestroy(): void;
72
+ componentChanged(changed: ComponentChanged): Promise<void>;
73
+ private setupAudioContext;
74
+ private unlockAudio;
75
+ private add;
76
+ private decodeAudioData;
77
+ }
78
+
79
+ declare interface SoundSystemParams {
80
+ autoPauseAndStart?: boolean;
81
+ onError: (error: any) => void;
82
+ }
83
+
84
+ export { }
@@ -181,7 +181,7 @@ var SoundSystem = (function (_super) {
181
181
  finally { if (e_1) throw e_1.error; }
182
182
  }
183
183
  };
184
- SoundSystem.prototype.onPlay = function () {
184
+ SoundSystem.prototype.onResume = function () {
185
185
  if (!this.autoPauseAndStart) {
186
186
  return;
187
187
  }
@@ -208,9 +208,8 @@ var SoundSystem = (function (_super) {
208
208
  SoundSystem.prototype.componentChanged = function (changed) {
209
209
  return __awaiter(this, void 0, void 0, function () {
210
210
  return __generator(this, function (_a) {
211
- if (changed.componentName !== 'Sound') {
211
+ if (changed.componentName !== 'Sound')
212
212
  return [2];
213
- }
214
213
  if (changed.type === OBSERVER_TYPE.ADD) {
215
214
  this.add(changed);
216
215
  }
@@ -258,28 +257,29 @@ var SoundSystem = (function (_super) {
258
257
  document.body.addEventListener('click', unlock);
259
258
  };
260
259
  SoundSystem.prototype.add = function (changed) {
260
+ var _a;
261
261
  return __awaiter(this, void 0, void 0, function () {
262
- var component, config, audio, _a, _b, error_1;
263
- return __generator(this, function (_c) {
264
- switch (_c.label) {
262
+ var component, config, audio, _b, _c, error_1;
263
+ return __generator(this, function (_d) {
264
+ switch (_d.label) {
265
265
  case 0:
266
266
  component = changed.component;
267
267
  this.components.push(component);
268
- _c.label = 1;
268
+ _d.label = 1;
269
269
  case 1:
270
- _c.trys.push([1, 5, , 6]);
270
+ _d.trys.push([1, 5, , 6]);
271
271
  config = component.config;
272
272
  component.state = 'loading';
273
273
  return [4, resource.getResource(config.resource)];
274
274
  case 2:
275
- audio = _c.sent();
276
- if (!!this.audioBufferCache[audio.name]) return [3, 4];
277
- _a = this.audioBufferCache;
278
- _b = audio.name;
275
+ audio = _d.sent();
276
+ if (!(!this.audioBufferCache[audio.name] && ((_a = audio === null || audio === void 0 ? void 0 : audio.data) === null || _a === void 0 ? void 0 : _a.audio))) return [3, 4];
277
+ _b = this.audioBufferCache;
278
+ _c = audio.name;
279
279
  return [4, this.decodeAudioData(audio.data.audio, audio.name)];
280
280
  case 3:
281
- _a[_b] = _c.sent();
282
- _c.label = 4;
281
+ _b[_c] = _d.sent();
282
+ _d.label = 4;
283
283
  case 4:
284
284
  if (this.audioBufferCache[audio.name]) {
285
285
  component.systemContext = this.ctx;
@@ -288,8 +288,7 @@ var SoundSystem = (function (_super) {
288
288
  }
289
289
  return [3, 6];
290
290
  case 5:
291
- error_1 = _c.sent();
292
- console.error(error_1);
291
+ error_1 = _d.sent();
293
292
  if (this.onError) {
294
293
  this.onError(error_1);
295
294
  }
@@ -308,12 +307,6 @@ var SoundSystem = (function (_super) {
308
307
  if (!_this.ctx) {
309
308
  reject(new Error('No audio support'));
310
309
  }
311
- var error = function (err) {
312
- if (_this.decodeAudioPromiseMap[name]) {
313
- delete _this.decodeAudioPromiseMap[name];
314
- }
315
- reject(new Error(err + ". arrayBuffer byteLength: " + (arraybuffer ? arraybuffer.byteLength : 0)));
316
- };
317
310
  var success = function (decodedData) {
318
311
  if (_this.decodeAudioPromiseMap[name]) {
319
312
  delete _this.decodeAudioPromiseMap[name];
@@ -325,7 +318,18 @@ var SoundSystem = (function (_super) {
325
318
  reject(new Error("Error decoding audio " + name));
326
319
  }
327
320
  };
328
- _this.ctx.decodeAudioData(arraybuffer, success, error);
321
+ var error = function (err) {
322
+ if (_this.decodeAudioPromiseMap[name]) {
323
+ delete _this.decodeAudioPromiseMap[name];
324
+ }
325
+ reject(new Error(err + ". arrayBuffer byteLength: " + (arraybuffer ? arraybuffer.byteLength : 0)));
326
+ };
327
+ var promise = _this.ctx.decodeAudioData(arraybuffer, success, error);
328
+ if (promise instanceof Promise) {
329
+ promise.catch(function (err) {
330
+ reject(new Error("catch " + err + ", arrayBuffer byteLength: " + (arraybuffer ? arraybuffer.byteLength : 0)));
331
+ });
332
+ }
329
333
  });
330
334
  this.decodeAudioPromiseMap[name] = promise;
331
335
  return promise;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eva/plugin-sound",
3
- "version": "1.1.1-fix.1",
3
+ "version": "1.1.1-fix.2",
4
4
  "description": "@eva/plugin-sound",
5
5
  "main": "index.js",
6
6
  "module": "dist/plugin-sound.esm.js",
@@ -18,7 +18,7 @@
18
18
  "license": "MIT",
19
19
  "homepage": "https://eva.js.org",
20
20
  "dependencies": {
21
- "@eva/eva.js": "1.1.1-fix.1",
21
+ "@eva/eva.js": "1.1.1-fix.2",
22
22
  "eventemitter3": "^3.1.2"
23
23
  }
24
24
  }