/
wavesurfer.js
executable file
·1826 lines (1689 loc) · 59.2 KB
/
wavesurfer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as util from './util';
import MultiCanvas from './drawer.multicanvas';
import WebAudio from './webaudio';
import MediaElement from './mediaelement';
import PeakCache from './peakcache';
import MediaElementWebAudio from './mediaelement-webaudio';
/*
* This work is licensed under a BSD-3-Clause License.
*/
/** @external {HTMLElement} https://developer.mozilla.org/en/docs/Web/API/HTMLElement */
/** @external {OfflineAudioContext} https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext */
/** @external {File} https://developer.mozilla.org/en-US/docs/Web/API/File */
/** @external {Blob} https://developer.mozilla.org/en-US/docs/Web/API/Blob */
/** @external {CanvasRenderingContext2D} https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D */
/** @external {MediaStreamConstraints} https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints */
/** @external {AudioNode} https://developer.mozilla.org/de/docs/Web/API/AudioNode */
/**
* @typedef {Object} WavesurferParams
* @property {AudioContext} audioContext=null Use your own previously
* initialized AudioContext or leave blank.
* @property {number} audioRate=1 Speed at which to play audio. Lower number is
* slower.
* @property {ScriptProcessorNode} audioScriptProcessor=null Use your own previously
* initialized ScriptProcessorNode or leave blank.
* @property {boolean} autoCenter=true If a scrollbar is present, center the
* waveform on current progress
* @property {number} autoCenterRate=5 If autoCenter is active, rate at which the
* waveform is centered
* @property {boolean} autoCenterImmediately=false If autoCenter is active, immediately
* center waveform on current progress
* @property {string} backend='WebAudio' `'WebAudio'|'MediaElement'|'MediaElementWebAudio'` In most cases
* you don't have to set this manually. MediaElement is a fallback for unsupported browsers.
* MediaElementWebAudio allows to use WebAudio API also with big audio files, loading audio like with
* MediaElement backend (HTML5 audio tag). You have to use the same methods of MediaElement backend for loading and
* playback, giving also peaks, so the audio data are not decoded. In this way you can use WebAudio features, like filters,
* also with audio with big duration. For example:
* ` wavesurfer.load(url | HTMLMediaElement, peaks, preload, duration);
* wavesurfer.play();
* wavesurfer.setFilter(customFilter);
* `
* @property {string} backgroundColor=null Change background color of the
* waveform container.
* @property {number} barHeight=1 The height of the wave bars.
* @property {number} barRadius=0 The radius of the wave bars. Makes bars rounded
* @property {number} barGap=null The optional spacing between bars of the wave,
* if not provided will be calculated in legacy format.
* @property {number} barWidth=null Draw the waveform using bars.
* @property {number} barMinHeight=null If specified, draw at least a bar of this height,
* eliminating waveform gaps
* @property {boolean} closeAudioContext=false Close and nullify all audio
* contexts when the destroy method is called.
* @property {!string|HTMLElement} container CSS selector or HTML element where
* the waveform should be drawn. This is the only required parameter.
* @property {string} cursorColor='#333' The fill color of the cursor indicating
* the playhead position.
* @property {number} cursorWidth=1 Measured in pixels.
* @property {object} drawingContextAttributes={desynchronized: false} Drawing context
* attributes.
* @property {number} duration=null Optional audio length so pre-rendered peaks
* can be display immediately for example.
* @property {boolean} fillParent=true Whether to fill the entire container or
* draw only according to `minPxPerSec`.
* @property {boolean} forceDecode=false Force decoding of audio using web audio
* when zooming to get a more detailed waveform.
* @property {number} height=128 The height of the waveform. Measured in
* pixels.
* @property {boolean} hideScrollbar=false Whether to hide the horizontal
* scrollbar when one would normally be shown.
* @property {boolean} hideCursor=false Whether to hide the mouse cursor
* when one would normally be shown by default.
* @property {boolean} ignoreSilenceMode=false If true, ignores device silence mode
* when using the `WebAudio` backend.
* @property {boolean} interact=true Whether the mouse interaction will be
* enabled at initialization. You can switch this parameter at any time later
* on.
* @property {boolean} loopSelection=true (Use with regions plugin) Enable
* looping of selected regions
* @property {number} maxCanvasWidth=4000 Maximum width of a single canvas in
* pixels, excluding a small overlap (2 * `pixelRatio`, rounded up to the next
* even integer). If the waveform is longer than this value, additional canvases
* will be used to render the waveform, which is useful for very large waveforms
* that may be too wide for browsers to draw on a single canvas.
* @property {boolean} mediaControls=false (Use with backend `MediaElement` or `MediaElementWebAudio`)
* this enables the native controls for the media element
* @property {string} mediaType='audio' (Use with backend `MediaElement` or `MediaElementWebAudio`)
* `'audio'|'video'` ('video' only for `MediaElement`)
* @property {number} minPxPerSec=20 Minimum number of pixels per second of
* audio.
* @property {boolean} normalize=false If true, normalize by the maximum peak
* instead of 1.0.
* @property {boolean} partialRender=false Use the PeakCache to improve
* rendering speed of large waveforms
* @property {number} pixelRatio=window.devicePixelRatio The pixel ratio used to
* calculate display
* @property {PluginDefinition[]} plugins=[] An array of plugin definitions to
* register during instantiation, they will be directly initialised unless they
* are added with the `deferInit` property set to true.
* @property {string} progressColor='#555' The fill color of the part of the
* waveform behind the cursor. When `progressColor` and `waveColor` are the same
* the progress wave is not rendered at all.
* @property {boolean} removeMediaElementOnDestroy=true Set to false to keep the
* media element in the DOM when the player is destroyed. This is useful when
* reusing an existing media element via the `loadMediaElement` method.
* @property {Object} renderer=MultiCanvas Can be used to inject a custom
* renderer.
* @property {boolean|number} responsive=false If set to `true` resize the
* waveform, when the window is resized. This is debounced with a `100ms`
* timeout by default. If this parameter is a number it represents that timeout.
* @property {boolean} rtl=false If set to `true`, renders waveform from
* right-to-left.
* @property {boolean} scrollParent=false Whether to scroll the container with a
* lengthy waveform. Otherwise the waveform is shrunk to the container width
* (see fillParent).
* @property {number} skipLength=2 Number of seconds to skip with the
* skipForward() and skipBackward() methods.
* @property {boolean} splitChannels=false Render with separate waveforms for
* the channels of the audio
* @property {SplitChannelOptions} splitChannelsOptions={} Options for splitChannel rendering
* @property {boolean} vertical=false Render the waveform vertically instead of horizontally.
* @property {string} waveColor='#999' The fill color of the waveform after the
* cursor.
* @property {object} xhr={} XHR options. For example:
* `let xhr = {
* cache: 'default',
* mode: 'cors',
* method: 'GET',
* credentials: 'same-origin',
* redirect: 'follow',
* referrer: 'client',
* requestHeaders: [
* {
* key: 'Authorization',
* value: 'my-token'
* }
* ]
* };`
*/
/**
* @typedef {Object} PluginDefinition
* @desc The Object used to describe a plugin
* @example wavesurfer.addPlugin(pluginDefinition);
* @property {string} name The name of the plugin, the plugin instance will be
* added as a property to the wavesurfer instance under this name
* @property {?Object} staticProps The properties that should be added to the
* wavesurfer instance as static properties
* @property {?boolean} deferInit Don't initialise plugin
* automatically
* @property {Object} params={} The plugin parameters, they are the first parameter
* passed to the plugin class constructor function
* @property {PluginClass} instance The plugin instance factory, is called with
* the dependency specified in extends. Returns the plugin class.
*/
/**
* @typedef {Object} SplitChannelOptions
* @desc parameters applied when splitChannels option is true
* @property {boolean} overlay=false determines whether channels are rendered on top of each other or on separate tracks
* @property {object} channelColors={} object describing color for each channel. Example:
* {
* 0: {
* progressColor: 'green',
* waveColor: 'pink'
* },
* 1: {
* progressColor: 'orange',
* waveColor: 'purple'
* }
* }
* @property {number[]} filterChannels=[] indexes of channels to be hidden from rendering
* @property {boolean} relativeNormalization=false determines whether
* normalization is done per channel or maintains proportionality between
* channels. Only applied when normalize and splitChannels are both true.
* @property {boolean} splitDragSelection=false determines if drag selection in regions
* plugin works separately on each channel or only one selection for all channels
* @since 4.3.0
*/
/**
* @interface PluginClass
*
* @desc This is the interface which is implemented by all plugin classes. Note
* that this only turns into an observer after being passed through
* `wavesurfer.addPlugin`.
*
* @extends {Observer}
*/
class PluginClass {
/**
* Plugin definition factory
*
* This function must be used to create a plugin definition which can be
* used by wavesurfer to correctly instantiate the plugin.
*
* It returns a `PluginDefinition` object representing the plugin.
*
* @param {Object} params={} The plugin params (specific to the plugin)
*/
create(params) {}
/**
* Construct the plugin
*
* @param {Object} params={} The plugin params (specific to the plugin)
* @param {Object} ws The wavesurfer instance
*/
constructor(params, ws) {}
/**
* Initialise the plugin
*
* Start doing something. This is called by
* `wavesurfer.initPlugin(pluginName)`
*/
init() {}
/**
* Destroy the plugin instance
*
* Stop doing something. This is called by
* `wavesurfer.destroyPlugin(pluginName)`
*/
destroy() {}
}
/**
* WaveSurfer core library class
*
* @extends {Observer}
* @example
* const params = {
* container: '#waveform',
* waveColor: 'violet',
* progressColor: 'purple'
* };
*
* // initialise like this
* const wavesurfer = WaveSurfer.create(params);
*
* // or like this ...
* const wavesurfer = new WaveSurfer(params);
* wavesurfer.init();
*
* // load audio file
* wavesurfer.load('example/media/demo.wav');
*/
export default class WaveSurfer extends util.Observer {
/** @private */
defaultParams = {
audioContext: null,
audioScriptProcessor: null,
audioRate: 1,
autoCenter: true,
autoCenterRate: 5,
autoCenterImmediately: false,
backend: 'WebAudio',
backgroundColor: null,
barHeight: 1,
barRadius: 0,
barGap: null,
barMinHeight: null,
container: null,
cursorColor: '#333',
cursorWidth: 1,
dragSelection: true,
drawingContextAttributes: {
// Boolean that hints the user agent to reduce the latency
// by desynchronizing the canvas paint cycle from the event
// loop
desynchronized: false
},
duration: null,
fillParent: true,
forceDecode: false,
height: 128,
hideScrollbar: false,
hideCursor: false,
ignoreSilenceMode: false,
interact: true,
loopSelection: true,
maxCanvasWidth: 4000,
mediaContainer: null,
mediaControls: false,
mediaType: 'audio',
minPxPerSec: 20,
normalize: false,
partialRender: false,
pixelRatio:
window.devicePixelRatio || screen.deviceXDPI / screen.logicalXDPI,
plugins: [],
progressColor: '#555',
removeMediaElementOnDestroy: true,
renderer: MultiCanvas,
responsive: false,
rtl: false,
scrollParent: false,
skipLength: 2,
splitChannels: false,
splitChannelsOptions: {
overlay: false,
channelColors: {},
filterChannels: [],
relativeNormalization: false,
splitDragSelection: false
},
vertical: false,
waveColor: '#999',
xhr: {}
};
/** @private */
backends = {
MediaElement,
WebAudio,
MediaElementWebAudio
};
/**
* Instantiate this class, call its `init` function and returns it
*
* @param {WavesurferParams} params The wavesurfer parameters
* @return {Object} WaveSurfer instance
* @example const wavesurfer = WaveSurfer.create(params);
*/
static create(params) {
const wavesurfer = new WaveSurfer(params);
return wavesurfer.init();
}
/**
* The library version number is available as a static property of the
* WaveSurfer class
*
* @type {String}
* @example
* console.log('Using wavesurfer.js ' + WaveSurfer.VERSION);
*/
static VERSION = __VERSION__;
/**
* Functions in the `util` property are available as a prototype property to
* all instances
*
* @type {Object}
* @example
* const wavesurfer = WaveSurfer.create(params);
* wavesurfer.util.style(myElement, { background: 'blue' });
*/
util = util;
/**
* Functions in the `util` property are available as a static property of the
* WaveSurfer class
*
* @type {Object}
* @example
* WaveSurfer.util.style(myElement, { background: 'blue' });
*/
static util = util;
/**
* Initialise wavesurfer instance
*
* @param {WavesurferParams} params Instantiation options for wavesurfer
* @example
* const wavesurfer = new WaveSurfer(params);
* @returns {this} Wavesurfer instance
*/
constructor(params) {
super();
/**
* Extract relevant parameters (or defaults)
* @private
*/
this.params = Object.assign({}, this.defaultParams, params);
this.params.splitChannelsOptions = Object.assign(
{},
this.defaultParams.splitChannelsOptions,
params.splitChannelsOptions
);
/** @private */
this.container =
'string' == typeof params.container
? document.querySelector(this.params.container)
: this.params.container;
if (!this.container) {
throw new Error('Container element not found');
}
if (this.params.mediaContainer == null) {
/** @private */
this.mediaContainer = this.container;
} else if (typeof this.params.mediaContainer == 'string') {
/** @private */
this.mediaContainer = document.querySelector(
this.params.mediaContainer
);
} else {
/** @private */
this.mediaContainer = this.params.mediaContainer;
}
if (!this.mediaContainer) {
throw new Error('Media Container element not found');
}
if (this.params.maxCanvasWidth <= 1) {
throw new Error('maxCanvasWidth must be greater than 1');
} else if (this.params.maxCanvasWidth % 2 == 1) {
throw new Error('maxCanvasWidth must be an even number');
}
if (this.params.rtl === true) {
if (this.params.vertical === true) {
util.style(this.container, { transform: 'rotateX(180deg)' });
} else {
util.style(this.container, { transform: 'rotateY(180deg)' });
}
}
if (this.params.backgroundColor) {
this.setBackgroundColor(this.params.backgroundColor);
}
/**
* @private Used to save the current volume when muting so we can
* restore once unmuted
* @type {number}
*/
this.savedVolume = 0;
/**
* @private The current muted state
* @type {boolean}
*/
this.isMuted = false;
/**
* @private Will hold a list of event descriptors that need to be
* canceled on subsequent loads of audio
* @type {Object[]}
*/
this.tmpEvents = [];
/**
* @private Holds any running audio downloads
* @type {Observer}
*/
this.currentRequest = null;
/** @private */
this.arraybuffer = null;
/** @private */
this.drawer = null;
/** @private */
this.backend = null;
/** @private */
this.peakCache = null;
// cache constructor objects
if (typeof this.params.renderer !== 'function') {
throw new Error('Renderer parameter is invalid');
}
/**
* @private The uninitialised Drawer class
*/
this.Drawer = this.params.renderer;
/**
* @private The uninitialised Backend class
*/
// Back compat
if (this.params.backend == 'AudioElement') {
this.params.backend = 'MediaElement';
}
if (
(this.params.backend == 'WebAudio' ||
this.params.backend === 'MediaElementWebAudio') &&
!WebAudio.prototype.supportsWebAudio.call(null)
) {
this.params.backend = 'MediaElement';
}
this.Backend = this.backends[this.params.backend];
/**
* @private map of plugin names that are currently initialised
*/
this.initialisedPluginList = {};
/** @private */
this.isDestroyed = false;
/**
* Get the current ready status.
*
* @example const isReady = wavesurfer.isReady;
* @return {boolean}
*/
this.isReady = false;
// responsive debounced event listener. If this.params.responsive is not
// set, this is never called. Use 100ms or this.params.responsive as
// timeout for the debounce function.
let prevWidth = 0;
this._onResize = util.debounce(
() => {
if (
this.drawer.wrapper &&
prevWidth != this.drawer.wrapper.clientWidth &&
!this.params.scrollParent
) {
prevWidth = this.drawer.wrapper.clientWidth;
if (prevWidth) {
// redraw only if waveform container is rendered and has a width
this.drawer.fireEvent('redraw');
}
}
},
typeof this.params.responsive === 'number'
? this.params.responsive
: 100
);
return this;
}
/**
* Initialise the wave
*
* @example
* var wavesurfer = new WaveSurfer(params);
* wavesurfer.init();
* @return {this} The wavesurfer instance
*/
init() {
this.registerPlugins(this.params.plugins);
this.createDrawer();
this.createBackend();
this.createPeakCache();
return this;
}
/**
* Add and initialise array of plugins (if `plugin.deferInit` is falsey),
* this function is called in the init function of wavesurfer
*
* @param {PluginDefinition[]} plugins An array of plugin definitions
* @emits {WaveSurfer#plugins-registered} Called with the array of plugin definitions
* @return {this} The wavesurfer instance
*/
registerPlugins(plugins) {
// first instantiate all the plugins
plugins.forEach(plugin => this.addPlugin(plugin));
// now run the init functions
plugins.forEach(plugin => {
// call init function of the plugin if deferInit is falsey
// in that case you would manually use initPlugins()
if (!plugin.deferInit) {
this.initPlugin(plugin.name);
}
});
this.fireEvent('plugins-registered', plugins);
return this;
}
/**
* Get a map of plugin names that are currently initialised
*
* @example wavesurfer.getPlugins();
* @return {Object} Object with plugin names
*/
getActivePlugins() {
return this.initialisedPluginList;
}
/**
* Add a plugin object to wavesurfer
*
* @param {PluginDefinition} plugin A plugin definition
* @emits {WaveSurfer#plugin-added} Called with the name of the plugin that was added
* @example wavesurfer.addPlugin(WaveSurfer.minimap());
* @return {this} The wavesurfer instance
*/
addPlugin(plugin) {
if (!plugin.name) {
throw new Error('Plugin does not have a name!');
}
if (!plugin.instance) {
throw new Error(
`Plugin ${plugin.name} does not have an instance property!`
);
}
// staticProps properties are applied to wavesurfer instance
if (plugin.staticProps) {
Object.keys(plugin.staticProps).forEach(pluginStaticProp => {
/**
* Properties defined in a plugin definition's `staticProps` property are added as
* staticProps properties of the WaveSurfer instance
*/
this[pluginStaticProp] = plugin.staticProps[pluginStaticProp];
});
}
const Instance = plugin.instance;
// turn the plugin instance into an observer
const observerPrototypeKeys = Object.getOwnPropertyNames(
util.Observer.prototype
);
observerPrototypeKeys.forEach(key => {
Instance.prototype[key] = util.Observer.prototype[key];
});
/**
* Instantiated plugin classes are added as a property of the wavesurfer
* instance
* @type {Object}
*/
this[plugin.name] = new Instance(plugin.params || {}, this);
this.fireEvent('plugin-added', plugin.name);
return this;
}
/**
* Initialise a plugin
*
* @param {string} name A plugin name
* @emits WaveSurfer#plugin-initialised
* @example wavesurfer.initPlugin('minimap');
* @return {this} The wavesurfer instance
*/
initPlugin(name) {
if (!this[name]) {
throw new Error(`Plugin ${name} has not been added yet!`);
}
if (this.initialisedPluginList[name]) {
// destroy any already initialised plugins
this.destroyPlugin(name);
}
this[name].init();
this.initialisedPluginList[name] = true;
this.fireEvent('plugin-initialised', name);
return this;
}
/**
* Destroy a plugin
*
* @param {string} name A plugin name
* @emits WaveSurfer#plugin-destroyed
* @example wavesurfer.destroyPlugin('minimap');
* @returns {this} The wavesurfer instance
*/
destroyPlugin(name) {
if (!this[name]) {
throw new Error(
`Plugin ${name} has not been added yet and cannot be destroyed!`
);
}
if (!this.initialisedPluginList[name]) {
throw new Error(
`Plugin ${name} is not active and cannot be destroyed!`
);
}
if (typeof this[name].destroy !== 'function') {
throw new Error(`Plugin ${name} does not have a destroy function!`);
}
this[name].destroy();
delete this.initialisedPluginList[name];
this.fireEvent('plugin-destroyed', name);
return this;
}
/**
* Destroy all initialised plugins. Convenience function to use when
* wavesurfer is removed
*
* @private
*/
destroyAllPlugins() {
Object.keys(this.initialisedPluginList).forEach(name =>
this.destroyPlugin(name)
);
}
/**
* Create the drawer and draw the waveform
*
* @private
* @emits WaveSurfer#drawer-created
*/
createDrawer() {
this.drawer = new this.Drawer(this.container, this.params);
this.drawer.init();
this.fireEvent('drawer-created', this.drawer);
if (this.params.responsive !== false) {
window.addEventListener('resize', this._onResize, true);
window.addEventListener('orientationchange', this._onResize, true);
}
this.drawer.on('redraw', () => {
this.drawBuffer();
this.drawer.progress(this.backend.getPlayedPercents());
});
// Click-to-seek
this.drawer.on('click', (e, progress) => {
setTimeout(() => this.seekTo(progress), 0);
});
// Relay the scroll event from the drawer
this.drawer.on('scroll', e => {
if (this.params.partialRender) {
this.drawBuffer();
}
this.fireEvent('scroll', e);
});
}
/**
* Create the backend
*
* @private
* @emits WaveSurfer#backend-created
*/
createBackend() {
if (this.backend) {
this.backend.destroy();
}
this.backend = new this.Backend(this.params);
this.backend.init();
this.fireEvent('backend-created', this.backend);
this.backend.on('finish', () => {
this.drawer.progress(this.backend.getPlayedPercents());
this.fireEvent('finish');
});
this.backend.on('play', () => this.fireEvent('play'));
this.backend.on('pause', () => this.fireEvent('pause'));
this.backend.on('audioprocess', time => {
this.drawer.progress(this.backend.getPlayedPercents());
this.fireEvent('audioprocess', time);
});
// only needed for MediaElement and MediaElementWebAudio backend
if (
this.params.backend === 'MediaElement' ||
this.params.backend === 'MediaElementWebAudio'
) {
this.backend.on('seek', () => {
this.drawer.progress(this.backend.getPlayedPercents());
});
this.backend.on('volume', () => {
let newVolume = this.getVolume();
this.fireEvent('volume', newVolume);
if (this.backend.isMuted !== this.isMuted) {
this.isMuted = this.backend.isMuted;
this.fireEvent('mute', this.isMuted);
}
});
}
}
/**
* Create the peak cache
*
* @private
*/
createPeakCache() {
if (this.params.partialRender) {
this.peakCache = new PeakCache();
}
}
/**
* Get the duration of the audio clip
*
* @example const duration = wavesurfer.getDuration();
* @return {number} Duration in seconds
*/
getDuration() {
return this.backend.getDuration();
}
/**
* Get the current playback position
*
* @example const currentTime = wavesurfer.getCurrentTime();
* @return {number} Playback position in seconds
*/
getCurrentTime() {
return this.backend.getCurrentTime();
}
/**
* Set the current play time in seconds.
*
* @param {number} seconds A positive number in seconds. E.g. 10 means 10
* seconds, 60 means 1 minute
*/
setCurrentTime(seconds) {
if (seconds >= this.getDuration()) {
this.seekTo(1);
} else {
this.seekTo(seconds / this.getDuration());
}
}
/**
* Starts playback from the current position. Optional start and end
* measured in seconds can be used to set the range of audio to play.
*
* @param {?number} start Position to start at
* @param {?number} end Position to end at
* @emits WaveSurfer#interaction
* @return {Promise} Result of the backend play method
* @example
* // play from second 1 to 5
* wavesurfer.play(1, 5);
*/
play(start, end) {
if (this.params.ignoreSilenceMode) {
// ignores device hardware silence mode
util.ignoreSilenceMode();
}
this.fireEvent('interaction', () => this.play(start, end));
return this.backend.play(start, end);
}
/**
* Set a point in seconds for playback to stop at.
*
* @param {number} position Position (in seconds) to stop at
* @version 3.3.0
*/
setPlayEnd(position) {
this.backend.setPlayEnd(position);
}
/**
* Stops and pauses playback
*
* @example wavesurfer.pause();
* @return {Promise} Result of the backend pause method
*/
pause() {
if (!this.backend.isPaused()) {
return this.backend.pause();
}
}
/**
* Toggle playback
*
* @example wavesurfer.playPause();
* @return {Promise} Result of the backend play or pause method
*/
playPause() {
return this.backend.isPaused() ? this.play() : this.pause();
}
/**
* Get the current playback state
*
* @example const isPlaying = wavesurfer.isPlaying();
* @return {boolean} False if paused, true if playing
*/
isPlaying() {
return !this.backend.isPaused();
}
/**
* Skip backward
*
* @param {?number} seconds Amount to skip back, if not specified `skipLength`
* is used
* @example wavesurfer.skipBackward();
*/
skipBackward(seconds) {
this.skip(-seconds || -this.params.skipLength);
}
/**
* Skip forward
*
* @param {?number} seconds Amount to skip back, if not specified `skipLength`
* is used
* @example wavesurfer.skipForward();
*/
skipForward(seconds) {
this.skip(seconds || this.params.skipLength);
}
/**
* Skip a number of seconds from the current position (use a negative value
* to go backwards).
*
* @param {number} offset Amount to skip back or forwards
* @example
* // go back 2 seconds
* wavesurfer.skip(-2);
*/
skip(offset) {
const duration = this.getDuration() || 1;
let position = this.getCurrentTime() || 0;
position = Math.max(0, Math.min(duration, position + (offset || 0)));
this.seekAndCenter(position / duration);
}
/**
* Seeks to a position and centers the view
*
* @param {number} progress Between 0 (=beginning) and 1 (=end)
* @example
* // seek and go to the middle of the audio
* wavesurfer.seekTo(0.5);
*/
seekAndCenter(progress) {
this.seekTo(progress);
this.drawer.recenter(progress);
}
/**
* Seeks to a position
*
* @param {number} progress Between 0 (=beginning) and 1 (=end)
* @emits WaveSurfer#interaction
* @emits WaveSurfer#seek
* @example
* // seek to the middle of the audio
* wavesurfer.seekTo(0.5);
*/
seekTo(progress) {
// return an error if progress is not a number between 0 and 1
if (
typeof progress !== 'number' ||
!isFinite(progress) ||
progress < 0 ||
progress > 1
) {
throw new Error(
'Error calling wavesurfer.seekTo, parameter must be a number between 0 and 1!'
);
}
this.fireEvent('interaction', () => this.seekTo(progress));
const isWebAudioBackend = this.params.backend === 'WebAudio';
const paused = this.backend.isPaused();
if (isWebAudioBackend && !paused) {
this.backend.pause();
}
// avoid small scrolls while paused seeking
const oldScrollParent = this.params.scrollParent;
this.params.scrollParent = false;
this.backend.seekTo(progress * this.getDuration());
this.drawer.progress(progress);
if (isWebAudioBackend && !paused) {
this.backend.play();
}
this.params.scrollParent = oldScrollParent;
this.fireEvent('seek', progress);
}
/**
* Stops and goes to the beginning.
*
* @example wavesurfer.stop();
*/
stop() {
this.pause();
this.seekTo(0);
this.drawer.progress(0);
}
/**
* Sets the ID of the audio device to use for output and returns a Promise.
*
* @param {string} deviceId String value representing underlying output
* device
* @returns {Promise} `Promise` that resolves to `undefined` when there are
* no errors detected.
*/
setSinkId(deviceId) {
return this.backend.setSinkId(deviceId);
}
/**
* Set the playback volume.