wavesurfer.js 7.11.0 → 7.11.1
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.
- package/dist/__tests__/renderer-utils.test.d.ts +1 -0
- package/dist/__tests__/renderer-utils.test.js +320 -0
- package/dist/decoder.js +12 -4
- package/dist/draggable.js +16 -5
- package/dist/fetcher.js +14 -23
- package/dist/plugins/envelope.cjs +1 -1
- package/dist/plugins/envelope.esm.js +1 -1
- package/dist/plugins/envelope.js +1 -1
- package/dist/plugins/envelope.min.js +1 -1
- package/dist/plugins/minimap.cjs +1 -1
- package/dist/plugins/minimap.esm.js +1 -1
- package/dist/plugins/minimap.js +1 -1
- package/dist/plugins/minimap.min.js +1 -1
- package/dist/plugins/regions.cjs +1 -1
- package/dist/plugins/regions.esm.js +1 -1
- package/dist/plugins/regions.js +1 -1
- package/dist/plugins/regions.min.js +1 -1
- package/dist/plugins/zoom.cjs +1 -1
- package/dist/plugins/zoom.d.ts +10 -1
- package/dist/plugins/zoom.esm.js +1 -1
- package/dist/plugins/zoom.js +1 -1
- package/dist/plugins/zoom.min.js +1 -1
- package/dist/renderer-utils.d.ts +117 -0
- package/dist/renderer-utils.js +232 -0
- package/dist/renderer.d.ts +2 -3
- package/dist/renderer.js +105 -171
- package/dist/types.d.ts +2 -0
- package/dist/wavesurfer.cjs +1 -1
- package/dist/wavesurfer.d.ts +2 -0
- package/dist/wavesurfer.esm.js +1 -1
- package/dist/wavesurfer.js +14 -8
- package/dist/wavesurfer.min.js +1 -1
- package/dist/webaudio.js +4 -0
- package/package.json +6 -5
package/dist/renderer.d.ts
CHANGED
|
@@ -9,10 +9,9 @@ type RendererEvents = {
|
|
|
9
9
|
scroll: [relativeStart: number, relativeEnd: number, scrollLeft: number, scrollRight: number];
|
|
10
10
|
render: [];
|
|
11
11
|
rendered: [];
|
|
12
|
+
resize: [];
|
|
12
13
|
};
|
|
13
14
|
declare class Renderer extends EventEmitter<RendererEvents> {
|
|
14
|
-
private static MAX_CANVAS_WIDTH;
|
|
15
|
-
private static MAX_NODES;
|
|
16
15
|
private options;
|
|
17
16
|
private parent;
|
|
18
17
|
private container;
|
|
@@ -35,7 +34,6 @@ declare class Renderer extends EventEmitter<RendererEvents> {
|
|
|
35
34
|
private initEvents;
|
|
36
35
|
private onContainerResize;
|
|
37
36
|
private initDrag;
|
|
38
|
-
private getHeight;
|
|
39
37
|
private initHtml;
|
|
40
38
|
/** Wavesurfer itself calls this method. Do not call it manually. */
|
|
41
39
|
setOptions(options: WaveSurferOptions): void;
|
|
@@ -46,6 +44,7 @@ declare class Renderer extends EventEmitter<RendererEvents> {
|
|
|
46
44
|
setScrollPercentage(percent: number): void;
|
|
47
45
|
destroy(): void;
|
|
48
46
|
private createDelay;
|
|
47
|
+
private getHeight;
|
|
49
48
|
private convertColorValues;
|
|
50
49
|
private getPixelRatio;
|
|
51
50
|
private renderBarWaveform;
|
package/dist/renderer.js
CHANGED
|
@@ -20,6 +20,7 @@ var __rest = (this && this.__rest) || function (s, e) {
|
|
|
20
20
|
};
|
|
21
21
|
import { makeDraggable } from './draggable.js';
|
|
22
22
|
import EventEmitter from './event-emitter.js';
|
|
23
|
+
import * as utils from './renderer-utils.js';
|
|
23
24
|
class Renderer extends EventEmitter {
|
|
24
25
|
constructor(options, audioElement) {
|
|
25
26
|
super();
|
|
@@ -63,22 +64,16 @@ class Renderer extends EventEmitter {
|
|
|
63
64
|
return parent;
|
|
64
65
|
}
|
|
65
66
|
initEvents() {
|
|
66
|
-
const getClickPosition = (e) => {
|
|
67
|
-
const rect = this.wrapper.getBoundingClientRect();
|
|
68
|
-
const x = e.clientX - rect.left;
|
|
69
|
-
const y = e.clientY - rect.top;
|
|
70
|
-
const relativeX = x / rect.width;
|
|
71
|
-
const relativeY = y / rect.height;
|
|
72
|
-
return [relativeX, relativeY];
|
|
73
|
-
};
|
|
74
67
|
// Add a click listener
|
|
75
68
|
this.wrapper.addEventListener('click', (e) => {
|
|
76
|
-
const
|
|
69
|
+
const rect = this.wrapper.getBoundingClientRect();
|
|
70
|
+
const [x, y] = utils.getRelativePointerPosition(rect, e.clientX, e.clientY);
|
|
77
71
|
this.emit('click', x, y);
|
|
78
72
|
});
|
|
79
73
|
// Add a double click listener
|
|
80
74
|
this.wrapper.addEventListener('dblclick', (e) => {
|
|
81
|
-
const
|
|
75
|
+
const rect = this.wrapper.getBoundingClientRect();
|
|
76
|
+
const [x, y] = utils.getRelativePointerPosition(rect, e.clientX, e.clientY);
|
|
82
77
|
this.emit('dblclick', x, y);
|
|
83
78
|
});
|
|
84
79
|
// Drag
|
|
@@ -88,8 +83,11 @@ class Renderer extends EventEmitter {
|
|
|
88
83
|
// Add a scroll listener
|
|
89
84
|
this.scrollContainer.addEventListener('scroll', () => {
|
|
90
85
|
const { scrollLeft, scrollWidth, clientWidth } = this.scrollContainer;
|
|
91
|
-
const startX
|
|
92
|
-
|
|
86
|
+
const { startX, endX } = utils.calculateScrollPercentages({
|
|
87
|
+
scrollLeft,
|
|
88
|
+
scrollWidth,
|
|
89
|
+
clientWidth,
|
|
90
|
+
});
|
|
93
91
|
this.emit('scroll', startX, endX, scrollLeft, scrollLeft + clientWidth);
|
|
94
92
|
});
|
|
95
93
|
// Re-render the waveform on container resize
|
|
@@ -109,6 +107,7 @@ class Renderer extends EventEmitter {
|
|
|
109
107
|
return;
|
|
110
108
|
this.lastContainerWidth = width;
|
|
111
109
|
this.reRender();
|
|
110
|
+
this.emit('resize');
|
|
112
111
|
}
|
|
113
112
|
initDrag() {
|
|
114
113
|
// Don't initialize drag if it's already set up
|
|
@@ -117,36 +116,23 @@ class Renderer extends EventEmitter {
|
|
|
117
116
|
this.dragUnsubscribe = makeDraggable(this.wrapper,
|
|
118
117
|
// On drag
|
|
119
118
|
(_, __, x) => {
|
|
120
|
-
|
|
119
|
+
const width = this.wrapper.getBoundingClientRect().width;
|
|
120
|
+
this.emit('drag', utils.clampToUnit(x / width));
|
|
121
121
|
},
|
|
122
122
|
// On start drag
|
|
123
123
|
(x) => {
|
|
124
124
|
this.isDragging = true;
|
|
125
|
-
|
|
125
|
+
const width = this.wrapper.getBoundingClientRect().width;
|
|
126
|
+
this.emit('dragstart', utils.clampToUnit(x / width));
|
|
126
127
|
},
|
|
127
128
|
// On end drag
|
|
128
129
|
(x) => {
|
|
129
130
|
this.isDragging = false;
|
|
130
|
-
|
|
131
|
+
const width = this.wrapper.getBoundingClientRect().width;
|
|
132
|
+
this.emit('dragend', utils.clampToUnit(x / width));
|
|
131
133
|
});
|
|
132
134
|
this.subscriptions.push(this.dragUnsubscribe);
|
|
133
135
|
}
|
|
134
|
-
getHeight(optionsHeight, optionsSplitChannel) {
|
|
135
|
-
var _a;
|
|
136
|
-
const defaultHeight = 128;
|
|
137
|
-
const numberOfChannels = ((_a = this.audioData) === null || _a === void 0 ? void 0 : _a.numberOfChannels) || 1;
|
|
138
|
-
if (optionsHeight == null)
|
|
139
|
-
return defaultHeight;
|
|
140
|
-
if (!isNaN(Number(optionsHeight)))
|
|
141
|
-
return Number(optionsHeight);
|
|
142
|
-
if (optionsHeight === 'auto') {
|
|
143
|
-
const height = this.parent.clientHeight || defaultHeight;
|
|
144
|
-
if (optionsSplitChannel === null || optionsSplitChannel === void 0 ? void 0 : optionsSplitChannel.every((channel) => !channel.overlay))
|
|
145
|
-
return height / numberOfChannels;
|
|
146
|
-
return height;
|
|
147
|
-
}
|
|
148
|
-
return defaultHeight;
|
|
149
|
-
}
|
|
150
136
|
initHtml() {
|
|
151
137
|
const div = document.createElement('div');
|
|
152
138
|
const shadow = div.attachShadow({ mode: 'open' });
|
|
@@ -182,6 +168,7 @@ class Renderer extends EventEmitter {
|
|
|
182
168
|
}
|
|
183
169
|
:host .canvases {
|
|
184
170
|
min-height: ${this.getHeight(this.options.height, this.options.splitChannels)}px;
|
|
171
|
+
pointer-events: none;
|
|
185
172
|
}
|
|
186
173
|
:host .canvases > div {
|
|
187
174
|
position: relative;
|
|
@@ -297,123 +284,86 @@ class Renderer extends EventEmitter {
|
|
|
297
284
|
});
|
|
298
285
|
};
|
|
299
286
|
}
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
const ctx = canvasElement.getContext('2d');
|
|
310
|
-
const gradientHeight = canvasElement.height * (window.devicePixelRatio || 1);
|
|
311
|
-
const gradient = ctx.createLinearGradient(0, 0, 0, gradientHeight);
|
|
312
|
-
const colorStopPercentage = 1 / (color.length - 1);
|
|
313
|
-
color.forEach((color, index) => {
|
|
314
|
-
const offset = index * colorStopPercentage;
|
|
315
|
-
gradient.addColorStop(offset, color);
|
|
287
|
+
getHeight(optionsHeight, optionsSplitChannel) {
|
|
288
|
+
var _a;
|
|
289
|
+
const numberOfChannels = ((_a = this.audioData) === null || _a === void 0 ? void 0 : _a.numberOfChannels) || 1;
|
|
290
|
+
return utils.resolveChannelHeight({
|
|
291
|
+
optionsHeight,
|
|
292
|
+
optionsSplitChannels: optionsSplitChannel,
|
|
293
|
+
parentHeight: this.parent.clientHeight,
|
|
294
|
+
numberOfChannels,
|
|
295
|
+
defaultHeight: utils.DEFAULT_HEIGHT,
|
|
316
296
|
});
|
|
317
|
-
|
|
297
|
+
}
|
|
298
|
+
convertColorValues(color) {
|
|
299
|
+
return utils.resolveColorValue(color, this.getPixelRatio());
|
|
318
300
|
}
|
|
319
301
|
getPixelRatio() {
|
|
320
|
-
return
|
|
302
|
+
return utils.getPixelRatio(window.devicePixelRatio);
|
|
321
303
|
}
|
|
322
304
|
renderBarWaveform(channelData, options, ctx, vScale) {
|
|
323
|
-
const topChannel = channelData[0];
|
|
324
|
-
const bottomChannel = channelData[1] || channelData[0];
|
|
325
|
-
const length = topChannel.length;
|
|
326
305
|
const { width, height } = ctx.canvas;
|
|
327
|
-
const halfHeight
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
306
|
+
const { halfHeight, barWidth, barRadius, barIndexScale, barSpacing } = utils.calculateBarRenderConfig({
|
|
307
|
+
width,
|
|
308
|
+
height,
|
|
309
|
+
length: (channelData[0] || []).length,
|
|
310
|
+
options,
|
|
311
|
+
pixelRatio: this.getPixelRatio(),
|
|
312
|
+
});
|
|
313
|
+
const segments = utils.calculateBarSegments({
|
|
314
|
+
channelData,
|
|
315
|
+
barIndexScale,
|
|
316
|
+
barSpacing,
|
|
317
|
+
barWidth,
|
|
318
|
+
halfHeight,
|
|
319
|
+
vScale,
|
|
320
|
+
canvasHeight: height,
|
|
321
|
+
barAlign: options.barAlign,
|
|
322
|
+
});
|
|
334
323
|
ctx.beginPath();
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
const bottomBarHeight = Math.round(maxBottom * halfHeight * vScale);
|
|
343
|
-
const barHeight = topBarHeight + bottomBarHeight || 1;
|
|
344
|
-
// Vertical alignment
|
|
345
|
-
let y = halfHeight - topBarHeight;
|
|
346
|
-
if (options.barAlign === 'top') {
|
|
347
|
-
y = 0;
|
|
348
|
-
}
|
|
349
|
-
else if (options.barAlign === 'bottom') {
|
|
350
|
-
y = height - barHeight;
|
|
351
|
-
}
|
|
352
|
-
ctx[rectFn](prevX * (barWidth + barGap), y, barWidth, barHeight, barRadius);
|
|
353
|
-
prevX = x;
|
|
354
|
-
maxTop = 0;
|
|
355
|
-
maxBottom = 0;
|
|
324
|
+
for (const segment of segments) {
|
|
325
|
+
if (barRadius && 'roundRect' in ctx) {
|
|
326
|
+
;
|
|
327
|
+
ctx.roundRect(segment.x, segment.y, segment.width, segment.height, barRadius);
|
|
328
|
+
}
|
|
329
|
+
else {
|
|
330
|
+
ctx.rect(segment.x, segment.y, segment.width, segment.height);
|
|
356
331
|
}
|
|
357
|
-
const magnitudeTop = Math.abs(topChannel[i] || 0);
|
|
358
|
-
const magnitudeBottom = Math.abs(bottomChannel[i] || 0);
|
|
359
|
-
if (magnitudeTop > maxTop)
|
|
360
|
-
maxTop = magnitudeTop;
|
|
361
|
-
if (magnitudeBottom > maxBottom)
|
|
362
|
-
maxBottom = magnitudeBottom;
|
|
363
332
|
}
|
|
364
333
|
ctx.fill();
|
|
365
334
|
ctx.closePath();
|
|
366
335
|
}
|
|
367
336
|
renderLineWaveform(channelData, _options, ctx, vScale) {
|
|
368
|
-
const
|
|
369
|
-
|
|
370
|
-
const length = channel.length;
|
|
371
|
-
const { height } = ctx.canvas;
|
|
372
|
-
const halfHeight = height / 2;
|
|
373
|
-
const hScale = ctx.canvas.width / length;
|
|
374
|
-
ctx.moveTo(0, halfHeight);
|
|
375
|
-
let prevX = 0;
|
|
376
|
-
let max = 0;
|
|
377
|
-
for (let i = 0; i <= length; i++) {
|
|
378
|
-
const x = Math.round(i * hScale);
|
|
379
|
-
if (x > prevX) {
|
|
380
|
-
const h = Math.round(max * halfHeight * vScale) || 1;
|
|
381
|
-
const y = halfHeight + h * (index === 0 ? -1 : 1);
|
|
382
|
-
ctx.lineTo(prevX, y);
|
|
383
|
-
prevX = x;
|
|
384
|
-
max = 0;
|
|
385
|
-
}
|
|
386
|
-
const value = Math.abs(channel[i] || 0);
|
|
387
|
-
if (value > max)
|
|
388
|
-
max = value;
|
|
389
|
-
}
|
|
390
|
-
ctx.lineTo(prevX, halfHeight);
|
|
391
|
-
};
|
|
337
|
+
const { width, height } = ctx.canvas;
|
|
338
|
+
const paths = utils.calculateLinePaths({ channelData, width, height, vScale });
|
|
392
339
|
ctx.beginPath();
|
|
393
|
-
|
|
394
|
-
|
|
340
|
+
for (const path of paths) {
|
|
341
|
+
if (!path.length)
|
|
342
|
+
continue;
|
|
343
|
+
ctx.moveTo(path[0].x, path[0].y);
|
|
344
|
+
for (let i = 1; i < path.length; i++) {
|
|
345
|
+
const point = path[i];
|
|
346
|
+
ctx.lineTo(point.x, point.y);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
395
349
|
ctx.fill();
|
|
396
350
|
ctx.closePath();
|
|
397
351
|
}
|
|
398
352
|
renderWaveform(channelData, options, ctx) {
|
|
399
353
|
ctx.fillStyle = this.convertColorValues(options.waveColor);
|
|
400
|
-
// Custom rendering function
|
|
401
354
|
if (options.renderFunction) {
|
|
402
355
|
options.renderFunction(channelData, ctx);
|
|
403
356
|
return;
|
|
404
357
|
}
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
// Render waveform as bars
|
|
412
|
-
if (options.barWidth || options.barGap || options.barAlign) {
|
|
358
|
+
const vScale = utils.calculateVerticalScale({
|
|
359
|
+
channelData,
|
|
360
|
+
barHeight: options.barHeight,
|
|
361
|
+
normalize: options.normalize,
|
|
362
|
+
});
|
|
363
|
+
if (utils.shouldRenderBars(options)) {
|
|
413
364
|
this.renderBarWaveform(channelData, options, ctx, vScale);
|
|
414
365
|
return;
|
|
415
366
|
}
|
|
416
|
-
// Render waveform as a polyline
|
|
417
367
|
this.renderLineWaveform(channelData, options, ctx, vScale);
|
|
418
368
|
}
|
|
419
369
|
renderSingleCanvas(data, options, width, height, offset, canvasContainer, progressContainer) {
|
|
@@ -426,7 +376,13 @@ class Renderer extends EventEmitter {
|
|
|
426
376
|
canvas.style.left = `${Math.round(offset)}px`;
|
|
427
377
|
canvasContainer.appendChild(canvas);
|
|
428
378
|
const ctx = canvas.getContext('2d');
|
|
429
|
-
|
|
379
|
+
if (options.renderFunction) {
|
|
380
|
+
ctx.fillStyle = this.convertColorValues(options.waveColor);
|
|
381
|
+
options.renderFunction(data, ctx);
|
|
382
|
+
}
|
|
383
|
+
else {
|
|
384
|
+
this.renderWaveform(data, options, ctx);
|
|
385
|
+
}
|
|
430
386
|
// Draw a progress canvas
|
|
431
387
|
if (canvas.width > 0 && canvas.height > 0) {
|
|
432
388
|
const progressCanvas = canvas.cloneNode();
|
|
@@ -444,17 +400,8 @@ class Renderer extends EventEmitter {
|
|
|
444
400
|
const pixelRatio = this.getPixelRatio();
|
|
445
401
|
const { clientWidth } = this.scrollContainer;
|
|
446
402
|
const totalWidth = width / pixelRatio;
|
|
447
|
-
|
|
403
|
+
const singleCanvasWidth = utils.calculateSingleCanvasWidth({ clientWidth, totalWidth, options });
|
|
448
404
|
let drawnIndexes = {};
|
|
449
|
-
// Adjust width to avoid gaps between canvases when using bars
|
|
450
|
-
if (options.barWidth || options.barGap) {
|
|
451
|
-
const barWidth = options.barWidth || 0.5;
|
|
452
|
-
const barGap = options.barGap || barWidth / 2;
|
|
453
|
-
const totalBarWidth = barWidth + barGap;
|
|
454
|
-
if (singleCanvasWidth % totalBarWidth !== 0) {
|
|
455
|
-
singleCanvasWidth = Math.floor(singleCanvasWidth / totalBarWidth) * totalBarWidth;
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
405
|
// Nothing to render
|
|
459
406
|
if (singleCanvasWidth === 0)
|
|
460
407
|
return;
|
|
@@ -468,24 +415,15 @@ class Renderer extends EventEmitter {
|
|
|
468
415
|
const offset = index * singleCanvasWidth;
|
|
469
416
|
let clampedWidth = Math.min(totalWidth - offset, singleCanvasWidth);
|
|
470
417
|
// Clamp the width to the bar grid to avoid empty canvases at the end
|
|
471
|
-
|
|
472
|
-
const barWidth = options.barWidth || 0.5;
|
|
473
|
-
const barGap = options.barGap || barWidth / 2;
|
|
474
|
-
const totalBarWidth = barWidth + barGap;
|
|
475
|
-
clampedWidth = Math.floor(clampedWidth / totalBarWidth) * totalBarWidth;
|
|
476
|
-
}
|
|
418
|
+
clampedWidth = utils.clampWidthToBarGrid(clampedWidth, options);
|
|
477
419
|
if (clampedWidth <= 0)
|
|
478
420
|
return;
|
|
479
|
-
const data =
|
|
480
|
-
const start = Math.floor((offset / totalWidth) * channel.length);
|
|
481
|
-
const end = Math.floor(((offset + clampedWidth) / totalWidth) * channel.length);
|
|
482
|
-
return channel.slice(start, end);
|
|
483
|
-
});
|
|
421
|
+
const data = utils.sliceChannelData({ channelData, offset, clampedWidth, totalWidth });
|
|
484
422
|
this.renderSingleCanvas(data, options, clampedWidth, height, offset, canvasContainer, progressContainer);
|
|
485
423
|
};
|
|
486
424
|
// Clear canvases to avoid too many DOM nodes
|
|
487
425
|
const clearCanvases = () => {
|
|
488
|
-
if (Object.keys(drawnIndexes).length
|
|
426
|
+
if (utils.shouldClearCanvases(Object.keys(drawnIndexes).length)) {
|
|
489
427
|
canvasContainer.innerHTML = '';
|
|
490
428
|
progressContainer.innerHTML = '';
|
|
491
429
|
drawnIndexes = {};
|
|
@@ -501,21 +439,18 @@ class Renderer extends EventEmitter {
|
|
|
501
439
|
return;
|
|
502
440
|
}
|
|
503
441
|
// Lazy rendering
|
|
504
|
-
const
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
442
|
+
const initialRange = utils.getLazyRenderRange({
|
|
443
|
+
scrollLeft: this.scrollContainer.scrollLeft,
|
|
444
|
+
totalWidth,
|
|
445
|
+
numCanvases,
|
|
446
|
+
});
|
|
447
|
+
initialRange.forEach((index) => draw(index));
|
|
510
448
|
// Subscribe to the scroll event to draw additional canvases
|
|
511
449
|
if (numCanvases > 1) {
|
|
512
450
|
const unsubscribe = this.on('scroll', () => {
|
|
513
451
|
const { scrollLeft } = this.scrollContainer;
|
|
514
|
-
const canvasIndex = Math.floor((scrollLeft / totalWidth) * numCanvases);
|
|
515
452
|
clearCanvases();
|
|
516
|
-
|
|
517
|
-
draw(canvasIndex);
|
|
518
|
-
draw(canvasIndex + 1);
|
|
453
|
+
utils.getLazyRenderRange({ scrollLeft, totalWidth, numCanvases }).forEach((index) => draw(index));
|
|
519
454
|
});
|
|
520
455
|
this.unsubscribeOnScroll.push(unsubscribe);
|
|
521
456
|
}
|
|
@@ -554,12 +489,15 @@ class Renderer extends EventEmitter {
|
|
|
554
489
|
// Determine the width of the waveform
|
|
555
490
|
const pixelRatio = this.getPixelRatio();
|
|
556
491
|
const parentWidth = this.scrollContainer.clientWidth;
|
|
557
|
-
const scrollWidth
|
|
492
|
+
const { scrollWidth, isScrollable, useParentWidth, width } = utils.calculateWaveformLayout({
|
|
493
|
+
duration: audioData.duration,
|
|
494
|
+
minPxPerSec: this.options.minPxPerSec || 0,
|
|
495
|
+
parentWidth,
|
|
496
|
+
fillParent: this.options.fillParent,
|
|
497
|
+
pixelRatio,
|
|
498
|
+
});
|
|
558
499
|
// Whether the container should scroll
|
|
559
|
-
this.isScrollable =
|
|
560
|
-
const useParentWidth = this.options.fillParent && !this.isScrollable;
|
|
561
|
-
// Width of the waveform in pixels
|
|
562
|
-
const width = (useParentWidth ? parentWidth : scrollWidth) * pixelRatio;
|
|
500
|
+
this.isScrollable = isScrollable;
|
|
563
501
|
// Set the width of the wrapper
|
|
564
502
|
this.wrapper.style.width = useParentWidth ? '100%' : `${scrollWidth}px`;
|
|
565
503
|
// Set additional styles
|
|
@@ -602,12 +540,7 @@ class Renderer extends EventEmitter {
|
|
|
602
540
|
// Adjust the scroll position so that the cursor stays in the same place
|
|
603
541
|
if (this.isScrollable && scrollWidth !== this.scrollContainer.scrollWidth) {
|
|
604
542
|
const { right: after } = this.progressWrapper.getBoundingClientRect();
|
|
605
|
-
|
|
606
|
-
// to limit compounding floating-point drift
|
|
607
|
-
// we need to round to the half px furthest from 0
|
|
608
|
-
delta *= 2;
|
|
609
|
-
delta = delta < 0 ? Math.floor(delta) : Math.ceil(delta);
|
|
610
|
-
delta /= 2;
|
|
543
|
+
const delta = utils.roundToHalfAwayFromZero(after - before);
|
|
611
544
|
this.scrollContainer.scrollLeft += delta;
|
|
612
545
|
}
|
|
613
546
|
}
|
|
@@ -638,14 +571,17 @@ class Renderer extends EventEmitter {
|
|
|
638
571
|
// Keep the cursor centered when playing
|
|
639
572
|
const center = progressWidth - scrollLeft - middle;
|
|
640
573
|
if (isPlaying && this.options.autoCenter && center > 0) {
|
|
641
|
-
this.scrollContainer.scrollLeft +=
|
|
574
|
+
this.scrollContainer.scrollLeft += center;
|
|
642
575
|
}
|
|
643
576
|
}
|
|
644
577
|
// Emit the scroll event
|
|
645
578
|
{
|
|
646
579
|
const newScroll = this.scrollContainer.scrollLeft;
|
|
647
|
-
const startX
|
|
648
|
-
|
|
580
|
+
const { startX, endX } = utils.calculateScrollPercentages({
|
|
581
|
+
scrollLeft: newScroll,
|
|
582
|
+
scrollWidth,
|
|
583
|
+
clientWidth,
|
|
584
|
+
});
|
|
649
585
|
this.emit('scroll', startX, endX, newScroll, newScroll + clientWidth);
|
|
650
586
|
}
|
|
651
587
|
}
|
|
@@ -690,6 +626,4 @@ class Renderer extends EventEmitter {
|
|
|
690
626
|
});
|
|
691
627
|
}
|
|
692
628
|
}
|
|
693
|
-
Renderer.MAX_CANVAS_WIDTH = 8000;
|
|
694
|
-
Renderer.MAX_NODES = 10;
|
|
695
629
|
export default Renderer;
|
package/dist/types.d.ts
CHANGED
|
@@ -243,6 +243,8 @@ type WaveSurferEvents = {
|
|
|
243
243
|
destroy: [];
|
|
244
244
|
/** When source file is unable to be fetched, decoded, or an error is thrown by media element */
|
|
245
245
|
error: [error: Error];
|
|
246
|
+
/** When audio container resizing */
|
|
247
|
+
resize: [];
|
|
246
248
|
};
|
|
247
249
|
declare class WaveSurfer extends Player<WaveSurferEvents> {
|
|
248
250
|
options: WaveSurferOptions & typeof defaultOptions;
|
package/dist/wavesurfer.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";function t(t,e,i,s){return new(i||(i=Promise))((function(n,r){function o(t){try{h(s.next(t))}catch(t){r(t)}}function a(t){try{h(s.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}h((s=s.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class e{constructor(){this.listeners={}}on(t,e,i){if(this.listeners[t]||(this.listeners[t]=new Set),null==i?void 0:i.once){const i=(...s)=>{this.un(t,i),e(...s)};return this.listeners[t].add(i),()=>this.un(t,i)}return this.listeners[t].add(e),()=>this.un(t,e)}un(t,e){var i;null===(i=this.listeners[t])||void 0===i||i.delete(e)}once(t,e){return this.on(t,e,{once:!0})}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}}const i={decode:function(e,i){return t(this,void 0,void 0,(function*(){const t=new AudioContext({sampleRate:i});try{return yield t.decodeAudioData(e)}finally{t.close()}}))},createBuffer:function(t,e){if(!t||0===t.length)throw new Error("channelData must be a non-empty array");if(e<=0)throw new Error("duration must be greater than 0");if("number"==typeof t[0]&&(t=[t]),!t[0]||0===t[0].length)throw new Error("channelData must contain non-empty channel arrays");return function(t){const e=t[0];if(e.some((t=>t>1||t<-1))){const i=e.length;let s=0;for(let t=0;t<i;t++){const i=Math.abs(e[t]);i>s&&(s=i)}for(const e of t)for(let t=0;t<i;t++)e[t]/=s}}(t),{duration:e,length:t[0].length,sampleRate:t[0].length/e,numberOfChannels:t.length,getChannelData:e=>null==t?void 0:t[e],copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}};function s(t,e){const i=e.xmlns?document.createElementNS(e.xmlns,t):document.createElement(t);for(const[t,n]of Object.entries(e))if("children"===t&&n)for(const[t,e]of Object.entries(n))e instanceof Node?i.appendChild(e):"string"==typeof e?i.appendChild(document.createTextNode(e)):i.appendChild(s(t,e));else"style"===t?Object.assign(i.style,n):"textContent"===t?i.textContent=n:i.setAttribute(t,n.toString());return i}function n(t,e,i){const n=s(t,e||{});return null==i||i.appendChild(n),n}var r=Object.freeze({__proto__:null,createElement:n,default:n});const o={fetchBlob:function(e,i,s){return t(this,void 0,void 0,(function*(){const n=yield fetch(e,s);if(n.status>=400)throw new Error(`Failed to fetch ${e}: ${n.status} (${n.statusText})`);return function(e,i){t(this,void 0,void 0,(function*(){if(!e.body||!e.headers)return;const s=e.body.getReader(),n=Number(e.headers.get("Content-Length"))||0;let r=0,o=0;const a=e=>t(this,void 0,void 0,(function*(){r+=(null==e?void 0:e.length)||0;const t=Math.round(r/n*100);i(t)})),h=()=>t(this,void 0,void 0,(function*(){if(o++>1e5)return void console.error("Fetcher: Maximum iterations reached, stopping read loop");let t;try{t=yield s.read()}catch(t){return}t.done||(a(t.value),yield h())}));h()}))}(n.clone(),i),n.blob()}))}};class a extends e{constructor(t){super(),this.isExternalMedia=!1,t.media?(this.media=t.media,this.isExternalMedia=!0):this.media=document.createElement("audio"),t.mediaControls&&(this.media.controls=!0),t.autoplay&&(this.media.autoplay=!0),null!=t.playbackRate&&this.onMediaEvent("canplay",(()=>{null!=t.playbackRate&&(this.media.playbackRate=t.playbackRate)}),{once:!0})}onMediaEvent(t,e,i){return this.media.addEventListener(t,e,i),()=>this.media.removeEventListener(t,e,i)}getSrc(){return this.media.currentSrc||this.media.src||""}revokeSrc(){const t=this.getSrc();t.startsWith("blob:")&&URL.revokeObjectURL(t)}canPlayType(t){return""!==this.media.canPlayType(t)}setSrc(t,e){const i=this.getSrc();if(t&&i===t)return;this.revokeSrc();const s=e instanceof Blob&&(this.canPlayType(e.type)||!t)?URL.createObjectURL(e):t;if(i&&this.media.removeAttribute("src"),s||t)try{this.media.src=s}catch(e){this.media.src=t}}destroy(){this.isExternalMedia||(this.media.pause(),this.revokeSrc(),this.media.removeAttribute("src"),this.media.load(),this.media.remove())}setMediaElement(t){this.media=t}play(){return t(this,void 0,void 0,(function*(){try{return yield this.media.play()}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)return;throw t}}))}pause(){this.media.pause()}isPlaying(){return!this.media.paused&&!this.media.ended}setTime(t){this.media.currentTime=Math.max(0,Math.min(t,this.getDuration()))}getDuration(){return this.media.duration}getCurrentTime(){return this.media.currentTime}getVolume(){return this.media.volume}setVolume(t){this.media.volume=t}getMuted(){return this.media.muted}setMuted(t){this.media.muted=t}getPlaybackRate(){return this.media.playbackRate}isSeeking(){return this.media.seeking}setPlaybackRate(t,e){null!=e&&(this.media.preservesPitch=e),this.media.playbackRate=t}getMediaElement(){return this.media}setSinkId(t){return this.media.setSinkId(t)}}class h extends e{constructor(t,e){super(),this.timeouts=[],this.isScrollable=!1,this.audioData=null,this.resizeObserver=null,this.lastContainerWidth=0,this.isDragging=!1,this.subscriptions=[],this.unsubscribeOnScroll=[],this.dragUnsubscribe=null,this.subscriptions=[],this.options=t;const i=this.parentFromOptionsContainer(t.container);this.parent=i;const[s,n]=this.initHtml();i.appendChild(s),this.container=s,this.scrollContainer=n.querySelector(".scroll"),this.wrapper=n.querySelector(".wrapper"),this.canvasWrapper=n.querySelector(".canvases"),this.progressWrapper=n.querySelector(".progress"),this.cursor=n.querySelector(".cursor"),e&&n.appendChild(e),this.initEvents()}parentFromOptionsContainer(t){let e;if("string"==typeof t?e=document.querySelector(t):t instanceof HTMLElement&&(e=t),!e)throw new Error("Container not found");return e}initEvents(){const t=t=>{const e=this.wrapper.getBoundingClientRect(),i=t.clientX-e.left,s=t.clientY-e.top;return[i/e.width,s/e.height]};if(this.wrapper.addEventListener("click",(e=>{const[i,s]=t(e);this.emit("click",i,s)})),this.wrapper.addEventListener("dblclick",(e=>{const[i,s]=t(e);this.emit("dblclick",i,s)})),!0!==this.options.dragToSeek&&"object"!=typeof this.options.dragToSeek||this.initDrag(),this.scrollContainer.addEventListener("scroll",(()=>{const{scrollLeft:t,scrollWidth:e,clientWidth:i}=this.scrollContainer,s=t/e,n=(t+i)/e;this.emit("scroll",s,n,t,t+i)})),"function"==typeof ResizeObserver){const t=this.createDelay(100);this.resizeObserver=new ResizeObserver((()=>{t().then((()=>this.onContainerResize())).catch((()=>{}))})),this.resizeObserver.observe(this.scrollContainer)}}onContainerResize(){const t=this.parent.clientWidth;t===this.lastContainerWidth&&"auto"!==this.options.height||(this.lastContainerWidth=t,this.reRender())}initDrag(){this.dragUnsubscribe||(this.dragUnsubscribe=function(t,e,i,s,n=3,r=0,o=100){if(!t)return()=>{};const a=matchMedia("(pointer: coarse)").matches;let h=()=>{};const l=l=>{if(l.button!==r)return;l.preventDefault(),l.stopPropagation();let d=l.clientX,c=l.clientY,u=!1;const p=Date.now(),m=s=>{if(s.preventDefault(),s.stopPropagation(),a&&Date.now()-p<o)return;const r=s.clientX,h=s.clientY,l=r-d,m=h-c;if(u||Math.abs(l)>n||Math.abs(m)>n){const s=t.getBoundingClientRect(),{left:n,top:o}=s;u||(null==i||i(d-n,c-o),u=!0),e(l,m,r-n,h-o),d=r,c=h}},f=e=>{if(u){const i=e.clientX,n=e.clientY,r=t.getBoundingClientRect(),{left:o,top:a}=r;null==s||s(i-o,n-a)}h()},g=t=>{t.relatedTarget&&t.relatedTarget!==document.documentElement||f(t)},v=t=>{u&&(t.stopPropagation(),t.preventDefault())},b=t=>{u&&t.preventDefault()};document.addEventListener("pointermove",m),document.addEventListener("pointerup",f),document.addEventListener("pointerout",g),document.addEventListener("pointercancel",g),document.addEventListener("touchmove",b,{passive:!1}),document.addEventListener("click",v,{capture:!0}),h=()=>{document.removeEventListener("pointermove",m),document.removeEventListener("pointerup",f),document.removeEventListener("pointerout",g),document.removeEventListener("pointercancel",g),document.removeEventListener("touchmove",b),setTimeout((()=>{document.removeEventListener("click",v,{capture:!0})}),10)}};return t.addEventListener("pointerdown",l),()=>{h(),t.removeEventListener("pointerdown",l)}}(this.wrapper,((t,e,i)=>{this.emit("drag",Math.max(0,Math.min(1,i/this.wrapper.getBoundingClientRect().width)))}),(t=>{this.isDragging=!0,this.emit("dragstart",Math.max(0,Math.min(1,t/this.wrapper.getBoundingClientRect().width)))}),(t=>{this.isDragging=!1,this.emit("dragend",Math.max(0,Math.min(1,t/this.wrapper.getBoundingClientRect().width)))})),this.subscriptions.push(this.dragUnsubscribe))}getHeight(t,e){var i;const s=(null===(i=this.audioData)||void 0===i?void 0:i.numberOfChannels)||1;if(null==t)return 128;if(!isNaN(Number(t)))return Number(t);if("auto"===t){const t=this.parent.clientHeight||128;return(null==e?void 0:e.every((t=>!t.overlay)))?t/s:t}return 128}initHtml(){const t=document.createElement("div"),e=t.attachShadow({mode:"open"}),i=this.options.cspNonce&&"string"==typeof this.options.cspNonce?this.options.cspNonce.replace(/"/g,""):"";return e.innerHTML=`\n <style${i?` nonce="${i}"`:""}>\n :host {\n user-select: none;\n min-width: 1px;\n }\n :host audio {\n display: block;\n width: 100%;\n }\n :host .scroll {\n overflow-x: auto;\n overflow-y: hidden;\n width: 100%;\n position: relative;\n }\n :host .noScrollbar {\n scrollbar-color: transparent;\n scrollbar-width: none;\n }\n :host .noScrollbar::-webkit-scrollbar {\n display: none;\n -webkit-appearance: none;\n }\n :host .wrapper {\n position: relative;\n overflow: visible;\n z-index: 2;\n }\n :host .canvases {\n min-height: ${this.getHeight(this.options.height,this.options.splitChannels)}px;\n }\n :host .canvases > div {\n position: relative;\n }\n :host canvas {\n display: block;\n position: absolute;\n top: 0;\n image-rendering: pixelated;\n }\n :host .progress {\n pointer-events: none;\n position: absolute;\n z-index: 2;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n overflow: hidden;\n }\n :host .progress > div {\n position: relative;\n }\n :host .cursor {\n pointer-events: none;\n position: absolute;\n z-index: 5;\n top: 0;\n left: 0;\n height: 100%;\n border-radius: 2px;\n }\n </style>\n\n <div class="scroll" part="scroll">\n <div class="wrapper" part="wrapper">\n <div class="canvases" part="canvases"></div>\n <div class="progress" part="progress"></div>\n <div class="cursor" part="cursor"></div>\n </div>\n </div>\n `,[t,e]}setOptions(t){if(this.options.container!==t.container){const e=this.parentFromOptionsContainer(t.container);e.appendChild(this.container),this.parent=e}!0!==t.dragToSeek&&"object"!=typeof this.options.dragToSeek||this.initDrag(),this.options=t,this.reRender()}getWrapper(){return this.wrapper}getWidth(){return this.scrollContainer.clientWidth}getScroll(){return this.scrollContainer.scrollLeft}setScroll(t){this.scrollContainer.scrollLeft=t}setScrollPercentage(t){const{scrollWidth:e}=this.scrollContainer,i=e*t;this.setScroll(i)}destroy(){var t;this.subscriptions.forEach((t=>t())),this.container.remove(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),null===(t=this.unsubscribeOnScroll)||void 0===t||t.forEach((t=>t())),this.unsubscribeOnScroll=[]}createDelay(t=10){let e,i;const s=()=>{e&&(clearTimeout(e),e=void 0),i&&(i(),i=void 0)};return this.timeouts.push(s),()=>new Promise(((n,r)=>{s(),i=r,e=setTimeout((()=>{e=void 0,i=void 0,n()}),t)}))}convertColorValues(t){if(!Array.isArray(t))return t||"";if(0===t.length)return"#999";if(t.length<2)return t[0]||"";const e=document.createElement("canvas"),i=e.getContext("2d"),s=e.height*(window.devicePixelRatio||1),n=i.createLinearGradient(0,0,0,s),r=1/(t.length-1);return t.forEach(((t,e)=>{const i=e*r;n.addColorStop(i,t)})),n}getPixelRatio(){return Math.max(1,window.devicePixelRatio||1)}renderBarWaveform(t,e,i,s){const n=t[0],r=t[1]||t[0],o=n.length,{width:a,height:h}=i.canvas,l=h/2,d=this.getPixelRatio(),c=e.barWidth?e.barWidth*d:1,u=e.barGap?e.barGap*d:e.barWidth?c/2:0,p=e.barRadius||0,m=a/(c+u)/o,f=p&&"roundRect"in i?"roundRect":"rect";i.beginPath();let g=0,v=0,b=0;for(let t=0;t<=o;t++){const o=Math.round(t*m);if(o>g){const t=Math.round(v*l*s),n=t+Math.round(b*l*s)||1;let r=l-t;"top"===e.barAlign?r=0:"bottom"===e.barAlign&&(r=h-n),i[f](g*(c+u),r,c,n,p),g=o,v=0,b=0}const a=Math.abs(n[t]||0),d=Math.abs(r[t]||0);a>v&&(v=a),d>b&&(b=d)}i.fill(),i.closePath()}renderLineWaveform(t,e,i,s){const n=e=>{const n=t[e]||t[0],r=n.length,{height:o}=i.canvas,a=o/2,h=i.canvas.width/r;i.moveTo(0,a);let l=0,d=0;for(let t=0;t<=r;t++){const r=Math.round(t*h);if(r>l){const t=a+(Math.round(d*a*s)||1)*(0===e?-1:1);i.lineTo(l,t),l=r,d=0}const o=Math.abs(n[t]||0);o>d&&(d=o)}i.lineTo(l,a)};i.beginPath(),n(0),n(1),i.fill(),i.closePath()}renderWaveform(t,e,i){if(i.fillStyle=this.convertColorValues(e.waveColor),e.renderFunction)return void e.renderFunction(t,i);let s=e.barHeight||1;if(e.normalize){const e=Array.from(t[0]).reduce(((t,e)=>Math.max(t,Math.abs(e))),0);s=e?s/e:s}e.barWidth||e.barGap||e.barAlign?this.renderBarWaveform(t,e,i,s):this.renderLineWaveform(t,e,i,s)}renderSingleCanvas(t,e,i,s,n,r,o){const a=this.getPixelRatio(),h=document.createElement("canvas");h.width=Math.round(i*a),h.height=Math.round(s*a),h.style.width=`${i}px`,h.style.height=`${s}px`,h.style.left=`${Math.round(n)}px`,r.appendChild(h);const l=h.getContext("2d");if(this.renderWaveform(t,e,l),h.width>0&&h.height>0){const t=h.cloneNode(),i=t.getContext("2d");i.drawImage(h,0,0),i.globalCompositeOperation="source-in",i.fillStyle=this.convertColorValues(e.progressColor),i.fillRect(0,0,h.width,h.height),o.appendChild(t)}}renderMultiCanvas(t,e,i,s,n,r){const o=this.getPixelRatio(),{clientWidth:a}=this.scrollContainer,l=i/o;let d=Math.min(h.MAX_CANVAS_WIDTH,a,l),c={};if(e.barWidth||e.barGap){const t=e.barWidth||.5,i=t+(e.barGap||t/2);d%i!=0&&(d=Math.floor(d/i)*i)}if(0===d)return;const u=i=>{if(i<0||i>=p)return;if(c[i])return;c[i]=!0;const o=i*d;let a=Math.min(l-o,d);if(e.barWidth||e.barGap){const t=e.barWidth||.5,i=t+(e.barGap||t/2);a=Math.floor(a/i)*i}if(a<=0)return;const h=t.map((t=>{const e=Math.floor(o/l*t.length),i=Math.floor((o+a)/l*t.length);return t.slice(e,i)}));this.renderSingleCanvas(h,e,a,s,o,n,r)},p=Math.ceil(l/d);if(!this.isScrollable){for(let t=0;t<p;t++)u(t);return}const m=this.scrollContainer.scrollLeft/l,f=Math.floor(m*p);if(u(f-1),u(f),u(f+1),p>1){const t=this.on("scroll",(()=>{const{scrollLeft:t}=this.scrollContainer,e=Math.floor(t/l*p);Object.keys(c).length>h.MAX_NODES&&(n.innerHTML="",r.innerHTML="",c={}),u(e-1),u(e),u(e+1)}));this.unsubscribeOnScroll.push(t)}}renderChannel(t,e,i,s){var{overlay:n}=e,r=function(t,e){var i={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(i[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(i[s[n]]=t[s[n]])}return i}(e,["overlay"]);const o=document.createElement("div"),a=this.getHeight(r.height,r.splitChannels);o.style.height=`${a}px`,n&&s>0&&(o.style.marginTop=`-${a}px`),this.canvasWrapper.style.minHeight=`${a}px`,this.canvasWrapper.appendChild(o);const h=o.cloneNode();this.progressWrapper.appendChild(h),this.renderMultiCanvas(t,r,i,a,o,h)}render(e){return t(this,void 0,void 0,(function*(){var t;this.timeouts.forEach((t=>t())),this.timeouts=[],this.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="",null!=this.options.width&&(this.scrollContainer.style.width="number"==typeof this.options.width?`${this.options.width}px`:this.options.width);const i=this.getPixelRatio(),s=this.scrollContainer.clientWidth,n=Math.ceil(e.duration*(this.options.minPxPerSec||0));this.isScrollable=n>s;const r=this.options.fillParent&&!this.isScrollable,o=(r?s:n)*i;if(this.wrapper.style.width=r?"100%":`${n}px`,this.scrollContainer.style.overflowX=this.isScrollable?"auto":"hidden",this.scrollContainer.classList.toggle("noScrollbar",!!this.options.hideScrollbar),this.cursor.style.backgroundColor=`${this.options.cursorColor||this.options.progressColor}`,this.cursor.style.width=`${this.options.cursorWidth}px`,this.audioData=e,this.emit("render"),this.options.splitChannels)for(let i=0;i<e.numberOfChannels;i++){const s=Object.assign(Object.assign({},this.options),null===(t=this.options.splitChannels)||void 0===t?void 0:t[i]);this.renderChannel([e.getChannelData(i)],s,o,i)}else{const t=[e.getChannelData(0)];e.numberOfChannels>1&&t.push(e.getChannelData(1)),this.renderChannel(t,this.options,o,0)}Promise.resolve().then((()=>this.emit("rendered")))}))}reRender(){if(this.unsubscribeOnScroll.forEach((t=>t())),this.unsubscribeOnScroll=[],!this.audioData)return;const{scrollWidth:t}=this.scrollContainer,{right:e}=this.progressWrapper.getBoundingClientRect();if(this.render(this.audioData),this.isScrollable&&t!==this.scrollContainer.scrollWidth){const{right:t}=this.progressWrapper.getBoundingClientRect();let i=t-e;i*=2,i=i<0?Math.floor(i):Math.ceil(i),i/=2,this.scrollContainer.scrollLeft+=i}}zoom(t){this.options.minPxPerSec=t,this.reRender()}scrollIntoView(t,e=!1){const{scrollLeft:i,scrollWidth:s,clientWidth:n}=this.scrollContainer,r=t*s,o=i,a=i+n,h=n/2;if(this.isDragging){const t=30;r+t>a?this.scrollContainer.scrollLeft+=t:r-t<o&&(this.scrollContainer.scrollLeft-=t)}else{(r<o||r>a)&&(this.scrollContainer.scrollLeft=r-(this.options.autoCenter?h:0));const t=r-i-h;e&&this.options.autoCenter&&t>0&&(this.scrollContainer.scrollLeft+=Math.min(t,10))}{const t=this.scrollContainer.scrollLeft,e=t/s,i=(t+n)/s;this.emit("scroll",e,i,t,t+n)}}renderProgress(t,e){if(isNaN(t))return;const i=100*t;this.canvasWrapper.style.clipPath=`polygon(${i}% 0%, 100% 0%, 100% 100%, ${i}% 100%)`,this.progressWrapper.style.width=`${i}%`,this.cursor.style.left=`${i}%`,this.cursor.style.transform=this.options.cursorWidth?`translateX(-${t*this.options.cursorWidth}px)`:"",this.isScrollable&&this.options.autoScroll&&this.scrollIntoView(t,e)}exportImage(e,i,s){return t(this,void 0,void 0,(function*(){const t=this.canvasWrapper.querySelectorAll("canvas");if(!t.length)throw new Error("No waveform data");if("dataURL"===s){const s=Array.from(t).map((t=>t.toDataURL(e,i)));return Promise.resolve(s)}return Promise.all(Array.from(t).map((t=>new Promise(((s,n)=>{t.toBlob((t=>{t?s(t):n(new Error("Could not export image"))}),e,i)})))))}))}}h.MAX_CANVAS_WIDTH=8e3,h.MAX_NODES=10;class l extends e{constructor(){super(...arguments),this.animationFrameId=null,this.isRunning=!1}start(){if(this.isRunning)return;this.isRunning=!0;const t=()=>{this.isRunning&&(this.emit("tick"),this.animationFrameId=requestAnimationFrame(t))};t()}stop(){this.isRunning=!1,null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}destroy(){this.stop()}}class d extends e{constructor(t=new AudioContext){super(),this.bufferNode=null,this.playStartTime=0,this.playedDuration=0,this._muted=!1,this._playbackRate=1,this._duration=void 0,this.buffer=null,this.currentSrc="",this.paused=!0,this.crossOrigin=null,this.seeking=!1,this.autoplay=!1,this.addEventListener=this.on,this.removeEventListener=this.un,this.audioContext=t,this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination)}load(){return t(this,void 0,void 0,(function*(){}))}get src(){return this.currentSrc}set src(t){if(this.currentSrc=t,this._duration=void 0,!t)return this.buffer=null,void this.emit("emptied");fetch(t).then((e=>{if(e.status>=400)throw new Error(`Failed to fetch ${t}: ${e.status} (${e.statusText})`);return e.arrayBuffer()})).then((e=>this.currentSrc!==t?null:this.audioContext.decodeAudioData(e))).then((e=>{this.currentSrc===t&&(this.buffer=e,this.emit("loadedmetadata"),this.emit("canplay"),this.autoplay&&this.play())}))}_play(){if(!this.paused)return;this.paused=!1,this.bufferNode&&(this.bufferNode.onended=null,this.bufferNode.disconnect()),this.bufferNode=this.audioContext.createBufferSource(),this.buffer&&(this.bufferNode.buffer=this.buffer),this.bufferNode.playbackRate.value=this._playbackRate,this.bufferNode.connect(this.gainNode);let t=this.playedDuration*this._playbackRate;(t>=this.duration||t<0)&&(t=0,this.playedDuration=0),this.bufferNode.start(this.audioContext.currentTime,t),this.playStartTime=this.audioContext.currentTime,this.bufferNode.onended=()=>{this.currentTime>=this.duration&&(this.pause(),this.emit("ended"))}}_pause(){var t;this.paused=!0,null===(t=this.bufferNode)||void 0===t||t.stop(),this.playedDuration+=this.audioContext.currentTime-this.playStartTime}play(){return t(this,void 0,void 0,(function*(){this.paused&&(this._play(),this.emit("play"))}))}pause(){this.paused||(this._pause(),this.emit("pause"))}stopAt(t){const e=t-this.currentTime,i=this.bufferNode;null==i||i.stop(this.audioContext.currentTime+e),null==i||i.addEventListener("ended",(()=>{i===this.bufferNode&&(this.bufferNode=null,this.pause())}),{once:!0})}setSinkId(e){return t(this,void 0,void 0,(function*(){return this.audioContext.setSinkId(e)}))}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this.bufferNode&&(this.bufferNode.playbackRate.value=t)}get currentTime(){return(this.paused?this.playedDuration:this.playedDuration+(this.audioContext.currentTime-this.playStartTime))*this._playbackRate}set currentTime(t){const e=!this.paused;e&&this._pause(),this.playedDuration=t/this._playbackRate,e&&this._play(),this.emit("seeking"),this.emit("timeupdate")}get duration(){var t,e;return null!==(t=this._duration)&&void 0!==t?t:(null===(e=this.buffer)||void 0===e?void 0:e.duration)||0}set duration(t){this._duration=t}get volume(){return this.gainNode.gain.value}set volume(t){this.gainNode.gain.value=t,this.emit("volumechange")}get muted(){return this._muted}set muted(t){this._muted!==t&&(this._muted=t,this._muted?this.gainNode.disconnect():this.gainNode.connect(this.audioContext.destination))}canPlayType(t){return/^(audio|video)\//.test(t)}getGainNode(){return this.gainNode}getChannelData(){const t=[];if(!this.buffer)return t;const e=this.buffer.numberOfChannels;for(let i=0;i<e;i++)t.push(this.buffer.getChannelData(i));return t}removeAttribute(t){switch(t){case"src":this.src="";break;case"playbackRate":this.playbackRate=0;break;case"currentTime":this.currentTime=0;break;case"duration":this.duration=0;break;case"volume":this.volume=0;break;case"muted":this.muted=!1}}}const c={waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,dragToSeek:!1,autoScroll:!0,autoCenter:!0,sampleRate:8e3};class u extends a{static create(t){return new u(t)}constructor(t){const e=t.media||("WebAudio"===t.backend?new d:void 0);super({media:e,mediaControls:t.mediaControls,autoplay:t.autoplay,playbackRate:t.audioRate}),this.plugins=[],this.decodedData=null,this.stopAtPosition=null,this.subscriptions=[],this.mediaSubscriptions=[],this.abortController=null,this.options=Object.assign({},c,t),this.timer=new l;const i=e?void 0:this.getMediaElement();this.renderer=new h(this.options,i),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initPlugins();const s=this.options.url||this.getSrc()||"";Promise.resolve().then((()=>{this.emit("init");const{peaks:t,duration:e}=this.options;(s||t&&e)&&this.load(s,t,e).catch((t=>{console.error("WaveSurfer initial load error:",t)}))}))}updateProgress(t=this.getCurrentTime()){return this.renderer.renderProgress(t/this.getDuration(),this.isPlaying()),t}initTimerEvents(){this.subscriptions.push(this.timer.on("tick",(()=>{if(!this.isSeeking()){const t=this.updateProgress();this.emit("timeupdate",t),this.emit("audioprocess",t),null!=this.stopAtPosition&&this.isPlaying()&&t>=this.stopAtPosition&&this.pause()}})))}initPlayerEvents(){this.isPlaying()&&(this.emit("play"),this.timer.start()),this.mediaSubscriptions.push(this.onMediaEvent("timeupdate",(()=>{const t=this.updateProgress();this.emit("timeupdate",t)})),this.onMediaEvent("play",(()=>{this.emit("play"),this.timer.start()})),this.onMediaEvent("pause",(()=>{this.emit("pause"),this.timer.stop(),this.stopAtPosition=null})),this.onMediaEvent("emptied",(()=>{this.timer.stop(),this.stopAtPosition=null})),this.onMediaEvent("ended",(()=>{this.emit("timeupdate",this.getDuration()),this.emit("finish"),this.stopAtPosition=null})),this.onMediaEvent("seeking",(()=>{this.emit("seeking",this.getCurrentTime())})),this.onMediaEvent("error",(()=>{var t;this.emit("error",null!==(t=this.getMediaElement().error)&&void 0!==t?t:new Error("Media error")),this.stopAtPosition=null})))}initRendererEvents(){this.subscriptions.push(this.renderer.on("click",((t,e)=>{this.options.interact&&(this.seekTo(t),this.emit("interaction",t*this.getDuration()),this.emit("click",t,e))})),this.renderer.on("dblclick",((t,e)=>{this.emit("dblclick",t,e)})),this.renderer.on("scroll",((t,e,i,s)=>{const n=this.getDuration();this.emit("scroll",t*n,e*n,i,s)})),this.renderer.on("render",(()=>{this.emit("redraw")})),this.renderer.on("rendered",(()=>{this.emit("redrawcomplete")})),this.renderer.on("dragstart",(t=>{this.emit("dragstart",t)})),this.renderer.on("dragend",(t=>{this.emit("dragend",t)})));{let t;const e=this.renderer.on("drag",(e=>{if(!this.options.interact)return;let i;this.renderer.renderProgress(e),clearTimeout(t),this.isPlaying()?i=0:!0===this.options.dragToSeek?i=200:"object"==typeof this.options.dragToSeek&&void 0!==this.options.dragToSeek&&(i=this.options.dragToSeek.debounceTime),t=setTimeout((()=>{this.seekTo(e)}),i),this.emit("interaction",e*this.getDuration()),this.emit("drag",e)}));this.subscriptions.push((()=>{clearTimeout(t),e()}))}}initPlugins(){var t;(null===(t=this.options.plugins)||void 0===t?void 0:t.length)&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}unsubscribePlayerEvents(){this.mediaSubscriptions.forEach((t=>t())),this.mediaSubscriptions=[]}setOptions(t){this.options=Object.assign({},this.options,t),t.duration&&!t.peaks&&(this.decodedData=i.createBuffer(this.exportPeaks(),t.duration)),t.peaks&&t.duration&&(this.decodedData=i.createBuffer(t.peaks,t.duration)),this.renderer.setOptions(this.options),t.audioRate&&this.setPlaybackRate(t.audioRate),null!=t.mediaControls&&(this.getMediaElement().controls=t.mediaControls)}registerPlugin(t){if(this.plugins.includes(t))return t;t._init(this),this.plugins.push(t);const e=t.once("destroy",(()=>{this.plugins=this.plugins.filter((e=>e!==t)),this.subscriptions=this.subscriptions.filter((t=>t!==e))}));return this.subscriptions.push(e),t}unregisterPlugin(t){this.plugins=this.plugins.filter((e=>e!==t)),t.destroy()}getWrapper(){return this.renderer.getWrapper()}getWidth(){return this.renderer.getWidth()}getScroll(){return this.renderer.getScroll()}setScroll(t){return this.renderer.setScroll(t)}setScrollTime(t){const e=t/this.getDuration();this.renderer.setScrollPercentage(e)}getActivePlugins(){return this.plugins}loadAudio(e,s,n,r){return t(this,void 0,void 0,(function*(){var t;if(this.emit("load",e),!this.options.media&&this.isPlaying()&&this.pause(),this.decodedData=null,this.stopAtPosition=null,null===(t=this.abortController)||void 0===t||t.abort(),this.abortController=null,!s&&!n){const t=this.options.fetchParams||{};window.AbortController&&!t.signal&&(this.abortController=new AbortController,t.signal=this.abortController.signal);const i=t=>this.emit("loading",t);s=yield o.fetchBlob(e,i,t);const n=this.options.blobMimeType;n&&(s=new Blob([s],{type:n}))}this.setSrc(e,s);const a=yield new Promise((t=>{const e=r||this.getDuration();e?t(e):this.mediaSubscriptions.push(this.onMediaEvent("loadedmetadata",(()=>t(this.getDuration())),{once:!0}))}));if(!e&&!s){const t=this.getMediaElement();t instanceof d&&(t.duration=a)}if(n)this.decodedData=i.createBuffer(n,a||0);else if(s){const t=yield s.arrayBuffer();this.decodedData=yield i.decode(t,this.options.sampleRate)}this.decodedData&&(this.emit("decode",this.getDuration()),this.renderer.render(this.decodedData)),this.emit("ready",this.getDuration())}))}load(e,i,s){return t(this,void 0,void 0,(function*(){try{return yield this.loadAudio(e,void 0,i,s)}catch(t){throw this.emit("error",t),t}}))}loadBlob(e,i,s){return t(this,void 0,void 0,(function*(){try{return yield this.loadAudio("",e,i,s)}catch(t){throw this.emit("error",t),t}}))}zoom(t){if(!this.decodedData)throw new Error("No audio loaded");this.renderer.zoom(t),this.emit("zoom",t)}getDecodedData(){return this.decodedData}exportPeaks({channels:t=2,maxLength:e=8e3,precision:i=1e4}={}){if(!this.decodedData)throw new Error("The audio has not been decoded yet");const s=Math.min(t,this.decodedData.numberOfChannels),n=[];for(let t=0;t<s;t++){const s=this.decodedData.getChannelData(t),r=[],o=s.length/e;for(let t=0;t<e;t++){const e=s.slice(Math.floor(t*o),Math.ceil((t+1)*o));let n=0;for(let t=0;t<e.length;t++){const i=e[t];Math.abs(i)>Math.abs(n)&&(n=i)}r.push(Math.round(n*i)/i)}n.push(r)}return n}getDuration(){let t=super.getDuration()||0;return 0!==t&&t!==1/0||!this.decodedData||(t=this.decodedData.duration),t}toggleInteraction(t){this.options.interact=t}setTime(t){this.stopAtPosition=null,super.setTime(t),this.updateProgress(t),this.emit("timeupdate",t)}seekTo(t){const e=this.getDuration()*t;this.setTime(e)}play(e,i){const s=Object.create(null,{play:{get:()=>super.play}});return t(this,void 0,void 0,(function*(){null!=e&&this.setTime(e);const t=yield s.play.call(this);return null!=i&&(this.media instanceof d?this.media.stopAt(i):this.stopAtPosition=i),t}))}playPause(){return t(this,void 0,void 0,(function*(){return this.isPlaying()?this.pause():this.play()}))}stop(){this.pause(),this.setTime(0)}skip(t){this.setTime(this.getCurrentTime()+t)}empty(){this.load("",[[0]],.001)}setMediaElement(t){this.unsubscribePlayerEvents(),super.setMediaElement(t),this.initPlayerEvents()}exportImage(){return t(this,arguments,void 0,(function*(t="image/png",e=1,i="dataURL"){return this.renderer.exportImage(t,e,i)}))}destroy(){var t;this.emit("destroy"),null===(t=this.abortController)||void 0===t||t.abort(),this.plugins.forEach((t=>t.destroy())),this.subscriptions.forEach((t=>t())),this.unsubscribePlayerEvents(),this.timer.destroy(),this.renderer.destroy(),super.destroy()}}u.BasePlugin=class extends e{constructor(t){super(),this.subscriptions=[],this.isDestroyed=!1,this.options=t}onInit(){}_init(t){this.isDestroyed&&(this.subscriptions=[],this.isDestroyed=!1),this.wavesurfer=t,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((t=>t())),this.subscriptions=[],this.isDestroyed=!0,this.wavesurfer=void 0}},u.dom=r,module.exports=u;
|
|
1
|
+
"use strict";function t(t,e,i,n){return new(i||(i=Promise))((function(s,r){function o(t){try{h(n.next(t))}catch(t){r(t)}}function a(t){try{h(n.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}h((n=n.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class e{constructor(){this.listeners={}}on(t,e,i){if(this.listeners[t]||(this.listeners[t]=new Set),null==i?void 0:i.once){const i=(...n)=>{this.un(t,i),e(...n)};return this.listeners[t].add(i),()=>this.un(t,i)}return this.listeners[t].add(e),()=>this.un(t,e)}un(t,e){var i;null===(i=this.listeners[t])||void 0===i||i.delete(e)}once(t,e){return this.on(t,e,{once:!0})}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}}const i={decode:function(e,i){return t(this,void 0,void 0,(function*(){const t=new AudioContext({sampleRate:i});try{return yield t.decodeAudioData(e)}finally{t.close()}}))},createBuffer:function(t,e){if(!t||0===t.length)throw new Error("channelData must be a non-empty array");if(e<=0)throw new Error("duration must be greater than 0");if("number"==typeof t[0]&&(t=[t]),!t[0]||0===t[0].length)throw new Error("channelData must contain non-empty channel arrays");!function(t){const e=t[0];if(e.some((t=>t>1||t<-1))){const i=e.length;let n=0;for(let t=0;t<i;t++){const i=Math.abs(e[t]);i>n&&(n=i)}for(const e of t)for(let t=0;t<i;t++)e[t]/=n}}(t);const i=t.map((t=>t instanceof Float32Array?t:Float32Array.from(t)));return{duration:e,length:i[0].length,sampleRate:i[0].length/e,numberOfChannels:i.length,getChannelData:t=>{const e=i[t];if(!e)throw new Error(`Channel ${t} not found`);return e},copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}};function n(t,e){const i=e.xmlns?document.createElementNS(e.xmlns,t):document.createElement(t);for(const[t,s]of Object.entries(e))if("children"===t&&s)for(const[t,e]of Object.entries(s))e instanceof Node?i.appendChild(e):"string"==typeof e?i.appendChild(document.createTextNode(e)):i.appendChild(n(t,e));else"style"===t?Object.assign(i.style,s):"textContent"===t?i.textContent=s:i.setAttribute(t,s.toString());return i}function s(t,e,i){const s=n(t,e||{});return null==i||i.appendChild(s),s}var r=Object.freeze({__proto__:null,createElement:s,default:s});const o={fetchBlob:function(e,i,n){return t(this,void 0,void 0,(function*(){const s=yield fetch(e,n);if(s.status>=400)throw new Error(`Failed to fetch ${e}: ${s.status} (${s.statusText})`);return function(e,i){t(this,void 0,void 0,(function*(){if(!e.body||!e.headers)return;const t=e.body.getReader(),n=Number(e.headers.get("Content-Length"))||0;let s=0;const r=t=>{s+=(null==t?void 0:t.length)||0;const e=Math.round(s/n*100);i(e)};try{for(;;){const e=yield t.read();if(e.done)break;r(e.value)}}catch(t){console.warn("Progress tracking error:",t)}}))}(s.clone(),i),s.blob()}))}};class a extends e{constructor(t){super(),this.isExternalMedia=!1,t.media?(this.media=t.media,this.isExternalMedia=!0):this.media=document.createElement("audio"),t.mediaControls&&(this.media.controls=!0),t.autoplay&&(this.media.autoplay=!0),null!=t.playbackRate&&this.onMediaEvent("canplay",(()=>{null!=t.playbackRate&&(this.media.playbackRate=t.playbackRate)}),{once:!0})}onMediaEvent(t,e,i){return this.media.addEventListener(t,e,i),()=>this.media.removeEventListener(t,e,i)}getSrc(){return this.media.currentSrc||this.media.src||""}revokeSrc(){const t=this.getSrc();t.startsWith("blob:")&&URL.revokeObjectURL(t)}canPlayType(t){return""!==this.media.canPlayType(t)}setSrc(t,e){const i=this.getSrc();if(t&&i===t)return;this.revokeSrc();const n=e instanceof Blob&&(this.canPlayType(e.type)||!t)?URL.createObjectURL(e):t;if(i&&this.media.removeAttribute("src"),n||t)try{this.media.src=n}catch(e){this.media.src=t}}destroy(){this.isExternalMedia||(this.media.pause(),this.revokeSrc(),this.media.removeAttribute("src"),this.media.load(),this.media.remove())}setMediaElement(t){this.media=t}play(){return t(this,void 0,void 0,(function*(){try{return yield this.media.play()}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)return;throw t}}))}pause(){this.media.pause()}isPlaying(){return!this.media.paused&&!this.media.ended}setTime(t){this.media.currentTime=Math.max(0,Math.min(t,this.getDuration()))}getDuration(){return this.media.duration}getCurrentTime(){return this.media.currentTime}getVolume(){return this.media.volume}setVolume(t){this.media.volume=t}getMuted(){return this.media.muted}setMuted(t){this.media.muted=t}getPlaybackRate(){return this.media.playbackRate}isSeeking(){return this.media.seeking}setPlaybackRate(t,e){null!=e&&(this.media.preservesPitch=e),this.media.playbackRate=t}getMediaElement(){return this.media}setSinkId(t){return this.media.setSinkId(t)}}function h(t){return t<0?0:t>1?1:t}function l({maxTop:t,maxBottom:e,halfHeight:i,vScale:n}){const s=Math.round(t*i*n);return{topHeight:s,totalHeight:s+Math.round(e*i*n)||1}}function c({barAlign:t,halfHeight:e,topHeight:i,totalHeight:n,canvasHeight:s}){return"top"===t?0:"bottom"===t?s-n:e-i}function d(t,e,i){const n=e-t.left,s=i-t.top;return[n/t.width,s/t.height]}function u(t){return Boolean(t.barWidth||t.barGap||t.barAlign)}function p(t,e){if(!u(e))return t;const i=e.barWidth||.5,n=i+(e.barGap||i/2);return 0===n?t:Math.floor(t/n)*n}function m({scrollLeft:t,totalWidth:e,numCanvases:i}){if(0===e)return[0];const n=t/e,s=Math.floor(n*i);return[s-1,s,s+1]}function f({scrollLeft:t,clientWidth:e,scrollWidth:i}){if(0===i)return{startX:0,endX:0};return{startX:t/i,endX:(t+e)/i}}class g extends e{constructor(t,e){super(),this.timeouts=[],this.isScrollable=!1,this.audioData=null,this.resizeObserver=null,this.lastContainerWidth=0,this.isDragging=!1,this.subscriptions=[],this.unsubscribeOnScroll=[],this.dragUnsubscribe=null,this.subscriptions=[],this.options=t;const i=this.parentFromOptionsContainer(t.container);this.parent=i;const[n,s]=this.initHtml();i.appendChild(n),this.container=n,this.scrollContainer=s.querySelector(".scroll"),this.wrapper=s.querySelector(".wrapper"),this.canvasWrapper=s.querySelector(".canvases"),this.progressWrapper=s.querySelector(".progress"),this.cursor=s.querySelector(".cursor"),e&&s.appendChild(e),this.initEvents()}parentFromOptionsContainer(t){let e;if("string"==typeof t?e=document.querySelector(t):t instanceof HTMLElement&&(e=t),!e)throw new Error("Container not found");return e}initEvents(){if(this.wrapper.addEventListener("click",(t=>{const e=this.wrapper.getBoundingClientRect(),[i,n]=d(e,t.clientX,t.clientY);this.emit("click",i,n)})),this.wrapper.addEventListener("dblclick",(t=>{const e=this.wrapper.getBoundingClientRect(),[i,n]=d(e,t.clientX,t.clientY);this.emit("dblclick",i,n)})),!0!==this.options.dragToSeek&&"object"!=typeof this.options.dragToSeek||this.initDrag(),this.scrollContainer.addEventListener("scroll",(()=>{const{scrollLeft:t,scrollWidth:e,clientWidth:i}=this.scrollContainer,{startX:n,endX:s}=f({scrollLeft:t,scrollWidth:e,clientWidth:i});this.emit("scroll",n,s,t,t+i)})),"function"==typeof ResizeObserver){const t=this.createDelay(100);this.resizeObserver=new ResizeObserver((()=>{t().then((()=>this.onContainerResize())).catch((()=>{}))})),this.resizeObserver.observe(this.scrollContainer)}}onContainerResize(){const t=this.parent.clientWidth;t===this.lastContainerWidth&&"auto"!==this.options.height||(this.lastContainerWidth=t,this.reRender(),this.emit("resize"))}initDrag(){this.dragUnsubscribe||(this.dragUnsubscribe=function(t,e,i,n,s=3,r=0,o=100){if(!t)return()=>{};const a=new Map,h=matchMedia("(pointer: coarse)").matches;let l=()=>{};const c=c=>{if(c.button!==r)return;if(a.set(c.pointerId,c),a.size>1)return;let d=c.clientX,u=c.clientY,p=!1;const m=Date.now(),f=n=>{if(n.defaultPrevented||a.size>1)return;if(h&&Date.now()-m<o)return;const r=n.clientX,l=n.clientY,c=r-d,f=l-u;if(p||Math.abs(c)>s||Math.abs(f)>s){n.preventDefault(),n.stopPropagation();const s=t.getBoundingClientRect(),{left:o,top:a}=s;p||(null==i||i(d-o,u-a),p=!0),e(c,f,r-o,l-a),d=r,u=l}},g=e=>{if(a.delete(e.pointerId),p){const i=e.clientX,s=e.clientY,r=t.getBoundingClientRect(),{left:o,top:a}=r;null==n||n(i-o,s-a)}l()},v=t=>{a.delete(t.pointerId),t.relatedTarget&&t.relatedTarget!==document.documentElement||g(t)},b=t=>{p&&(t.stopPropagation(),t.preventDefault())},y=t=>{t.defaultPrevented||a.size>1||p&&t.preventDefault()};document.addEventListener("pointermove",f),document.addEventListener("pointerup",g),document.addEventListener("pointerout",v),document.addEventListener("pointercancel",v),document.addEventListener("touchmove",y,{passive:!1}),document.addEventListener("click",b,{capture:!0}),l=()=>{document.removeEventListener("pointermove",f),document.removeEventListener("pointerup",g),document.removeEventListener("pointerout",v),document.removeEventListener("pointercancel",v),document.removeEventListener("touchmove",y),setTimeout((()=>{document.removeEventListener("click",b,{capture:!0})}),10)}};return t.addEventListener("pointerdown",c),()=>{l(),t.removeEventListener("pointerdown",c),a.clear()}}(this.wrapper,((t,e,i)=>{const n=this.wrapper.getBoundingClientRect().width;this.emit("drag",h(i/n))}),(t=>{this.isDragging=!0;const e=this.wrapper.getBoundingClientRect().width;this.emit("dragstart",h(t/e))}),(t=>{this.isDragging=!1;const e=this.wrapper.getBoundingClientRect().width;this.emit("dragend",h(t/e))})),this.subscriptions.push(this.dragUnsubscribe))}initHtml(){const t=document.createElement("div"),e=t.attachShadow({mode:"open"}),i=this.options.cspNonce&&"string"==typeof this.options.cspNonce?this.options.cspNonce.replace(/"/g,""):"";return e.innerHTML=`\n <style${i?` nonce="${i}"`:""}>\n :host {\n user-select: none;\n min-width: 1px;\n }\n :host audio {\n display: block;\n width: 100%;\n }\n :host .scroll {\n overflow-x: auto;\n overflow-y: hidden;\n width: 100%;\n position: relative;\n }\n :host .noScrollbar {\n scrollbar-color: transparent;\n scrollbar-width: none;\n }\n :host .noScrollbar::-webkit-scrollbar {\n display: none;\n -webkit-appearance: none;\n }\n :host .wrapper {\n position: relative;\n overflow: visible;\n z-index: 2;\n }\n :host .canvases {\n min-height: ${this.getHeight(this.options.height,this.options.splitChannels)}px;\n pointer-events: none;\n }\n :host .canvases > div {\n position: relative;\n }\n :host canvas {\n display: block;\n position: absolute;\n top: 0;\n image-rendering: pixelated;\n }\n :host .progress {\n pointer-events: none;\n position: absolute;\n z-index: 2;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n overflow: hidden;\n }\n :host .progress > div {\n position: relative;\n }\n :host .cursor {\n pointer-events: none;\n position: absolute;\n z-index: 5;\n top: 0;\n left: 0;\n height: 100%;\n border-radius: 2px;\n }\n </style>\n\n <div class="scroll" part="scroll">\n <div class="wrapper" part="wrapper">\n <div class="canvases" part="canvases"></div>\n <div class="progress" part="progress"></div>\n <div class="cursor" part="cursor"></div>\n </div>\n </div>\n `,[t,e]}setOptions(t){if(this.options.container!==t.container){const e=this.parentFromOptionsContainer(t.container);e.appendChild(this.container),this.parent=e}!0!==t.dragToSeek&&"object"!=typeof this.options.dragToSeek||this.initDrag(),this.options=t,this.reRender()}getWrapper(){return this.wrapper}getWidth(){return this.scrollContainer.clientWidth}getScroll(){return this.scrollContainer.scrollLeft}setScroll(t){this.scrollContainer.scrollLeft=t}setScrollPercentage(t){const{scrollWidth:e}=this.scrollContainer,i=e*t;this.setScroll(i)}destroy(){var t;this.subscriptions.forEach((t=>t())),this.container.remove(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),null===(t=this.unsubscribeOnScroll)||void 0===t||t.forEach((t=>t())),this.unsubscribeOnScroll=[]}createDelay(t=10){let e,i;const n=()=>{e&&(clearTimeout(e),e=void 0),i&&(i(),i=void 0)};return this.timeouts.push(n),()=>new Promise(((s,r)=>{n(),i=r,e=setTimeout((()=>{e=void 0,i=void 0,s()}),t)}))}getHeight(t,e){var i;const n=(null===(i=this.audioData)||void 0===i?void 0:i.numberOfChannels)||1;return function({optionsHeight:t,optionsSplitChannels:e,parentHeight:i,numberOfChannels:n,defaultHeight:s=128}){if(null==t)return s;const r=Number(t);if(!isNaN(r))return r;if("auto"===t){const t=i||s;return(null==e?void 0:e.every((t=>!t.overlay)))?t/n:t}return s}({optionsHeight:t,optionsSplitChannels:e,parentHeight:this.parent.clientHeight,numberOfChannels:n,defaultHeight:128})}convertColorValues(t){return function(t,e){if(!Array.isArray(t))return t||"";if(0===t.length)return"#999";if(t.length<2)return t[0]||"";const i=document.createElement("canvas"),n=i.getContext("2d"),s=i.height*e,r=n.createLinearGradient(0,0,0,s||e),o=1/(t.length-1);return t.forEach(((t,e)=>{r.addColorStop(e*o,t)})),r}(t,this.getPixelRatio())}getPixelRatio(){return t=window.devicePixelRatio,Math.max(1,t||1);var t}renderBarWaveform(t,e,i,n){const{width:s,height:r}=i.canvas,{halfHeight:o,barWidth:a,barRadius:h,barIndexScale:d,barSpacing:u}=function({width:t,height:e,length:i,options:n,pixelRatio:s}){const r=e/2,o=n.barWidth?n.barWidth*s:1,a=n.barGap?n.barGap*s:n.barWidth?o/2:0,h=o+a||1;return{halfHeight:r,barWidth:o,barGap:a,barRadius:n.barRadius||0,barIndexScale:i>0?t/h/i:0,barSpacing:h}}({width:s,height:r,length:(t[0]||[]).length,options:e,pixelRatio:this.getPixelRatio()}),p=function({channelData:t,barIndexScale:e,barSpacing:i,barWidth:n,halfHeight:s,vScale:r,canvasHeight:o,barAlign:a}){const h=t[0]||[],d=t[1]||h,u=h.length,p=[];let m=0,f=0,g=0;for(let t=0;t<=u;t++){const u=Math.round(t*e);if(u>m){const{topHeight:t,totalHeight:e}=l({maxTop:f,maxBottom:g,halfHeight:s,vScale:r}),h=c({barAlign:a,halfHeight:s,topHeight:t,totalHeight:e,canvasHeight:o});p.push({x:m*i,y:h,width:n,height:e}),m=u,f=0,g=0}const v=Math.abs(h[t]||0),b=Math.abs(d[t]||0);v>f&&(f=v),b>g&&(g=b)}return p}({channelData:t,barIndexScale:d,barSpacing:u,barWidth:a,halfHeight:o,vScale:n,canvasHeight:r,barAlign:e.barAlign});i.beginPath();for(const t of p)h&&"roundRect"in i?i.roundRect(t.x,t.y,t.width,t.height,h):i.rect(t.x,t.y,t.width,t.height);i.fill(),i.closePath()}renderLineWaveform(t,e,i,n){const{width:s,height:r}=i.canvas,o=function({channelData:t,width:e,height:i,vScale:n}){const s=i/2,r=t[0]||[];return[r,t[1]||r].map(((t,i)=>{const r=t.length,o=r?e/r:0,a=s,h=0===i?-1:1,l=[{x:0,y:a}];let c=0,d=0;for(let e=0;e<=r;e++){const i=Math.round(e*o);if(i>c){const t=a+(Math.round(d*s*n)||1)*h;l.push({x:c,y:t}),c=i,d=0}const r=Math.abs(t[e]||0);r>d&&(d=r)}return l.push({x:c,y:a}),l}))}({channelData:t,width:s,height:r,vScale:n});i.beginPath();for(const t of o)if(t.length){i.moveTo(t[0].x,t[0].y);for(let e=1;e<t.length;e++){const n=t[e];i.lineTo(n.x,n.y)}}i.fill(),i.closePath()}renderWaveform(t,e,i){if(i.fillStyle=this.convertColorValues(e.waveColor),e.renderFunction)return void e.renderFunction(t,i);const n=function({channelData:t,barHeight:e,normalize:i}){var n;const s=e||1;if(!i)return s;const r=t[0];if(!r||0===r.length)return s;let o=0;for(let t=0;t<r.length;t++){const e=null!==(n=r[t])&&void 0!==n?n:0,i=Math.abs(e);i>o&&(o=i)}return o?s/o:s}({channelData:t,barHeight:e.barHeight,normalize:e.normalize});u(e)?this.renderBarWaveform(t,e,i,n):this.renderLineWaveform(t,e,i,n)}renderSingleCanvas(t,e,i,n,s,r,o){const a=this.getPixelRatio(),h=document.createElement("canvas");h.width=Math.round(i*a),h.height=Math.round(n*a),h.style.width=`${i}px`,h.style.height=`${n}px`,h.style.left=`${Math.round(s)}px`,r.appendChild(h);const l=h.getContext("2d");if(e.renderFunction?(l.fillStyle=this.convertColorValues(e.waveColor),e.renderFunction(t,l)):this.renderWaveform(t,e,l),h.width>0&&h.height>0){const t=h.cloneNode(),i=t.getContext("2d");i.drawImage(h,0,0),i.globalCompositeOperation="source-in",i.fillStyle=this.convertColorValues(e.progressColor),i.fillRect(0,0,h.width,h.height),o.appendChild(t)}}renderMultiCanvas(t,e,i,n,s,r){const o=this.getPixelRatio(),{clientWidth:a}=this.scrollContainer,h=i/o,l=function({clientWidth:t,totalWidth:e,options:i}){return p(Math.min(8e3,t,e),i)}({clientWidth:a,totalWidth:h,options:e});let c={};if(0===l)return;const d=i=>{if(i<0||i>=u)return;if(c[i])return;c[i]=!0;const o=i*l;let a=Math.min(h-o,l);if(a=p(a,e),a<=0)return;const d=function({channelData:t,offset:e,clampedWidth:i,totalWidth:n}){return t.map((t=>{const s=Math.floor(e/n*t.length),r=Math.floor((e+i)/n*t.length);return t.slice(s,r)}))}({channelData:t,offset:o,clampedWidth:a,totalWidth:h});this.renderSingleCanvas(d,e,a,n,o,s,r)},u=Math.ceil(h/l);if(!this.isScrollable){for(let t=0;t<u;t++)d(t);return}if(m({scrollLeft:this.scrollContainer.scrollLeft,totalWidth:h,numCanvases:u}).forEach((t=>d(t))),u>1){const t=this.on("scroll",(()=>{const{scrollLeft:t}=this.scrollContainer;Object.keys(c).length>10&&(s.innerHTML="",r.innerHTML="",c={}),m({scrollLeft:t,totalWidth:h,numCanvases:u}).forEach((t=>d(t)))}));this.unsubscribeOnScroll.push(t)}}renderChannel(t,e,i,n){var{overlay:s}=e,r=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i}(e,["overlay"]);const o=document.createElement("div"),a=this.getHeight(r.height,r.splitChannels);o.style.height=`${a}px`,s&&n>0&&(o.style.marginTop=`-${a}px`),this.canvasWrapper.style.minHeight=`${a}px`,this.canvasWrapper.appendChild(o);const h=o.cloneNode();this.progressWrapper.appendChild(h),this.renderMultiCanvas(t,r,i,a,o,h)}render(e){return t(this,void 0,void 0,(function*(){var t;this.timeouts.forEach((t=>t())),this.timeouts=[],this.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="",null!=this.options.width&&(this.scrollContainer.style.width="number"==typeof this.options.width?`${this.options.width}px`:this.options.width);const i=this.getPixelRatio(),n=this.scrollContainer.clientWidth,{scrollWidth:s,isScrollable:r,useParentWidth:o,width:a}=function({duration:t,minPxPerSec:e=0,parentWidth:i,fillParent:n,pixelRatio:s}){const r=Math.ceil(t*e),o=r>i,a=Boolean(n&&!o);return{scrollWidth:r,isScrollable:o,useParentWidth:a,width:(a?i:r)*s}}({duration:e.duration,minPxPerSec:this.options.minPxPerSec||0,parentWidth:n,fillParent:this.options.fillParent,pixelRatio:i});if(this.isScrollable=r,this.wrapper.style.width=o?"100%":`${s}px`,this.scrollContainer.style.overflowX=this.isScrollable?"auto":"hidden",this.scrollContainer.classList.toggle("noScrollbar",!!this.options.hideScrollbar),this.cursor.style.backgroundColor=`${this.options.cursorColor||this.options.progressColor}`,this.cursor.style.width=`${this.options.cursorWidth}px`,this.audioData=e,this.emit("render"),this.options.splitChannels)for(let i=0;i<e.numberOfChannels;i++){const n=Object.assign(Object.assign({},this.options),null===(t=this.options.splitChannels)||void 0===t?void 0:t[i]);this.renderChannel([e.getChannelData(i)],n,a,i)}else{const t=[e.getChannelData(0)];e.numberOfChannels>1&&t.push(e.getChannelData(1)),this.renderChannel(t,this.options,a,0)}Promise.resolve().then((()=>this.emit("rendered")))}))}reRender(){if(this.unsubscribeOnScroll.forEach((t=>t())),this.unsubscribeOnScroll=[],!this.audioData)return;const{scrollWidth:t}=this.scrollContainer,{right:e}=this.progressWrapper.getBoundingClientRect();if(this.render(this.audioData),this.isScrollable&&t!==this.scrollContainer.scrollWidth){const{right:t}=this.progressWrapper.getBoundingClientRect(),i=function(t){const e=2*t;return(e<0?Math.floor(e):Math.ceil(e))/2}(t-e);this.scrollContainer.scrollLeft+=i}}zoom(t){this.options.minPxPerSec=t,this.reRender()}scrollIntoView(t,e=!1){const{scrollLeft:i,scrollWidth:n,clientWidth:s}=this.scrollContainer,r=t*n,o=i,a=i+s,h=s/2;if(this.isDragging){const t=30;r+t>a?this.scrollContainer.scrollLeft+=t:r-t<o&&(this.scrollContainer.scrollLeft-=t)}else{(r<o||r>a)&&(this.scrollContainer.scrollLeft=r-(this.options.autoCenter?h:0));const t=r-i-h;e&&this.options.autoCenter&&t>0&&(this.scrollContainer.scrollLeft+=t)}{const t=this.scrollContainer.scrollLeft,{startX:e,endX:i}=f({scrollLeft:t,scrollWidth:n,clientWidth:s});this.emit("scroll",e,i,t,t+s)}}renderProgress(t,e){if(isNaN(t))return;const i=100*t;this.canvasWrapper.style.clipPath=`polygon(${i}% 0%, 100% 0%, 100% 100%, ${i}% 100%)`,this.progressWrapper.style.width=`${i}%`,this.cursor.style.left=`${i}%`,this.cursor.style.transform=this.options.cursorWidth?`translateX(-${t*this.options.cursorWidth}px)`:"",this.isScrollable&&this.options.autoScroll&&this.scrollIntoView(t,e)}exportImage(e,i,n){return t(this,void 0,void 0,(function*(){const t=this.canvasWrapper.querySelectorAll("canvas");if(!t.length)throw new Error("No waveform data");if("dataURL"===n){const n=Array.from(t).map((t=>t.toDataURL(e,i)));return Promise.resolve(n)}return Promise.all(Array.from(t).map((t=>new Promise(((n,s)=>{t.toBlob((t=>{t?n(t):s(new Error("Could not export image"))}),e,i)})))))}))}}class v extends e{constructor(){super(...arguments),this.animationFrameId=null,this.isRunning=!1}start(){if(this.isRunning)return;this.isRunning=!0;const t=()=>{this.isRunning&&(this.emit("tick"),this.animationFrameId=requestAnimationFrame(t))};t()}stop(){this.isRunning=!1,null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}destroy(){this.stop()}}class b extends e{constructor(t=new AudioContext){super(),this.bufferNode=null,this.playStartTime=0,this.playedDuration=0,this._muted=!1,this._playbackRate=1,this._duration=void 0,this.buffer=null,this.currentSrc="",this.paused=!0,this.crossOrigin=null,this.seeking=!1,this.autoplay=!1,this.addEventListener=this.on,this.removeEventListener=this.un,this.audioContext=t,this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination)}load(){return t(this,void 0,void 0,(function*(){}))}get src(){return this.currentSrc}set src(t){if(this.currentSrc=t,this._duration=void 0,!t)return this.buffer=null,void this.emit("emptied");fetch(t).then((e=>{if(e.status>=400)throw new Error(`Failed to fetch ${t}: ${e.status} (${e.statusText})`);return e.arrayBuffer()})).then((e=>this.currentSrc!==t?null:this.audioContext.decodeAudioData(e))).then((e=>{this.currentSrc===t&&(this.buffer=e,this.emit("loadedmetadata"),this.emit("canplay"),this.autoplay&&this.play())})).catch((t=>{console.error("WebAudioPlayer load error:",t)}))}_play(){if(!this.paused)return;this.paused=!1,this.bufferNode&&(this.bufferNode.onended=null,this.bufferNode.disconnect()),this.bufferNode=this.audioContext.createBufferSource(),this.buffer&&(this.bufferNode.buffer=this.buffer),this.bufferNode.playbackRate.value=this._playbackRate,this.bufferNode.connect(this.gainNode);let t=this.playedDuration*this._playbackRate;(t>=this.duration||t<0)&&(t=0,this.playedDuration=0),this.bufferNode.start(this.audioContext.currentTime,t),this.playStartTime=this.audioContext.currentTime,this.bufferNode.onended=()=>{this.currentTime>=this.duration&&(this.pause(),this.emit("ended"))}}_pause(){var t;this.paused=!0,null===(t=this.bufferNode)||void 0===t||t.stop(),this.playedDuration+=this.audioContext.currentTime-this.playStartTime}play(){return t(this,void 0,void 0,(function*(){this.paused&&(this._play(),this.emit("play"))}))}pause(){this.paused||(this._pause(),this.emit("pause"))}stopAt(t){const e=t-this.currentTime,i=this.bufferNode;null==i||i.stop(this.audioContext.currentTime+e),null==i||i.addEventListener("ended",(()=>{i===this.bufferNode&&(this.bufferNode=null,this.pause())}),{once:!0})}setSinkId(e){return t(this,void 0,void 0,(function*(){return this.audioContext.setSinkId(e)}))}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this.bufferNode&&(this.bufferNode.playbackRate.value=t)}get currentTime(){return(this.paused?this.playedDuration:this.playedDuration+(this.audioContext.currentTime-this.playStartTime))*this._playbackRate}set currentTime(t){const e=!this.paused;e&&this._pause(),this.playedDuration=t/this._playbackRate,e&&this._play(),this.emit("seeking"),this.emit("timeupdate")}get duration(){var t,e;return null!==(t=this._duration)&&void 0!==t?t:(null===(e=this.buffer)||void 0===e?void 0:e.duration)||0}set duration(t){this._duration=t}get volume(){return this.gainNode.gain.value}set volume(t){this.gainNode.gain.value=t,this.emit("volumechange")}get muted(){return this._muted}set muted(t){this._muted!==t&&(this._muted=t,this._muted?this.gainNode.disconnect():this.gainNode.connect(this.audioContext.destination))}canPlayType(t){return/^(audio|video)\//.test(t)}getGainNode(){return this.gainNode}getChannelData(){const t=[];if(!this.buffer)return t;const e=this.buffer.numberOfChannels;for(let i=0;i<e;i++)t.push(this.buffer.getChannelData(i));return t}removeAttribute(t){switch(t){case"src":this.src="";break;case"playbackRate":this.playbackRate=0;break;case"currentTime":this.currentTime=0;break;case"duration":this.duration=0;break;case"volume":this.volume=0;break;case"muted":this.muted=!1}}}const y={waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,dragToSeek:!1,autoScroll:!0,autoCenter:!0,sampleRate:8e3};class C extends a{static create(t){return new C(t)}constructor(t){const e=t.media||("WebAudio"===t.backend?new b:void 0);super({media:e,mediaControls:t.mediaControls,autoplay:t.autoplay,playbackRate:t.audioRate}),this.plugins=[],this.decodedData=null,this.stopAtPosition=null,this.subscriptions=[],this.mediaSubscriptions=[],this.abortController=null,this.options=Object.assign({},y,t),this.timer=new v;const i=e?void 0:this.getMediaElement();this.renderer=new g(this.options,i),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initPlugins();const n=this.options.url||this.getSrc()||"";Promise.resolve().then((()=>{this.emit("init");const{peaks:t,duration:e}=this.options;(n||t&&e)&&this.load(n,t,e).catch((t=>{this.emit("error",t instanceof Error?t:new Error(String(t)))}))}))}updateProgress(t=this.getCurrentTime()){return this.renderer.renderProgress(t/this.getDuration(),this.isPlaying()),t}initTimerEvents(){this.subscriptions.push(this.timer.on("tick",(()=>{if(!this.isSeeking()){const t=this.updateProgress();this.emit("timeupdate",t),this.emit("audioprocess",t),null!=this.stopAtPosition&&this.isPlaying()&&t>=this.stopAtPosition&&this.pause()}})))}initPlayerEvents(){this.isPlaying()&&(this.emit("play"),this.timer.start()),this.mediaSubscriptions.push(this.onMediaEvent("timeupdate",(()=>{const t=this.updateProgress();this.emit("timeupdate",t)})),this.onMediaEvent("play",(()=>{this.emit("play"),this.timer.start()})),this.onMediaEvent("pause",(()=>{this.emit("pause"),this.timer.stop(),this.stopAtPosition=null})),this.onMediaEvent("emptied",(()=>{this.timer.stop(),this.stopAtPosition=null})),this.onMediaEvent("ended",(()=>{this.emit("timeupdate",this.getDuration()),this.emit("finish"),this.stopAtPosition=null})),this.onMediaEvent("seeking",(()=>{this.emit("seeking",this.getCurrentTime())})),this.onMediaEvent("error",(()=>{var t;this.emit("error",null!==(t=this.getMediaElement().error)&&void 0!==t?t:new Error("Media error")),this.stopAtPosition=null})))}initRendererEvents(){this.subscriptions.push(this.renderer.on("click",((t,e)=>{this.options.interact&&(this.seekTo(t),this.emit("interaction",t*this.getDuration()),this.emit("click",t,e))})),this.renderer.on("dblclick",((t,e)=>{this.emit("dblclick",t,e)})),this.renderer.on("scroll",((t,e,i,n)=>{const s=this.getDuration();this.emit("scroll",t*s,e*s,i,n)})),this.renderer.on("render",(()=>{this.emit("redraw")})),this.renderer.on("rendered",(()=>{this.emit("redrawcomplete")})),this.renderer.on("dragstart",(t=>{this.emit("dragstart",t)})),this.renderer.on("dragend",(t=>{this.emit("dragend",t)})),this.renderer.on("resize",(()=>{this.emit("resize")})));{let t;const e=this.renderer.on("drag",(e=>{var i;if(!this.options.interact)return;this.renderer.renderProgress(e),clearTimeout(t);let n=0;const s=this.options.dragToSeek;this.isPlaying()?n=0:!0===s?n=200:s&&"object"==typeof s&&(n=null!==(i=s.debounceTime)&&void 0!==i?i:200),t=setTimeout((()=>{this.seekTo(e)}),n),this.emit("interaction",e*this.getDuration()),this.emit("drag",e)}));this.subscriptions.push((()=>{clearTimeout(t),e()}))}}initPlugins(){var t;(null===(t=this.options.plugins)||void 0===t?void 0:t.length)&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}unsubscribePlayerEvents(){this.mediaSubscriptions.forEach((t=>t())),this.mediaSubscriptions=[]}setOptions(t){this.options=Object.assign({},this.options,t),t.duration&&!t.peaks&&(this.decodedData=i.createBuffer(this.exportPeaks(),t.duration)),t.peaks&&t.duration&&(this.decodedData=i.createBuffer(t.peaks,t.duration)),this.renderer.setOptions(this.options),t.audioRate&&this.setPlaybackRate(t.audioRate),null!=t.mediaControls&&(this.getMediaElement().controls=t.mediaControls)}registerPlugin(t){if(this.plugins.includes(t))return t;t._init(this),this.plugins.push(t);const e=t.once("destroy",(()=>{this.plugins=this.plugins.filter((e=>e!==t)),this.subscriptions=this.subscriptions.filter((t=>t!==e))}));return this.subscriptions.push(e),t}unregisterPlugin(t){this.plugins=this.plugins.filter((e=>e!==t)),t.destroy()}getWrapper(){return this.renderer.getWrapper()}getWidth(){return this.renderer.getWidth()}getScroll(){return this.renderer.getScroll()}setScroll(t){return this.renderer.setScroll(t)}setScrollTime(t){const e=t/this.getDuration();this.renderer.setScrollPercentage(e)}getActivePlugins(){return this.plugins}loadAudio(e,n,s,r){return t(this,void 0,void 0,(function*(){var t;if(this.emit("load",e),!this.options.media&&this.isPlaying()&&this.pause(),this.decodedData=null,this.stopAtPosition=null,null===(t=this.abortController)||void 0===t||t.abort(),this.abortController=null,!n&&!s){const t=this.options.fetchParams||{};window.AbortController&&!t.signal&&(this.abortController=new AbortController,t.signal=this.abortController.signal);const i=t=>this.emit("loading",t);n=yield o.fetchBlob(e,i,t);const s=this.options.blobMimeType;s&&(n=new Blob([n],{type:s}))}this.setSrc(e,n);const a=yield new Promise((t=>{const e=r||this.getDuration();e?t(e):this.mediaSubscriptions.push(this.onMediaEvent("loadedmetadata",(()=>t(this.getDuration())),{once:!0}))}));if(!e&&!n){const t=this.getMediaElement();t instanceof b&&(t.duration=a)}if(s)this.decodedData=i.createBuffer(s,a||0);else if(n){const t=yield n.arrayBuffer();this.decodedData=yield i.decode(t,this.options.sampleRate)}this.decodedData&&(this.emit("decode",this.getDuration()),this.renderer.render(this.decodedData)),this.emit("ready",this.getDuration())}))}load(e,i,n){return t(this,void 0,void 0,(function*(){try{return yield this.loadAudio(e,void 0,i,n)}catch(t){throw this.emit("error",t),t}}))}loadBlob(e,i,n){return t(this,void 0,void 0,(function*(){try{return yield this.loadAudio("",e,i,n)}catch(t){throw this.emit("error",t),t}}))}zoom(t){if(!this.decodedData)throw new Error("No audio loaded");this.renderer.zoom(t),this.emit("zoom",t)}getDecodedData(){return this.decodedData}exportPeaks({channels:t=2,maxLength:e=8e3,precision:i=1e4}={}){if(!this.decodedData)throw new Error("The audio has not been decoded yet");const n=Math.min(t,this.decodedData.numberOfChannels),s=[];for(let t=0;t<n;t++){const n=this.decodedData.getChannelData(t),r=[],o=n.length/e;for(let t=0;t<e;t++){const e=n.slice(Math.floor(t*o),Math.ceil((t+1)*o));let s=0;for(let t=0;t<e.length;t++){const i=e[t];Math.abs(i)>Math.abs(s)&&(s=i)}r.push(Math.round(s*i)/i)}s.push(r)}return s}getDuration(){let t=super.getDuration()||0;return 0!==t&&t!==1/0||!this.decodedData||(t=this.decodedData.duration),t}toggleInteraction(t){this.options.interact=t}setTime(t){this.stopAtPosition=null,super.setTime(t),this.updateProgress(t),this.emit("timeupdate",t)}seekTo(t){const e=this.getDuration()*t;this.setTime(e)}play(e,i){const n=Object.create(null,{play:{get:()=>super.play}});return t(this,void 0,void 0,(function*(){null!=e&&this.setTime(e);const t=yield n.play.call(this);return null!=i&&(this.media instanceof b?this.media.stopAt(i):this.stopAtPosition=i),t}))}playPause(){return t(this,void 0,void 0,(function*(){return this.isPlaying()?this.pause():this.play()}))}stop(){this.pause(),this.setTime(0)}skip(t){this.setTime(this.getCurrentTime()+t)}empty(){this.load("",[[0]],.001)}setMediaElement(t){this.unsubscribePlayerEvents(),super.setMediaElement(t),this.initPlayerEvents()}exportImage(){return t(this,arguments,void 0,(function*(t="image/png",e=1,i="dataURL"){return this.renderer.exportImage(t,e,i)}))}destroy(){var t;this.emit("destroy"),null===(t=this.abortController)||void 0===t||t.abort(),this.plugins.forEach((t=>t.destroy())),this.subscriptions.forEach((t=>t())),this.unsubscribePlayerEvents(),this.timer.destroy(),this.renderer.destroy(),super.destroy()}}C.BasePlugin=class extends e{constructor(t){super(),this.subscriptions=[],this.isDestroyed=!1,this.options=t}onInit(){}_init(t){this.isDestroyed&&(this.subscriptions=[],this.isDestroyed=!1),this.wavesurfer=t,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((t=>t())),this.subscriptions=[],this.isDestroyed=!0,this.wavesurfer=void 0}},C.dom=r,module.exports=C;
|