forked from katspaugh/wavesurfer.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mediaelement.js
executable file
·424 lines (382 loc) · 11.5 KB
/
mediaelement.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
import WebAudio from './webaudio';
import * as util from './util';
/**
* MediaElement backend
*/
export default class MediaElement extends WebAudio {
/**
* Construct the backend
*
* @param {WavesurferParams} params Wavesurfer parameters
*/
constructor(params) {
super(params);
/** @private */
this.params = params;
/**
* Initially a dummy media element to catch errors. Once `_load` is
* called, this will contain the actual `HTMLMediaElement`.
* @private
*/
this.media = {
currentTime: 0,
duration: 0,
paused: true,
playbackRate: 1,
play() {},
pause() {},
volume: 0
};
/** @private */
this.mediaType = params.mediaType.toLowerCase();
/** @private */
this.elementPosition = params.elementPosition;
/** @private */
this.peaks = null;
/** @private */
this.playbackRate = 1;
/** @private */
this.volume = 1;
/** @private */
this.isMuted = false;
/** @private */
this.buffer = null;
/** @private */
this.onPlayEnd = null;
/** @private */
this.mediaListeners = {};
}
/**
* Initialise the backend, called in `wavesurfer.createBackend()`
*/
init() {
this.setPlaybackRate(this.params.audioRate);
this.createTimer();
}
/**
* Attach event listeners to media element.
*/
_setupMediaListeners() {
this.mediaListeners.error = () => {
this.fireEvent('error', 'Error loading media element');
};
this.mediaListeners.canplay = () => {
this.fireEvent('canplay');
};
this.mediaListeners.ended = () => {
this.fireEvent('finish');
};
// listen to and relay play, pause and seeked events to enable
// playback control from the external media element
this.mediaListeners.play = () => {
this.fireEvent('play');
};
this.mediaListeners.pause = () => {
this.fireEvent('pause');
};
this.mediaListeners.seeked = event => {
this.fireEvent('seek');
};
this.mediaListeners.volumechange = event => {
this.isMuted = this.media.muted;
if (this.isMuted) {
this.volume = 0;
} else {
this.volume = this.media.volume;
}
this.fireEvent('volume');
};
// reset event listeners
Object.keys(this.mediaListeners).forEach(id => {
this.media.removeEventListener(id, this.mediaListeners[id]);
this.media.addEventListener(id, this.mediaListeners[id]);
});
}
/**
* Create a timer to provide a more precise `audioprocess` event.
*/
createTimer() {
const onAudioProcess = () => {
if (this.isPaused()) {
return;
}
this.fireEvent('audioprocess', this.getCurrentTime());
// Call again in the next frame
util.frame(onAudioProcess)();
};
this.on('play', onAudioProcess);
// Update the progress one more time to prevent it from being stuck in
// case of lower framerates
this.on('pause', () => {
this.fireEvent('audioprocess', this.getCurrentTime());
});
}
/**
* Create media element with url as its source,
* and append to container element.
*
* @param {string} url Path to media file
* @param {HTMLElement} container HTML element
* @param {number[]|Number.<Array[]>} peaks Array of peak data
* @param {string} preload HTML 5 preload attribute value
* @throws Will throw an error if the `url` argument is not a valid media
* element.
*/
load(url, container, peaks, preload) {
const media = document.createElement(this.mediaType);
media.controls = this.params.mediaControls;
media.autoplay = this.params.autoplay || false;
media.preload = preload == null ? 'auto' : preload;
media.src = url;
media.style.width = '100%';
const prevMedia = container.querySelector(this.mediaType);
if (prevMedia) {
container.removeChild(prevMedia);
}
container.appendChild(media);
this._load(media, peaks);
}
/**
* Load existing media element.
*
* @param {HTMLMediaElement} elt HTML5 Audio or Video element
* @param {number[]|Number.<Array[]>} peaks Array of peak data
*/
loadElt(elt, peaks) {
elt.controls = this.params.mediaControls;
elt.autoplay = this.params.autoplay || false;
this._load(elt, peaks);
}
/**
* Method called by both `load` (from url)
* and `loadElt` (existing media element) methods.
*
* @param {HTMLMediaElement} media HTML5 Audio or Video element
* @param {number[]|Number.<Array[]>} peaks Array of peak data
* @throws Will throw an error if the `media` argument is not a valid media
* element.
* @private
*/
_load(media, peaks) {
// verify media element is valid
if (
!(media instanceof HTMLMediaElement) ||
typeof media.addEventListener === 'undefined'
) {
throw new Error('media parameter is not a valid media element');
}
// load must be called manually on iOS, otherwise peaks won't draw
// until a user interaction triggers load --> 'ready' event
if (typeof media.load == 'function') {
// Resets the media element and restarts the media resource. Any
// pending events are discarded. How much media data is fetched is
// still affected by the preload attribute.
media.load();
}
this.media = media;
this._setupMediaListeners();
this.peaks = peaks;
this.onPlayEnd = null;
this.buffer = null;
this.isMuted = media.muted;
this.setPlaybackRate(this.playbackRate);
this.setVolume(this.volume);
}
/**
* Used by `wavesurfer.isPlaying()` and `wavesurfer.playPause()`
*
* @return {boolean} Media paused or not
*/
isPaused() {
return !this.media || this.media.paused;
}
/**
* Used by `wavesurfer.getDuration()`
*
* @return {number} Duration
*/
getDuration() {
if (this.explicitDuration) {
return this.explicitDuration;
}
let duration = (this.buffer || this.media).duration;
if (duration >= Infinity) {
// streaming audio
duration = this.media.seekable.end(0);
}
return duration;
}
/**
* Returns the current time in seconds relative to the audio-clip's
* duration.
*
* @return {number} Current time
*/
getCurrentTime() {
return this.media && this.media.currentTime;
}
/**
* Get the position from 0 to 1
*
* @return {number} Current position
*/
getPlayedPercents() {
return this.getCurrentTime() / this.getDuration() || 0;
}
/**
* Get the audio source playback rate.
*
* @return {number} Playback rate
*/
getPlaybackRate() {
return this.playbackRate || this.media.playbackRate;
}
/**
* Set the audio source playback rate.
*
* @param {number} value Playback rate
*/
setPlaybackRate(value) {
this.playbackRate = value || 1;
this.media.playbackRate = this.playbackRate;
}
/**
* Used by `wavesurfer.seekTo()`
*
* @param {number} start Position to start at in seconds
*/
seekTo(start) {
if (start != null) {
this.media.currentTime = start;
}
this.clearPlayEnd();
}
/**
* Plays the loaded audio region.
*
* @param {number} start Start offset in seconds, relative to the beginning
* of a clip.
* @param {number} end When to stop, relative to the beginning of a clip.
* @emits MediaElement#play
* @return {Promise} Result
*/
play(start, end) {
this.seekTo(start);
const promise = this.media.play();
end && this.setPlayEnd(end);
return promise;
}
/**
* Pauses the loaded audio.
*
* @emits MediaElement#pause
* @return {Promise} Result
*/
pause() {
let promise;
if (this.media) {
promise = this.media.pause();
}
this.clearPlayEnd();
return promise;
}
/**
* Set the play end
*
* @param {number} end Where to end
*/
setPlayEnd(end) {
this.clearPlayEnd();
this._onPlayEnd = time => {
if (time >= end) {
this.pause();
this.seekTo(end);
}
};
this.on('audioprocess', this._onPlayEnd);
}
/** @private */
clearPlayEnd() {
if (this._onPlayEnd) {
this.un('audioprocess', this._onPlayEnd);
this._onPlayEnd = null;
}
}
/**
* Compute the max and min value of the waveform when broken into
* <length> subranges.
*
* @param {number} length How many subranges to break the waveform into.
* @param {number} first First sample in the required range.
* @param {number} last Last sample in the required range.
* @return {number[]|Number.<Array[]>} Array of 2*<length> peaks or array of
* arrays of peaks consisting of (max, min) values for each subrange.
*/
getPeaks(length, first, last) {
if (this.buffer) {
return super.getPeaks(length, first, last);
}
return this.peaks || [];
}
/**
* Set the sink id for the media player
*
* @param {string} deviceId String value representing audio device id.
* @returns {Promise} A Promise that resolves to `undefined` when there
* are no errors.
*/
setSinkId(deviceId) {
if (deviceId) {
if (!this.media.setSinkId) {
return Promise.reject(
new Error('setSinkId is not supported in your browser')
);
}
return this.media.setSinkId(deviceId);
}
return Promise.reject(new Error('Invalid deviceId: ' + deviceId));
}
/**
* Get the current volume
*
* @return {number} value A floating point value between 0 and 1.
*/
getVolume() {
return this.volume;
}
/**
* Set the audio volume
*
* @param {number} value A floating point value between 0 and 1.
*/
setVolume(value) {
this.volume = value;
// no need to change when it's already at that volume
if (this.media.volume !== this.volume) {
this.media.volume = this.volume;
}
}
/**
* This is called when wavesurfer is destroyed
*
*/
destroy() {
this.pause();
this.unAll();
this.destroyed = true;
// cleanup media event listeners
Object.keys(this.mediaListeners).forEach(id => {
if (this.media) {
this.media.removeEventListener(id, this.mediaListeners[id]);
}
});
if (
this.params.removeMediaElementOnDestroy &&
this.media &&
this.media.parentNode
) {
this.media.parentNode.removeChild(this.media);
}
this.media = null;
}
}