forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstance.js
More file actions
984 lines (802 loc) · 31.7 KB
/
instance.js
File metadata and controls
984 lines (802 loc) · 31.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
import { EventHandler } from '../core/event-handler.js';
import { math } from '../math/math.js';
import { hasAudioContext } from '../audio/capabilities.js';
const STATE_PLAYING = 0;
const STATE_PAUSED = 1;
const STATE_STOPPED = 2;
// Return time % duration but always return a number
// instead of NaN when duration is 0
function capTime(time, duration) {
return (time % duration) || 0;
}
/**
* @class
* @name SoundInstance
* @augments EventHandler
* @classdesc A SoundInstance plays a {@link Sound}.
* @param {SoundManager} manager - The sound manager.
* @param {Sound} sound - The sound to play.
* @param {object} options - Options for the instance.
* @param {number} [options.volume=1] - The playback volume, between 0 and 1.
* @param {number} [options.pitch=1] - The relative pitch, default of 1, plays at normal pitch.
* @param {boolean} [options.loop=false] - Whether the sound should loop when it reaches the end or not.
* @param {number} [options.startTime=0] - The time from which the playback will start in seconds. Default is 0 to start at the beginning.
* @param {number} [options.duration=null] - The total time after the startTime in seconds when playback will stop or restart if loop is true.
* @param {Function} [options.onPlay=null] - Function called when the instance starts playing.
* @param {Function} [options.onPause=null] - Function called when the instance is paused.
* @param {Function} [options.onResume=null] - Function called when the instance is resumed.
* @param {Function} [options.onStop=null] - Function called when the instance is stopped.
* @param {Function} [options.onEnd=null] - Function called when the instance ends.
* @property {number} volume The volume modifier to play the sound with. In range 0-1.
* @property {number} pitch The pitch modifier to play the sound with. Must be larger than 0.01.
* @property {number} startTime The start time from which the sound will start playing.
* @property {number} currentTime Gets or sets the current time of the sound that is playing. If the value provided is bigger than the duration of the instance it will wrap from the beginning.
* @property {number} duration The duration of the sound that the instance will play starting from startTime.
* @property {boolean} loop If true the instance will restart when it finishes playing.
* @property {boolean} isPlaying Returns true if the instance is currently playing.
* @property {boolean} isPaused Returns true if the instance is currently paused.
* @property {boolean} isStopped Returns true if the instance is currently stopped.
* @property {boolean} isSuspended Returns true if the instance is currently suspended because the window is not focused.
* @property {AudioBufferSourceNode} source Gets the source that plays the sound resource. If the Web Audio API is not supported the type of source is <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio" target="_blank">Audio</a>. Source is only available after calling play.
* @property {Sound} sound The sound resource that the instance will play.
*/
class SoundInstance extends EventHandler {
constructor(manager, sound, options) {
super();
this._manager = manager;
this._volume = options.volume !== undefined ? math.clamp(Number(options.volume) || 0, 0, 1) : 1;
this._pitch = options.pitch !== undefined ? Math.max(0.01, Number(options.pitch) || 0) : 1;
this._loop = !!(options.loop !== undefined ? options.loop : false);
this._sound = sound;
// start at 'stopped'
this._state = STATE_STOPPED;
// true if the manager was suspended
this._suspended = false;
// true if we want to suspend the event handled to the 'onended' event
this._suspendEndEvent = false;
// true if we want to suspend firing instance events
this._suspendInstanceEvents = false;
// if true then the instance will start playing its source
// when its created
this._playWhenLoaded = true;
this._startTime = Math.max(0, Number(options.startTime) || 0);
this._duration = Math.max(0, Number(options.duration) || 0);
this._startOffset = null;
// source is initialized when play() is called
this.source = null;
// external event handlers
this._onPlayCallback = options.onPlay;
this._onPauseCallback = options.onPause;
this._onResumeCallback = options.onResume;
this._onStopCallback = options.onStop;
this._onEndCallback = options.onEnd;
if (hasAudioContext()) {
this._startedAt = 0;
// manually keep track of the playback position
// because the Web Audio API does not provide a way to do this
// accurately if the playbackRate is not 1
this._currentTime = 0;
this._currentOffset = 0;
// The input node is the one that is connected to the source.
this._inputNode = null;
// the connected node is the one that is connected to the destination (speakers). Any
// external nodes will be connected to this node.
this._connectorNode = null;
// The first external node set by a user
this._firstNode = null;
// The last external node set by a user
this._lastNode = null;
this._initializeNodes();
// bind internal event handlers to 'this'
this._endedHandler = this._onEnded.bind(this);
} else {
this._isReady = false;
this._loadedMetadataHandler = this._onLoadedMetadata.bind(this);
this._timeUpdateHandler = this._onTimeUpdate.bind(this);
this._endedHandler = this._onEnded.bind(this);
this._createSource();
}
}
_onPlay() {
this.fire('play');
if (this._onPlayCallback)
this._onPlayCallback(this);
}
_onPause() {
this.fire('pause');
if (this._onPauseCallback)
this._onPauseCallback(this);
}
_onResume() {
this.fire('resume');
if (this._onResumeCallback)
this._onResumeCallback(this);
}
_onStop() {
this.fire('stop');
if (this._onStopCallback)
this._onStopCallback(this);
}
_onEnded() {
// the callback is not fired synchronously
// so only reset _suspendEndEvent to false when the
// callback is fired
if (this._suspendEndEvent) {
this._suspendEndEvent = false;
return;
}
this.fire('end');
if (this._onEndCallback)
this._onEndCallback(this);
this.stop();
}
/**
* @private
* @function
* @name SoundInstance#_onManagerVolumeChange
* @description Handle the manager's 'volumechange' event.
*/
_onManagerVolumeChange() {
this.volume = this._volume;
}
/**
* @private
* @function
* @name SoundInstance#_onManagerSuspend
* @description Handle the manager's 'suspend' event.
*/
_onManagerSuspend() {
if (this._state === STATE_PLAYING && !this._suspended) {
this._suspended = true;
this.pause();
}
}
/**
* @private
* @function
* @name SoundInstance#_onManagerResume
* @description Handle the manager's 'resume' event.
*/
_onManagerResume() {
if (this._suspended) {
this._suspended = false;
this.resume();
}
}
get loop() {
return this._loop;
}
set loop(value) {
this._loop = !!value;
if (this.source) {
this.source.loop = this._loop;
}
}
get startTime() {
return this._startTime;
}
set startTime(value) {
this._startTime = Math.max(0, Number(value) || 0);
// restart
const isPlaying = this._state === STATE_PLAYING;
this.stop();
if (isPlaying) {
this.play();
}
}
get duration() {
if (!this._sound) {
return 0;
}
if (this._duration) {
return capTime(this._duration, this._sound.duration);
}
return this._sound.duration;
}
set duration(value) {
this._duration = Math.max(0, Number(value) || 0);
// restart
const isPlaying = this._state === STATE_PLAYING;
this.stop();
if (isPlaying) {
this.play();
}
}
get isPlaying() {
return this._state === STATE_PLAYING;
}
get isPaused() {
return this._state === STATE_PAUSED;
}
get isStopped() {
return this._state === STATE_STOPPED;
}
get isSuspended() {
return this._suspended;
}
}
if (hasAudioContext()) {
Object.assign(SoundInstance.prototype, {
/**
* @function
* @private
* @name SoundInstance#_initializeNodes
* @description Creates internal audio nodes and connects them.
*/
_initializeNodes: function () {
// create gain node for volume control
this.gain = this._manager.context.createGain();
this._inputNode = this.gain;
// the gain node is also the connector node for 2D sound instances
this._connectorNode = this.gain;
this._connectorNode.connect(this._manager.context.destination);
},
/**
* @function
* @name SoundInstance#play
* @description Begins playback of sound. If the sound is not loaded this will return false.
* If the sound is already playing this will restart the sound.
* @returns {boolean} True if the sound was started.
*/
play: function () {
if (this._state !== STATE_STOPPED) {
this.stop();
}
if (!this.source) {
this._createSource();
}
// calculate start offset
let offset = capTime(this._startOffset, this.duration);
offset = capTime(this._startTime + offset, this._sound.duration);
// reset start offset now that we started the sound
this._startOffset = null;
// start source with specified offset and duration
if (this._duration) {
this.source.start(0, offset, this._duration);
} else {
this.source.start(0, offset);
}
// reset times
this._startedAt = this._manager.context.currentTime;
this._currentTime = 0;
this._currentOffset = offset;
// set state to playing
this._state = STATE_PLAYING;
// no need for this anymore
this._playWhenLoaded = false;
// Initialize volume and loop - note moved to be after start() because of Chrome bug
this.volume = this._volume;
this.loop = this._loop;
this.pitch = this._pitch;
// handle suspend events / volumechange events
this._manager.on('volumechange', this._onManagerVolumeChange, this);
this._manager.on('suspend', this._onManagerSuspend, this);
this._manager.on('resume', this._onManagerResume, this);
this._manager.on('destroy', this._onManagerDestroy, this);
// suspend immediately if manager is suspended
if (this._manager.suspended) {
this._onManagerSuspend();
}
if (!this._suspendInstanceEvents)
this._onPlay();
return true;
},
/**
* @function
* @name SoundInstance#pause
* @description Pauses playback of sound. Call resume() to resume playback from the same position.
* @returns {boolean} Returns true if the sound was paused.
*/
pause: function () {
// no need for this anymore
this._playWhenLoaded = false;
if (this._state !== STATE_PLAYING || !this.source)
return false;
// store current time
this._updateCurrentTime();
// set state to paused
this._state = STATE_PAUSED;
// Stop the source and re-create it because we cannot reuse the same source.
// Suspend the end event as we are manually stopping the source
this._suspendEndEvent = true;
this.source.stop(0);
this.source = null;
// reset user-set start offset
this._startOffset = null;
if (!this._suspendInstanceEvents)
this._onPause();
return true;
},
/**
* @function
* @name SoundInstance#resume
* @description Resumes playback of the sound. Playback resumes at the point that the audio was paused.
* @returns {boolean} Returns true if the sound was resumed.
*/
resume: function () {
if (this._state !== STATE_PAUSED) {
return false;
}
if (!this.source) {
this._createSource();
}
// start at point where sound was paused
let offset = this.currentTime;
// if the user set the 'currentTime' property while the sound
// was paused then use that as the offset instead
if (this._startOffset !== null) {
offset = capTime(this._startOffset, this.duration);
offset = capTime(this._startTime + offset, this._sound.duration);
// reset offset
this._startOffset = null;
}
// start source
if (this._duration) {
this.source.start(0, offset, this._duration);
} else {
this.source.start(0, offset);
}
// set state back to playing
this._state = STATE_PLAYING;
this._startedAt = this._manager.context.currentTime;
this._currentOffset = offset;
// Initialize parameters
this.volume = this._volume;
this.loop = this._loop;
this.pitch = this._pitch;
this._playWhenLoaded = false;
if (!this._suspendInstanceEvents)
this._onResume();
return true;
},
/**
* @function
* @name SoundInstance#stop
* @description Stops playback of sound. Calling play() again will restart playback from the beginning of the sound.
* @returns {boolean} Returns true if the sound was stopped.
*/
stop: function () {
this._playWhenLoaded = false;
if (this._state === STATE_STOPPED || !this.source)
return false;
// unsubscribe from manager events
this._manager.off('volumechange', this._onManagerVolumeChange, this);
this._manager.off('suspend', this._onManagerSuspend, this);
this._manager.off('resume', this._onManagerResume, this);
this._manager.off('destroy', this._onManagerDestroy, this);
// reset stored times
this._startedAt = 0;
this._currentTime = 0;
this._currentOffset = 0;
this._startOffset = null;
this._suspendEndEvent = true;
if (this._state === STATE_PLAYING) {
this.source.stop(0);
}
this.source = null;
// set the state to stopped
this._state = STATE_STOPPED;
if (!this._suspendInstanceEvents)
this._onStop();
return true;
},
/**
* @function
* @name SoundInstance#setExternalNodes
* @description Connects external Web Audio API nodes. You need to pass
* the first node of the node graph that you created externally and the last node of that graph. The first
* node will be connected to the audio source and the last node will be connected to the destination of the
* AudioContext (e.g. speakers). Requires Web Audio API support.
* @param {AudioNode} firstNode - The first node that will be connected to the audio source of sound instances.
* @param {AudioNode} [lastNode] - The last node that will be connected to the destination of the AudioContext.
* If unspecified then the firstNode will be connected to the destination instead.
* @example
* var context = app.systems.sound.context;
* var analyzer = context.createAnalyzer();
* var distortion = context.createWaveShaper();
* var filter = context.createBiquadFilter();
* analyzer.connect(distortion);
* distortion.connect(filter);
* instance.setExternalNodes(analyzer, filter);
*/
setExternalNodes: function (firstNode, lastNode) {
if (!firstNode) {
console.error('The firstNode must be a valid Audio Node');
return;
}
if (!lastNode) {
lastNode = firstNode;
}
// connections are:
// source -> inputNode -> connectorNode -> [firstNode -> ... -> lastNode] -> speakers
const speakers = this._manager.context.destination;
if (this._firstNode !== firstNode) {
if (this._firstNode) {
// if firstNode already exists means the connector node
// is connected to it so disconnect it
this._connectorNode.disconnect(this._firstNode);
} else {
// if firstNode does not exist means that its connected
// to the speakers so disconnect it
this._connectorNode.disconnect(speakers);
}
// set first node and connect with connector node
this._firstNode = firstNode;
this._connectorNode.connect(firstNode);
}
if (this._lastNode !== lastNode) {
if (this._lastNode) {
// if last node exists means it's connected to the speakers so disconnect it
this._lastNode.disconnect(speakers);
}
// set last node and connect with speakers
this._lastNode = lastNode;
this._lastNode.connect(speakers);
}
},
/**
* @function
* @name SoundInstance#clearExternalNodes
* @description Clears any external nodes set by {@link SoundInstance#setExternalNodes}.
*/
clearExternalNodes: function () {
const speakers = this._manager.context.destination;
// break existing connections
if (this._firstNode) {
this._connectorNode.disconnect(this._firstNode);
this._firstNode = null;
}
if (this._lastNode) {
this._lastNode.disconnect(speakers);
this._lastNode = null;
}
// reset connect to speakers
this._connectorNode.connect(speakers);
},
/**
* @function
* @name SoundInstance#getExternalNodes
* @description Gets any external nodes set by {@link SoundInstance#setExternalNodes}.
* @returns {AudioNode[]} Returns an array that contains the two nodes set by {@link SoundInstance#setExternalNodes}.
*/
getExternalNodes: function () {
return [this._firstNode, this._lastNode];
},
/**
* @private
* @function
* @description Creates the source for the instance.
*/
_createSource: function () {
if (!this._sound) {
return null;
}
const context = this._manager.context;
if (this._sound.buffer) {
this.source = context.createBufferSource();
this.source.buffer = this._sound.buffer;
// Connect up the nodes
this.source.connect(this._inputNode);
// set events
this.source.onended = this._endedHandler;
// set loopStart and loopEnd so that the source starts and ends at the correct user-set times
this.source.loopStart = capTime(this._startTime, this.source.buffer.duration);
if (this._duration) {
this.source.loopEnd = Math.max(this.source.loopStart, capTime(this._startTime + this._duration, this.source.buffer.duration));
}
}
return this.source;
},
/**
* @private
* @function
* @name SoundInstance#_updateCurrentTime
* @description Sets the current time taking into account the time the instance started playing, the current pitch and the current time offset.
*/
_updateCurrentTime: function () {
this._currentTime = capTime((this._manager.context.currentTime - this._startedAt) * this._pitch + this._currentOffset, this.duration);
},
/**
* @private
* @function
* @name SoundInstance#_onManagerDestroy
* @description Handle the manager's 'destroy' event.
*/
_onManagerDestroy: function () {
if (this.source && this._state === STATE_PLAYING) {
this.source.stop(0);
this.source = null;
}
}
});
Object.defineProperty(SoundInstance.prototype, 'volume', {
get: function () {
return this._volume;
},
set: function (volume) {
volume = math.clamp(volume, 0, 1);
this._volume = volume;
if (this.gain) {
this.gain.gain.value = volume * this._manager.volume;
}
}
});
Object.defineProperty(SoundInstance.prototype, 'pitch', {
get: function () {
return this._pitch;
},
set: function (pitch) {
// set offset to current time so that
// we calculate the rest of the time with the new pitch
// from now on
this._currentOffset = this.currentTime;
this._startedAt = this._manager.context.currentTime;
this._pitch = Math.max(Number(pitch) || 0, 0.01);
if (this.source) {
this.source.playbackRate.value = this._pitch;
}
}
});
Object.defineProperty(SoundInstance.prototype, 'sound', {
get: function () {
return this._sound;
},
set: function (value) {
this._sound = value;
if (this._state !== STATE_STOPPED) {
this.stop();
} else {
this._createSource();
}
}
});
Object.defineProperty(SoundInstance.prototype, 'currentTime', {
get: function () {
// if the user has set the currentTime and we have not used it yet
// then just return that
if (this._startOffset !== null) {
return this._startOffset;
}
// if the sound is paused return the currentTime calculated when
// pause() was called
if (this._state === STATE_PAUSED) {
return this._currentTime;
}
// if the sound is stopped or we don't have a source
// return 0
if (this._state === STATE_STOPPED || !this.source) {
return 0;
}
// recalculate current time
this._updateCurrentTime();
return this._currentTime;
},
set: function (value) {
if (value < 0) return;
if (this._state === STATE_PLAYING) {
// stop first which will set _startOffset to null
this.stop();
const suspend = this._suspendInstanceEvents;
this._suspendInstanceEvents = true;
// set _startOffset and play
this._startOffset = value;
this.play();
this._suspendInstanceEvents = suspend;
} else {
// set _startOffset which will be used when the instance will start playing
this._startOffset = value;
// set _currentTime
this._currentTime = value;
}
}
});
} else {
Object.assign(SoundInstance.prototype, {
play: function () {
if (this._state !== STATE_STOPPED) {
this.stop();
}
if (!this.source) {
if (!this._createSource()) {
return false;
}
}
this.volume = this._volume;
this.pitch = this._pitch;
this.loop = this._loop;
this.source.play();
this._state = STATE_PLAYING;
this._playWhenLoaded = false;
this._manager.on('volumechange', this._onManagerVolumeChange, this);
this._manager.on('suspend', this._onManagerSuspend, this);
this._manager.on('resume', this._onManagerResume, this);
this._manager.on('destroy', this._onManagerDestroy, this);
// suspend immediately if manager is suspended
if (this._manager.suspended)
this._onManagerSuspend();
if (!this._suspendInstanceEvents)
this._onPlay();
return true;
},
pause: function () {
if (!this.source || this._state !== STATE_PLAYING)
return false;
this._suspendEndEvent = true;
this.source.pause();
this._playWhenLoaded = false;
this._state = STATE_PAUSED;
this._startOffset = null;
if (!this._suspendInstanceEvents)
this._onPause();
return true;
},
resume: function () {
if (!this.source || this._state !== STATE_PAUSED)
return false;
this._state = STATE_PLAYING;
this._playWhenLoaded = false;
if (this.source.paused) {
this.source.play();
if (!this._suspendInstanceEvents)
this._onResume();
}
return true;
},
stop: function () {
if (!this.source || this._state === STATE_STOPPED)
return false;
this._manager.off('volumechange', this._onManagerVolumeChange, this);
this._manager.off('suspend', this._onManagerSuspend, this);
this._manager.off('resume', this._onManagerResume, this);
this._manager.off('destroy', this._onManagerDestroy, this);
this._suspendEndEvent = true;
this.source.pause();
this._playWhenLoaded = false;
this._state = STATE_STOPPED;
this._startOffset = null;
if (!this._suspendInstanceEvents)
this._onStop();
return true;
},
setExternalNodes: function () {
// not supported
},
clearExternalNodes: function () {
// not supported
},
getExternalNodes: function () {
// not supported but return same type of result
return [null, null];
},
// Sets start time after loadedmetadata is fired which is required by most browsers
_onLoadedMetadata: function () {
this.source.removeEventListener('loadedmetadata', this._loadedMetadataHandler);
this._isReady = true;
// calculate start time for source
let offset = capTime(this._startOffset, this.duration);
offset = capTime(this._startTime + offset, this._sound.duration);
// reset currentTime
this._startOffset = null;
// set offset on source
this.source.currentTime = offset;
},
_createSource: function () {
if (this._sound && this._sound.audio) {
this._isReady = false;
this.source = this._sound.audio.cloneNode(true);
// set events
this.source.addEventListener('loadedmetadata', this._loadedMetadataHandler);
this.source.addEventListener('timeupdate', this._timeUpdateHandler);
this.source.onended = this._endedHandler;
}
return this.source;
},
// called every time the 'currentTime' is changed
_onTimeUpdate: function () {
if (!this._duration)
return;
// if the currentTime passes the end then if looping go back to the beginning
// otherwise manually stop
if (this.source.currentTime > capTime(this._startTime + this._duration, this.source.duration)) {
if (this.loop) {
this.source.currentTime = capTime(this._startTime, this.source.duration);
} else {
// remove listener to prevent multiple calls
this.source.removeEventListener('timeupdate', this._timeUpdateHandler);
this.source.pause();
// call this manually because it doesn't work in all browsers in this case
this._onEnded();
}
}
},
/**
* @private
* @function
* @name SoundInstance#_onManagerDestroy
* @description Handle the manager's 'destroy' event.
*/
_onManagerDestroy: function () {
if (this.source) {
this.source.pause();
}
}
});
Object.defineProperty(SoundInstance.prototype, 'volume', {
get: function () {
return this._volume;
},
set: function (volume) {
volume = math.clamp(volume, 0, 1);
this._volume = volume;
if (this.source) {
this.source.volume = volume * this._manager.volume;
}
}
});
Object.defineProperty(SoundInstance.prototype, 'pitch', {
get: function () {
return this._pitch;
},
set: function (pitch) {
this._pitch = Math.max(Number(pitch) || 0, 0.01);
if (this.source) {
this.source.playbackRate = this._pitch;
}
}
});
Object.defineProperty(SoundInstance.prototype, 'sound', {
get: function () {
return this._sound;
},
set: function (value) {
this.stop();
this._sound = value;
}
});
Object.defineProperty(SoundInstance.prototype, 'currentTime', {
get: function () {
if (this._startOffset !== null) {
return this._startOffset;
}
if (this._state === STATE_STOPPED || !this.source) {
return 0;
}
return this.source.currentTime - this._startTime;
},
set: function (value) {
if (value < 0) return;
this._startOffset = value;
if (this.source && this._isReady) {
this.source.currentTime = capTime(this._startTime + capTime(value, this.duration), this._sound.duration);
this._startOffset = null;
}
}
});
}
// Events Documentation
/**
* @event
* @name SoundInstance#play
* @description Fired when the instance starts playing its source.
*/
/**
* @event
* @name SoundInstance#pause
* @description Fired when the instance is paused.
*/
/**
* @event
* @name SoundInstance#resume
* @description Fired when the instance is resumed.
*/
/**
* @event
* @name SoundInstance#stop
* @description Fired when the instance is stopped.
*/
/**
* @event
* @name SoundInstance#end
* @description Fired when the sound currently played by the instance ends.
*/
export { SoundInstance };