wavesurfer.js 7.1.1 → 7.1.3
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/README.md +4 -3
- package/dist/plugins/envelope.js +1 -348
- package/dist/plugins/hover.js +1 -103
- package/dist/plugins/minimap.cjs +1 -1
- package/dist/plugins/minimap.esm.js +1 -1
- package/dist/plugins/minimap.js +1 -109
- package/dist/plugins/minimap.min.js +1 -1
- package/dist/plugins/plugins/regions.d.ts +1 -1
- package/dist/plugins/plugins/timeline.d.ts +8 -4
- package/dist/plugins/record.js +1 -122
- package/dist/plugins/regions.cjs +1 -1
- package/dist/plugins/regions.d.ts +1 -1
- package/dist/plugins/regions.esm.js +1 -1
- package/dist/plugins/regions.js +1 -363
- package/dist/plugins/regions.min.js +1 -1
- package/dist/plugins/renderer.d.ts +4 -2
- package/dist/plugins/spectrogram.js +1 -484
- package/dist/plugins/timeline.cjs +1 -1
- package/dist/plugins/timeline.d.ts +8 -4
- package/dist/plugins/timeline.esm.js +1 -1
- package/dist/plugins/timeline.js +1 -166
- package/dist/plugins/timeline.min.js +1 -1
- package/dist/plugins/wavesurfer.d.ts +0 -1
- package/dist/renderer.d.ts +4 -2
- package/dist/renderer.js +66 -29
- package/dist/wavesurfer.cjs +1 -1
- package/dist/wavesurfer.d.ts +0 -1
- package/dist/wavesurfer.esm.js +1 -1
- package/dist/wavesurfer.js +20 -21
- package/dist/wavesurfer.min.js +1 -1
- package/package.json +12 -10
package/README.md
CHANGED
|
@@ -25,7 +25,7 @@ import WaveSurfer from 'wavesurfer.js'
|
|
|
25
25
|
|
|
26
26
|
Alternatively, insert a UMD script tag which exports the library as a global `WaveSurfer` variable:
|
|
27
27
|
```html
|
|
28
|
-
<script src="https://unpkg.com/wavesurfer.js@7
|
|
28
|
+
<script src="https://unpkg.com/wavesurfer.js@7"></script>
|
|
29
29
|
```
|
|
30
30
|
|
|
31
31
|
Create a wavesurfer instance and pass various [options](#wavesurfer-options):
|
|
@@ -40,10 +40,10 @@ const wavesurfer = WaveSurfer.create({
|
|
|
40
40
|
|
|
41
41
|
To import one of the plugins, e.g. the [Regions plugin](https://wavesurfer-js.org/examples/#regions.js):
|
|
42
42
|
```js
|
|
43
|
-
import Regions from 'wavesurfer.js/
|
|
43
|
+
import Regions from 'wavesurfer.js/plugins/regions'
|
|
44
44
|
```
|
|
45
45
|
|
|
46
|
-
Or as a script tag
|
|
46
|
+
Or as a script tag that will export `WaveSurfer.Regions`:
|
|
47
47
|
```html
|
|
48
48
|
<script src="https://unpkg.com/wavesurfer.js@7/dist/plugins/regions.min.js"></script>
|
|
49
49
|
```
|
|
@@ -89,6 +89,7 @@ See the documentation on wavesurfer [methods](http://wavesurfer-js.org/docs/meth
|
|
|
89
89
|
|
|
90
90
|
### Wavesurfer events
|
|
91
91
|
- `load`: `[url: string]` - When audio starts loading
|
|
92
|
+
- `loading`: `[percentage: number]` - When audio is being loaded
|
|
92
93
|
- `decode`: `[duration: number]` - When the audio has been decoded
|
|
93
94
|
- `ready`: `[duration: number]` - When the audio is both decoded and can play
|
|
94
95
|
- `redraw`: `[]` - When a waveform is drawn
|
package/dist/plugins/envelope.js
CHANGED
|
@@ -1,348 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* Envelope is a visual UI for controlling the audio volume and add fade-in and fade-out effects.
|
|
3
|
-
*/
|
|
4
|
-
import BasePlugin from '../base-plugin.js';
|
|
5
|
-
import { makeDraggable } from '../draggable.js';
|
|
6
|
-
import EventEmitter from '../event-emitter.js';
|
|
7
|
-
const defaultOptions = {
|
|
8
|
-
fadeInStart: 0,
|
|
9
|
-
fadeOutEnd: 0,
|
|
10
|
-
fadeInEnd: 0,
|
|
11
|
-
fadeOutStart: 0,
|
|
12
|
-
lineWidth: 4,
|
|
13
|
-
lineColor: 'rgba(0, 0, 255, 0.5)',
|
|
14
|
-
dragPointSize: 10,
|
|
15
|
-
dragPointFill: 'rgba(255, 255, 255, 0.8)',
|
|
16
|
-
dragPointStroke: 'rgba(255, 255, 255, 0.8)',
|
|
17
|
-
};
|
|
18
|
-
class Polyline extends EventEmitter {
|
|
19
|
-
constructor(options, wrapper) {
|
|
20
|
-
super();
|
|
21
|
-
this.top = 0;
|
|
22
|
-
// An padding to make the envelope fit into the SVG
|
|
23
|
-
this.padding = options.dragPointSize / 2 + 1;
|
|
24
|
-
// SVG element
|
|
25
|
-
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
|
26
|
-
svg.setAttribute('width', '100%');
|
|
27
|
-
svg.setAttribute('height', '100%');
|
|
28
|
-
svg.setAttribute('viewBox', '0 0 0 0');
|
|
29
|
-
svg.setAttribute('preserveAspectRatio', 'none');
|
|
30
|
-
svg.setAttribute('style', 'position: absolute; left: 0; top: 0; z-index: 4; pointer-events: none;');
|
|
31
|
-
svg.setAttribute('part', 'envelope');
|
|
32
|
-
this.svg = svg;
|
|
33
|
-
// A polyline representing the envelope
|
|
34
|
-
const polyline = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
|
|
35
|
-
polyline.setAttribute('points', '0,0 0,0 0,0 0,0');
|
|
36
|
-
polyline.setAttribute('stroke', options.lineColor);
|
|
37
|
-
polyline.setAttribute('stroke-width', options.lineWidth);
|
|
38
|
-
polyline.setAttribute('fill', 'none');
|
|
39
|
-
polyline.setAttribute('style', 'pointer-events: none;');
|
|
40
|
-
polyline.setAttribute('part', 'polyline');
|
|
41
|
-
svg.appendChild(polyline);
|
|
42
|
-
// Draggable top line
|
|
43
|
-
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
|
|
44
|
-
line.setAttribute('stroke', 'transparent');
|
|
45
|
-
line.setAttribute('stroke-width', (options.lineWidth * 3).toString());
|
|
46
|
-
line.setAttribute('style', 'cursor: ns-resize; pointer-events: all;');
|
|
47
|
-
line.setAttribute('part', 'line');
|
|
48
|
-
svg.appendChild(line);
|
|
49
|
-
[0, 1].forEach(() => {
|
|
50
|
-
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
|
|
51
|
-
circle.setAttribute('r', (options.dragPointSize / 2).toString());
|
|
52
|
-
circle.setAttribute('fill', options.dragPointFill);
|
|
53
|
-
circle.setAttribute('stroke', options.dragPointStroke || options.dragPointFill);
|
|
54
|
-
circle.setAttribute('stroke-width', '2');
|
|
55
|
-
circle.setAttribute('style', 'cursor: ew-resize; pointer-events: all;');
|
|
56
|
-
circle.setAttribute('part', 'circle');
|
|
57
|
-
svg.appendChild(circle);
|
|
58
|
-
});
|
|
59
|
-
wrapper.appendChild(svg);
|
|
60
|
-
// Init dtagging
|
|
61
|
-
{
|
|
62
|
-
// On top line drag
|
|
63
|
-
const onDragY = (dy) => {
|
|
64
|
-
const newTop = this.top + dy;
|
|
65
|
-
const { height } = svg.viewBox.baseVal;
|
|
66
|
-
if (newTop < -0.5 || newTop > height)
|
|
67
|
-
return;
|
|
68
|
-
const relativeY = Math.min(1, Math.max(0, (height - newTop) / height));
|
|
69
|
-
this.emit('line-move', relativeY);
|
|
70
|
-
};
|
|
71
|
-
// On points drag
|
|
72
|
-
const onDragX = (index, dx) => {
|
|
73
|
-
const point = polyline.points.getItem(index);
|
|
74
|
-
const newX = point.x + dx;
|
|
75
|
-
const { width } = svg.viewBox.baseVal;
|
|
76
|
-
this.emit('point-move', index, newX / width);
|
|
77
|
-
};
|
|
78
|
-
// Draggable top line of the polyline
|
|
79
|
-
this.makeDraggable(line, (_, y) => onDragY(y));
|
|
80
|
-
// Make each point draggable
|
|
81
|
-
const draggables = this.svg.querySelectorAll('circle');
|
|
82
|
-
Array.from(draggables).forEach((draggable, index) => {
|
|
83
|
-
this.makeDraggable(draggable, (x) => onDragX(index + 1, x));
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
makeDraggable(draggable, onDrag) {
|
|
88
|
-
makeDraggable(draggable, onDrag);
|
|
89
|
-
}
|
|
90
|
-
update({ x1, x2, x3, x4, y }) {
|
|
91
|
-
const width = this.svg.clientWidth;
|
|
92
|
-
const height = this.svg.clientHeight;
|
|
93
|
-
this.top = height - y * height;
|
|
94
|
-
const paddedTop = Math.max(this.padding, Math.min(this.top, height - this.padding));
|
|
95
|
-
this.svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
|
|
96
|
-
const polyline = this.svg.querySelector('polyline');
|
|
97
|
-
const { points } = polyline;
|
|
98
|
-
points.getItem(0).x = x1 * width;
|
|
99
|
-
points.getItem(0).y = height;
|
|
100
|
-
points.getItem(1).x = x2 * width;
|
|
101
|
-
points.getItem(1).y = paddedTop;
|
|
102
|
-
points.getItem(2).x = x3 * width;
|
|
103
|
-
points.getItem(2).y = paddedTop;
|
|
104
|
-
points.getItem(3).x = x4 * width;
|
|
105
|
-
points.getItem(3).y = height;
|
|
106
|
-
const line = this.svg.querySelector('line');
|
|
107
|
-
line.setAttribute('x1', points.getItem(1).x.toString());
|
|
108
|
-
line.setAttribute('x2', points.getItem(2).x.toString());
|
|
109
|
-
line.setAttribute('y1', paddedTop.toString());
|
|
110
|
-
line.setAttribute('y2', paddedTop.toString());
|
|
111
|
-
const circles = this.svg.querySelectorAll('circle');
|
|
112
|
-
Array.from(circles).forEach((circle, i) => {
|
|
113
|
-
const point = points.getItem(i + 1);
|
|
114
|
-
circle.setAttribute('cx', point.x.toString());
|
|
115
|
-
circle.setAttribute('cy', point.y.toString());
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
destroy() {
|
|
119
|
-
this.svg.remove();
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
class EnvelopePlugin extends BasePlugin {
|
|
123
|
-
constructor(options) {
|
|
124
|
-
var _a;
|
|
125
|
-
super(options);
|
|
126
|
-
this.polyline = null;
|
|
127
|
-
this.audioContext = null;
|
|
128
|
-
this.gainNode = null;
|
|
129
|
-
this.volume = 1;
|
|
130
|
-
this.isFadingIn = false;
|
|
131
|
-
this.isFadingOut = false;
|
|
132
|
-
// Adjust the exponent to change the curve of the volume control
|
|
133
|
-
this.naturalVolumeExponent = 1.5;
|
|
134
|
-
this.options = Object.assign({}, defaultOptions, options);
|
|
135
|
-
this.options.lineColor = this.options.lineColor || defaultOptions.lineColor;
|
|
136
|
-
this.options.dragPointFill = this.options.dragPointFill || defaultOptions.dragPointFill;
|
|
137
|
-
this.options.dragPointStroke = this.options.dragPointStroke || defaultOptions.dragPointStroke;
|
|
138
|
-
this.volume = (_a = this.options.volume) !== null && _a !== void 0 ? _a : 1;
|
|
139
|
-
}
|
|
140
|
-
static create(options) {
|
|
141
|
-
return new EnvelopePlugin(options);
|
|
142
|
-
}
|
|
143
|
-
destroy() {
|
|
144
|
-
var _a;
|
|
145
|
-
(_a = this.polyline) === null || _a === void 0 ? void 0 : _a.destroy();
|
|
146
|
-
super.destroy();
|
|
147
|
-
}
|
|
148
|
-
/** Called by wavesurfer, don't call manually */
|
|
149
|
-
onInit() {
|
|
150
|
-
if (!this.wavesurfer) {
|
|
151
|
-
throw Error('WaveSurfer is not initialized');
|
|
152
|
-
}
|
|
153
|
-
this.initWebAudio();
|
|
154
|
-
this.initSvg();
|
|
155
|
-
this.initFadeEffects();
|
|
156
|
-
this.subscriptions.push(this.wavesurfer.on('redraw', () => {
|
|
157
|
-
var _a;
|
|
158
|
-
const duration = (_a = this.wavesurfer) === null || _a === void 0 ? void 0 : _a.getDuration();
|
|
159
|
-
if (!duration)
|
|
160
|
-
return;
|
|
161
|
-
this.options.fadeInStart = this.options.fadeInStart || 0;
|
|
162
|
-
this.options.fadeOutEnd = this.options.fadeOutEnd || duration;
|
|
163
|
-
this.options.fadeInEnd = this.options.fadeInEnd || this.options.fadeInStart;
|
|
164
|
-
this.options.fadeOutStart = this.options.fadeOutStart || this.options.fadeOutEnd;
|
|
165
|
-
this.renderPolyline();
|
|
166
|
-
}));
|
|
167
|
-
}
|
|
168
|
-
initSvg() {
|
|
169
|
-
if (!this.wavesurfer)
|
|
170
|
-
return;
|
|
171
|
-
const wrapper = this.wavesurfer.getWrapper();
|
|
172
|
-
this.polyline = new Polyline(this.options, wrapper);
|
|
173
|
-
this.subscriptions.push(this.polyline.on('line-move', (relativeY) => {
|
|
174
|
-
this.setVolume(this.naturalVolume(relativeY));
|
|
175
|
-
}), this.polyline.on('point-move', (index, relativeX) => {
|
|
176
|
-
var _a;
|
|
177
|
-
const duration = ((_a = this.wavesurfer) === null || _a === void 0 ? void 0 : _a.getDuration()) || 0;
|
|
178
|
-
const newTime = relativeX * duration;
|
|
179
|
-
// Fade-in end point
|
|
180
|
-
if (index === 1) {
|
|
181
|
-
if (newTime < this.options.fadeInStart || newTime > this.options.fadeOutStart)
|
|
182
|
-
return;
|
|
183
|
-
this.options.fadeInEnd = newTime;
|
|
184
|
-
this.emit('fade-in-change', newTime);
|
|
185
|
-
}
|
|
186
|
-
else if (index === 2) {
|
|
187
|
-
// Fade-out start point
|
|
188
|
-
if (newTime > this.options.fadeOutEnd || newTime < this.options.fadeInEnd)
|
|
189
|
-
return;
|
|
190
|
-
this.options.fadeOutStart = newTime;
|
|
191
|
-
this.emit('fade-out-change', newTime);
|
|
192
|
-
}
|
|
193
|
-
this.renderPolyline();
|
|
194
|
-
}));
|
|
195
|
-
}
|
|
196
|
-
renderPolyline() {
|
|
197
|
-
if (!this.polyline || !this.wavesurfer)
|
|
198
|
-
return;
|
|
199
|
-
const duration = this.wavesurfer.getDuration();
|
|
200
|
-
if (!duration)
|
|
201
|
-
return;
|
|
202
|
-
this.polyline.update({
|
|
203
|
-
x1: this.options.fadeInStart / duration,
|
|
204
|
-
x2: this.options.fadeInEnd / duration,
|
|
205
|
-
x3: this.options.fadeOutStart / duration,
|
|
206
|
-
x4: this.options.fadeOutEnd / duration,
|
|
207
|
-
y: this.invertNaturalVolume(this.volume),
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
initWebAudio() {
|
|
211
|
-
var _a, _b;
|
|
212
|
-
const audio = (_a = this.wavesurfer) === null || _a === void 0 ? void 0 : _a.getMediaElement();
|
|
213
|
-
if (!audio)
|
|
214
|
-
return null;
|
|
215
|
-
this.volume = (_b = this.options.volume) !== null && _b !== void 0 ? _b : audio.volume;
|
|
216
|
-
// Create an AudioContext
|
|
217
|
-
const audioContext = new window.AudioContext();
|
|
218
|
-
// Create a GainNode for controlling the volume
|
|
219
|
-
this.gainNode = audioContext.createGain();
|
|
220
|
-
this.setGainValue();
|
|
221
|
-
// Create a MediaElementAudioSourceNode using the audio element
|
|
222
|
-
const source = audioContext.createMediaElementSource(audio);
|
|
223
|
-
// Connect the source to the GainNode, and the GainNode to the destination (speakers)
|
|
224
|
-
source.connect(this.gainNode);
|
|
225
|
-
this.gainNode.connect(audioContext.destination);
|
|
226
|
-
this.audioContext = audioContext;
|
|
227
|
-
}
|
|
228
|
-
invertNaturalVolume(value) {
|
|
229
|
-
if (value === 0)
|
|
230
|
-
return value;
|
|
231
|
-
const minValue = 0.0001;
|
|
232
|
-
const maxValue = 1;
|
|
233
|
-
const interpolatedValue = Math.pow((value - minValue) / (maxValue - minValue), 1 / this.naturalVolumeExponent);
|
|
234
|
-
return interpolatedValue;
|
|
235
|
-
}
|
|
236
|
-
naturalVolume(value) {
|
|
237
|
-
const minValue = 0.0001;
|
|
238
|
-
const maxValue = 1;
|
|
239
|
-
const interpolatedValue = minValue + (maxValue - minValue) * Math.pow(value, this.naturalVolumeExponent);
|
|
240
|
-
return interpolatedValue;
|
|
241
|
-
}
|
|
242
|
-
setGainValue() {
|
|
243
|
-
if (this.gainNode) {
|
|
244
|
-
this.gainNode.gain.value = this.volume;
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
initFadeEffects() {
|
|
248
|
-
if (!this.audioContext || !this.wavesurfer)
|
|
249
|
-
return;
|
|
250
|
-
const unsub = this.wavesurfer.on('timeupdate', (currentTime) => {
|
|
251
|
-
var _a;
|
|
252
|
-
if (!this.audioContext || !this.gainNode)
|
|
253
|
-
return;
|
|
254
|
-
if (!((_a = this.wavesurfer) === null || _a === void 0 ? void 0 : _a.isPlaying()))
|
|
255
|
-
return;
|
|
256
|
-
if (this.audioContext.state === 'suspended') {
|
|
257
|
-
this.audioContext.resume();
|
|
258
|
-
}
|
|
259
|
-
// Fade in
|
|
260
|
-
if (!this.isFadingIn && currentTime >= this.options.fadeInStart && currentTime <= this.options.fadeInEnd) {
|
|
261
|
-
this.isFadingIn = true;
|
|
262
|
-
// Set the initial gain (volume) to 0 (silent)
|
|
263
|
-
this.gainNode.gain.setValueAtTime(0, this.audioContext.currentTime);
|
|
264
|
-
// Set the target gain (volume) to 1 (full volume) over N seconds
|
|
265
|
-
this.gainNode.gain.linearRampToValueAtTime(this.volume, this.audioContext.currentTime + (this.options.fadeInEnd - currentTime));
|
|
266
|
-
return;
|
|
267
|
-
}
|
|
268
|
-
// Fade out
|
|
269
|
-
if (!this.isFadingOut && currentTime >= this.options.fadeOutStart && currentTime <= this.options.fadeOutEnd) {
|
|
270
|
-
this.isFadingOut = true;
|
|
271
|
-
/**
|
|
272
|
-
* Set the gain at this point in time to the current volume, otherwise
|
|
273
|
-
* the audio will start fading out from the fade-in point.
|
|
274
|
-
*/
|
|
275
|
-
this.gainNode.gain.setValueAtTime(this.volume, this.audioContext.currentTime);
|
|
276
|
-
// Set the target gain (volume) to 0 (silent) over N seconds
|
|
277
|
-
this.gainNode.gain.linearRampToValueAtTime(0, this.audioContext.currentTime + (this.options.fadeOutEnd - currentTime));
|
|
278
|
-
return;
|
|
279
|
-
}
|
|
280
|
-
// Reset fade in/out
|
|
281
|
-
let cancelRamp = false;
|
|
282
|
-
if (this.isFadingIn && (currentTime < this.options.fadeInStart || currentTime > this.options.fadeInEnd)) {
|
|
283
|
-
this.isFadingIn = false;
|
|
284
|
-
cancelRamp = true;
|
|
285
|
-
}
|
|
286
|
-
if (this.isFadingOut && (currentTime < this.options.fadeOutStart || currentTime >= this.options.fadeOutEnd)) {
|
|
287
|
-
this.isFadingOut = false;
|
|
288
|
-
cancelRamp = true;
|
|
289
|
-
}
|
|
290
|
-
if (cancelRamp) {
|
|
291
|
-
this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime);
|
|
292
|
-
this.setGainValue();
|
|
293
|
-
}
|
|
294
|
-
});
|
|
295
|
-
this.subscriptions.push(unsub);
|
|
296
|
-
}
|
|
297
|
-
/** Get the current audio volume */
|
|
298
|
-
getCurrentVolume() {
|
|
299
|
-
return this.gainNode ? this.gainNode.gain.value : this.volume;
|
|
300
|
-
}
|
|
301
|
-
/**
|
|
302
|
-
* Set the fade-in start time.
|
|
303
|
-
* @param time The time (in seconds) to set the fade-in start time to
|
|
304
|
-
* @param moveFadeInEnd Whether to move the drag point to the new time (default: false)
|
|
305
|
-
*/
|
|
306
|
-
setStartTime(time, moveFadeInEnd = false) {
|
|
307
|
-
if (moveFadeInEnd) {
|
|
308
|
-
const rampLength = this.options.fadeInEnd - this.options.fadeInStart;
|
|
309
|
-
this.options.fadeInEnd = time + rampLength;
|
|
310
|
-
}
|
|
311
|
-
this.options.fadeInStart = time;
|
|
312
|
-
this.renderPolyline();
|
|
313
|
-
}
|
|
314
|
-
/** Set the fade-out end time.
|
|
315
|
-
* @param time The time (in seconds) to set the fade-out end time to
|
|
316
|
-
* @param moveFadeOutStart Whether to move the drag point to the new time (default: false)
|
|
317
|
-
*/
|
|
318
|
-
setEndTime(time, moveFadeOutStart = false) {
|
|
319
|
-
if (moveFadeOutStart) {
|
|
320
|
-
const rampLength = this.options.fadeOutEnd - this.options.fadeOutStart;
|
|
321
|
-
this.options.fadeOutStart = time - rampLength;
|
|
322
|
-
}
|
|
323
|
-
this.options.fadeOutEnd = time;
|
|
324
|
-
this.renderPolyline();
|
|
325
|
-
}
|
|
326
|
-
/** Set the fade-in end time.
|
|
327
|
-
* @param time The time (in seconds) to set the fade-in end time to
|
|
328
|
-
*/
|
|
329
|
-
setFadeInEnd(time) {
|
|
330
|
-
this.options.fadeInEnd = time;
|
|
331
|
-
this.renderPolyline();
|
|
332
|
-
}
|
|
333
|
-
/** Set the fade-out start time.
|
|
334
|
-
* @param time The time (in seconds) to set the fade-out start time to
|
|
335
|
-
*/
|
|
336
|
-
setFadeOutStart(time) {
|
|
337
|
-
this.options.fadeOutStart = time;
|
|
338
|
-
this.renderPolyline();
|
|
339
|
-
}
|
|
340
|
-
/** Set the volume of the audio */
|
|
341
|
-
setVolume(volume) {
|
|
342
|
-
this.volume = volume;
|
|
343
|
-
this.setGainValue();
|
|
344
|
-
this.renderPolyline();
|
|
345
|
-
this.emit('volume-change', volume);
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
export default EnvelopePlugin;
|
|
1
|
+
class t{constructor(){this.listeners={}}on(t,e){return this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e),()=>this.un(t,e)}once(t,e){const i=this.on(t,e),n=this.on(t,(()=>{i(),n()}));return i}un(t,e){this.listeners[t]&&(e?this.listeners[t].delete(e):delete this.listeners[t])}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}}class e extends t{constructor(t){super(),this.subscriptions=[],this.options=t}onInit(){}init(t){this.wavesurfer=t,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((t=>t()))}}const i={fadeInStart:0,fadeOutEnd:0,fadeInEnd:0,fadeOutStart:0,lineWidth:4,lineColor:"rgba(0, 0, 255, 0.5)",dragPointSize:10,dragPointFill:"rgba(255, 255, 255, 0.8)",dragPointStroke:"rgba(255, 255, 255, 0.8)"};class n extends t{constructor(t,e){super(),this.top=0,this.padding=t.dragPointSize/2+1;const i=document.createElementNS("http://www.w3.org/2000/svg","svg");i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("viewBox","0 0 0 0"),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("style","position: absolute; left: 0; top: 0; z-index: 4; pointer-events: none;"),i.setAttribute("part","envelope"),this.svg=i;const n=document.createElementNS("http://www.w3.org/2000/svg","polyline");n.setAttribute("points","0,0 0,0 0,0 0,0"),n.setAttribute("stroke",t.lineColor),n.setAttribute("stroke-width",t.lineWidth),n.setAttribute("fill","none"),n.setAttribute("style","pointer-events: none;"),n.setAttribute("part","polyline"),i.appendChild(n);const s=document.createElementNS("http://www.w3.org/2000/svg","line");s.setAttribute("stroke","transparent"),s.setAttribute("stroke-width",(3*t.lineWidth).toString()),s.setAttribute("style","cursor: ns-resize; pointer-events: all;"),s.setAttribute("part","line"),i.appendChild(s),[0,1].forEach((()=>{const e=document.createElementNS("http://www.w3.org/2000/svg","circle");e.setAttribute("r",(t.dragPointSize/2).toString()),e.setAttribute("fill",t.dragPointFill),e.setAttribute("stroke",t.dragPointStroke||t.dragPointFill),e.setAttribute("stroke-width","2"),e.setAttribute("style","cursor: ew-resize; pointer-events: all;"),e.setAttribute("part","circle"),i.appendChild(e)})),e.appendChild(i);{const t=t=>{const e=this.top+t,{height:n}=i.viewBox.baseVal;if(e<-.5||e>n)return;const s=Math.min(1,Math.max(0,(n-e)/n));this.emit("line-move",s)},e=(t,e)=>{const s=n.points.getItem(t).x+e,{width:o}=i.viewBox.baseVal;this.emit("point-move",t,s/o)};this.makeDraggable(s,((e,i)=>t(i)));const o=this.svg.querySelectorAll("circle");Array.from(o).forEach(((t,i)=>{this.makeDraggable(t,(t=>e(i+1,t)))}))}}makeDraggable(t,e){!function(t,e,i,n,s=5){let o=()=>{};if(!t)return o;const r=r=>{if(2===r.button)return;r.preventDefault(),r.stopPropagation();let a=r.clientX,u=r.clientY,d=!1;const h=n=>{n.preventDefault(),n.stopPropagation();const o=n.clientX,r=n.clientY;if(d||Math.abs(o-a)>=s||Math.abs(r-u)>=s){const{left:n,top:s}=t.getBoundingClientRect();d||(d=!0,null==i||i(a-n,u-s)),e(o-a,r-u,o-n,r-s),a=o,u=r}},l=t=>{d&&(t.preventDefault(),t.stopPropagation())},p=()=>{d&&(null==n||n()),o()};document.addEventListener("pointermove",h),document.addEventListener("pointerup",p),document.addEventListener("pointerleave",p),document.addEventListener("click",l,!0),o=()=>{document.removeEventListener("pointermove",h),document.removeEventListener("pointerup",p),document.removeEventListener("pointerleave",p),setTimeout((()=>{document.removeEventListener("click",l,!0)}),10)}};t.addEventListener("pointerdown",r)}(t,e)}update({x1:t,x2:e,x3:i,x4:n,y:s}){const o=this.svg.clientWidth,r=this.svg.clientHeight;this.top=r-s*r;const a=Math.max(this.padding,Math.min(this.top,r-this.padding));this.svg.setAttribute("viewBox",`0 0 ${o} ${r}`);const u=this.svg.querySelector("polyline"),{points:d}=u;d.getItem(0).x=t*o,d.getItem(0).y=r,d.getItem(1).x=e*o,d.getItem(1).y=a,d.getItem(2).x=i*o,d.getItem(2).y=a,d.getItem(3).x=n*o,d.getItem(3).y=r;const h=this.svg.querySelector("line");h.setAttribute("x1",d.getItem(1).x.toString()),h.setAttribute("x2",d.getItem(2).x.toString()),h.setAttribute("y1",a.toString()),h.setAttribute("y2",a.toString());const l=this.svg.querySelectorAll("circle");Array.from(l).forEach(((t,e)=>{const i=d.getItem(e+1);t.setAttribute("cx",i.x.toString()),t.setAttribute("cy",i.y.toString())}))}destroy(){this.svg.remove()}}class s extends e{constructor(t){var e;super(t),this.polyline=null,this.audioContext=null,this.gainNode=null,this.volume=1,this.isFadingIn=!1,this.isFadingOut=!1,this.naturalVolumeExponent=1.5,this.options=Object.assign({},i,t),this.options.lineColor=this.options.lineColor||i.lineColor,this.options.dragPointFill=this.options.dragPointFill||i.dragPointFill,this.options.dragPointStroke=this.options.dragPointStroke||i.dragPointStroke,this.volume=null!==(e=this.options.volume)&&void 0!==e?e:1}static create(t){return new s(t)}destroy(){var t;null===(t=this.polyline)||void 0===t||t.destroy(),super.destroy()}onInit(){if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");this.initWebAudio(),this.initSvg(),this.initFadeEffects(),this.subscriptions.push(this.wavesurfer.on("redraw",(()=>{var t;const e=null===(t=this.wavesurfer)||void 0===t?void 0:t.getDuration();e&&(this.options.fadeInStart=this.options.fadeInStart||0,this.options.fadeOutEnd=this.options.fadeOutEnd||e,this.options.fadeInEnd=this.options.fadeInEnd||this.options.fadeInStart,this.options.fadeOutStart=this.options.fadeOutStart||this.options.fadeOutEnd,this.renderPolyline())})))}initSvg(){if(!this.wavesurfer)return;const t=this.wavesurfer.getWrapper();this.polyline=new n(this.options,t),this.subscriptions.push(this.polyline.on("line-move",(t=>{this.setVolume(this.naturalVolume(t))})),this.polyline.on("point-move",((t,e)=>{var i;const n=e*((null===(i=this.wavesurfer)||void 0===i?void 0:i.getDuration())||0);if(1===t){if(n<this.options.fadeInStart||n>this.options.fadeOutStart)return;this.options.fadeInEnd=n,this.emit("fade-in-change",n)}else if(2===t){if(n>this.options.fadeOutEnd||n<this.options.fadeInEnd)return;this.options.fadeOutStart=n,this.emit("fade-out-change",n)}this.renderPolyline()})))}renderPolyline(){if(!this.polyline||!this.wavesurfer)return;const t=this.wavesurfer.getDuration();t&&this.polyline.update({x1:this.options.fadeInStart/t,x2:this.options.fadeInEnd/t,x3:this.options.fadeOutStart/t,x4:this.options.fadeOutEnd/t,y:this.invertNaturalVolume(this.volume)})}initWebAudio(){var t,e;const i=null===(t=this.wavesurfer)||void 0===t?void 0:t.getMediaElement();if(!i)return null;this.volume=null!==(e=this.options.volume)&&void 0!==e?e:i.volume;const n=new window.AudioContext;this.gainNode=n.createGain(),this.setGainValue();n.createMediaElementSource(i).connect(this.gainNode),this.gainNode.connect(n.destination),this.audioContext=n}invertNaturalVolume(t){if(0===t)return t;const e=1e-4;return Math.pow((t-e)/.9999,1/this.naturalVolumeExponent)}naturalVolume(t){const e=1e-4;return e+.9999*Math.pow(t,this.naturalVolumeExponent)}setGainValue(){this.gainNode&&(this.gainNode.gain.value=this.volume)}initFadeEffects(){if(!this.audioContext||!this.wavesurfer)return;const t=this.wavesurfer.on("timeupdate",(t=>{var e;if(!this.audioContext||!this.gainNode)return;if(!(null===(e=this.wavesurfer)||void 0===e?void 0:e.isPlaying()))return;if("suspended"===this.audioContext.state&&this.audioContext.resume(),!this.isFadingIn&&t>=this.options.fadeInStart&&t<=this.options.fadeInEnd)return this.isFadingIn=!0,this.gainNode.gain.setValueAtTime(0,this.audioContext.currentTime),void this.gainNode.gain.linearRampToValueAtTime(this.volume,this.audioContext.currentTime+(this.options.fadeInEnd-t));if(!this.isFadingOut&&t>=this.options.fadeOutStart&&t<=this.options.fadeOutEnd)return this.isFadingOut=!0,this.gainNode.gain.setValueAtTime(this.volume,this.audioContext.currentTime),void this.gainNode.gain.linearRampToValueAtTime(0,this.audioContext.currentTime+(this.options.fadeOutEnd-t));let i=!1;this.isFadingIn&&(t<this.options.fadeInStart||t>this.options.fadeInEnd)&&(this.isFadingIn=!1,i=!0),this.isFadingOut&&(t<this.options.fadeOutStart||t>=this.options.fadeOutEnd)&&(this.isFadingOut=!1,i=!0),i&&(this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.setGainValue())}));this.subscriptions.push(t)}getCurrentVolume(){return this.gainNode?this.gainNode.gain.value:this.volume}setStartTime(t,e=!1){if(e){const e=this.options.fadeInEnd-this.options.fadeInStart;this.options.fadeInEnd=t+e}this.options.fadeInStart=t,this.renderPolyline()}setEndTime(t,e=!1){if(e){const e=this.options.fadeOutEnd-this.options.fadeOutStart;this.options.fadeOutStart=t-e}this.options.fadeOutEnd=t,this.renderPolyline()}setFadeInEnd(t){this.options.fadeInEnd=t,this.renderPolyline()}setFadeOutStart(t){this.options.fadeOutStart=t,this.renderPolyline()}setVolume(t){this.volume=t,this.setGainValue(),this.renderPolyline(),this.emit("volume-change",t)}}export{s as default};
|
package/dist/plugins/hover.js
CHANGED
|
@@ -1,103 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* The Hover plugin follows the mouse and shows a timestamp
|
|
3
|
-
*/
|
|
4
|
-
import BasePlugin from '../base-plugin.js';
|
|
5
|
-
const defaultOptions = {
|
|
6
|
-
lineWidth: 1,
|
|
7
|
-
labelSize: 11,
|
|
8
|
-
};
|
|
9
|
-
class HoverPlugin extends BasePlugin {
|
|
10
|
-
constructor(options) {
|
|
11
|
-
super(options || {});
|
|
12
|
-
this.unsubscribe = () => undefined;
|
|
13
|
-
this.onPointerMove = (e) => {
|
|
14
|
-
if (!this.wavesurfer)
|
|
15
|
-
return;
|
|
16
|
-
// Position
|
|
17
|
-
const bbox = this.wavesurfer.getWrapper().getBoundingClientRect();
|
|
18
|
-
const { width } = bbox;
|
|
19
|
-
const offsetX = e.clientX - bbox.left;
|
|
20
|
-
const relX = Math.min(1, Math.max(0, offsetX / width));
|
|
21
|
-
const posX = Math.min(width - this.options.lineWidth - 1, offsetX);
|
|
22
|
-
this.wrapper.style.transform = `translateX(${posX}px)`;
|
|
23
|
-
this.wrapper.style.opacity = '1';
|
|
24
|
-
// Timestamp
|
|
25
|
-
const duration = this.wavesurfer.getDuration() || 0;
|
|
26
|
-
this.label.textContent = this.formatTime(duration * relX);
|
|
27
|
-
const labelWidth = this.label.offsetWidth;
|
|
28
|
-
this.label.style.transform =
|
|
29
|
-
posX + labelWidth > width ? `translateX(-${labelWidth + this.options.lineWidth}px)` : '';
|
|
30
|
-
// Emit a hover event with the relative X position
|
|
31
|
-
this.emit('hover', relX);
|
|
32
|
-
};
|
|
33
|
-
this.onPointerLeave = () => {
|
|
34
|
-
this.wrapper.style.opacity = '0';
|
|
35
|
-
};
|
|
36
|
-
this.options = Object.assign({}, defaultOptions, options);
|
|
37
|
-
// Create the plugin elements
|
|
38
|
-
this.wrapper = document.createElement('div');
|
|
39
|
-
this.label = document.createElement('span');
|
|
40
|
-
this.wrapper.appendChild(this.label);
|
|
41
|
-
}
|
|
42
|
-
static create(options) {
|
|
43
|
-
return new HoverPlugin(options);
|
|
44
|
-
}
|
|
45
|
-
addUnits(value) {
|
|
46
|
-
const units = typeof value === 'number' ? 'px' : '';
|
|
47
|
-
return `${value}${units}`;
|
|
48
|
-
}
|
|
49
|
-
/** Called by wavesurfer, don't call manually */
|
|
50
|
-
onInit() {
|
|
51
|
-
if (!this.wavesurfer) {
|
|
52
|
-
throw Error('WaveSurfer is not initialized');
|
|
53
|
-
}
|
|
54
|
-
const wsOptions = this.wavesurfer.options;
|
|
55
|
-
const lineColor = this.options.lineColor || wsOptions.cursorColor || wsOptions.progressColor;
|
|
56
|
-
// Vertical line
|
|
57
|
-
this.wrapper.setAttribute('part', 'hover');
|
|
58
|
-
Object.assign(this.wrapper.style, {
|
|
59
|
-
position: 'absolute',
|
|
60
|
-
zIndex: 10,
|
|
61
|
-
left: 0,
|
|
62
|
-
top: 0,
|
|
63
|
-
height: '100%',
|
|
64
|
-
pointerEvents: 'none',
|
|
65
|
-
borderLeft: `${this.addUnits(this.options.lineWidth)} solid ${lineColor}`,
|
|
66
|
-
opacity: '0',
|
|
67
|
-
transition: 'opacity .1s ease-in',
|
|
68
|
-
});
|
|
69
|
-
// Timestamp label
|
|
70
|
-
this.label.setAttribute('part', 'hover-label');
|
|
71
|
-
Object.assign(this.label.style, {
|
|
72
|
-
display: 'block',
|
|
73
|
-
backgroundColor: this.options.labelBackground,
|
|
74
|
-
color: this.options.labelColor,
|
|
75
|
-
fontSize: `${this.addUnits(this.options.labelSize)}`,
|
|
76
|
-
transition: 'transform .1s ease-in',
|
|
77
|
-
padding: '2px 3px',
|
|
78
|
-
});
|
|
79
|
-
// Append the wrapper
|
|
80
|
-
const container = this.wavesurfer.getWrapper();
|
|
81
|
-
container.appendChild(this.wrapper);
|
|
82
|
-
// Attach pointer events
|
|
83
|
-
container.addEventListener('pointermove', this.onPointerMove);
|
|
84
|
-
container.addEventListener('pointerleave', this.onPointerLeave);
|
|
85
|
-
this.unsubscribe = () => {
|
|
86
|
-
container.removeEventListener('pointermove', this.onPointerMove);
|
|
87
|
-
container.removeEventListener('pointerleave', this.onPointerLeave);
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
formatTime(seconds) {
|
|
91
|
-
const minutes = Math.floor(seconds / 60);
|
|
92
|
-
const secondsRemainder = Math.floor(seconds) % 60;
|
|
93
|
-
const paddedSeconds = `0${secondsRemainder}`.slice(-2);
|
|
94
|
-
return `${minutes}:${paddedSeconds}`;
|
|
95
|
-
}
|
|
96
|
-
/** Unmount */
|
|
97
|
-
destroy() {
|
|
98
|
-
super.destroy();
|
|
99
|
-
this.unsubscribe();
|
|
100
|
-
this.wrapper.remove();
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
export default HoverPlugin;
|
|
1
|
+
class t{constructor(){this.listeners={}}on(t,e){return this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e),()=>this.un(t,e)}once(t,e){const s=this.on(t,e),i=this.on(t,(()=>{s(),i()}));return s}un(t,e){this.listeners[t]&&(e?this.listeners[t].delete(e):delete this.listeners[t])}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}}class e extends t{constructor(t){super(),this.subscriptions=[],this.options=t}onInit(){}init(t){this.wavesurfer=t,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((t=>t()))}}const s={lineWidth:1,labelSize:11};class i extends e{constructor(t){super(t||{}),this.unsubscribe=()=>{},this.onPointerMove=t=>{if(!this.wavesurfer)return;const e=this.wavesurfer.getWrapper().getBoundingClientRect(),{width:s}=e,i=t.clientX-e.left,r=Math.min(1,Math.max(0,i/s)),n=Math.min(s-this.options.lineWidth-1,i);this.wrapper.style.transform=`translateX(${n}px)`,this.wrapper.style.opacity="1";const o=this.wavesurfer.getDuration()||0;this.label.textContent=this.formatTime(o*r);const a=this.label.offsetWidth;this.label.style.transform=n+a>s?`translateX(-${a+this.options.lineWidth}px)`:"",this.emit("hover",r)},this.onPointerLeave=()=>{this.wrapper.style.opacity="0"},this.options=Object.assign({},s,t),this.wrapper=document.createElement("div"),this.label=document.createElement("span"),this.wrapper.appendChild(this.label)}static create(t){return new i(t)}addUnits(t){return`${t}${"number"==typeof t?"px":""}`}onInit(){if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");const t=this.wavesurfer.options,e=this.options.lineColor||t.cursorColor||t.progressColor;this.wrapper.setAttribute("part","hover"),Object.assign(this.wrapper.style,{position:"absolute",zIndex:10,left:0,top:0,height:"100%",pointerEvents:"none",borderLeft:`${this.addUnits(this.options.lineWidth)} solid ${e}`,opacity:"0",transition:"opacity .1s ease-in"}),this.label.setAttribute("part","hover-label"),Object.assign(this.label.style,{display:"block",backgroundColor:this.options.labelBackground,color:this.options.labelColor,fontSize:`${this.addUnits(this.options.labelSize)}`,transition:"transform .1s ease-in",padding:"2px 3px"});const s=this.wavesurfer.getWrapper();s.appendChild(this.wrapper),s.addEventListener("pointermove",this.onPointerMove),s.addEventListener("pointerleave",this.onPointerLeave),this.unsubscribe=()=>{s.removeEventListener("pointermove",this.onPointerMove),s.removeEventListener("pointerleave",this.onPointerLeave)}}formatTime(t){return`${Math.floor(t/60)}:${`0${Math.floor(t)%60}`.slice(-2)}`}destroy(){super.destroy(),this.unsubscribe(),this.wrapper.remove()}}export{i as default};
|
package/dist/plugins/minimap.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";class t{constructor(){this.listeners={}}on(t,e){return this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e),()=>this.un(t,e)}once(t,e){const i=this.on(t,e),s=this.on(t,(()=>{i(),s()}));return i}un(t,e){this.listeners[t]&&(e?this.listeners[t].delete(e):delete this.listeners[t])}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}}class e extends t{constructor(t){super(),this.subscriptions=[],this.options=t}onInit(){}init(t){this.wavesurfer=t,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((t=>t()))}}function i(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;const s={decode:function(t,e){return i(this,void 0,void 0,(function*(){const i=new AudioContext({sampleRate:e}),s=i.decodeAudioData(t);return s.finally((()=>i.close())),s}))},createBuffer:function(t,e){return"number"==typeof t[0]&&(t=[t]),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}}};const n={fetchBlob:function(t,e,s){var n,r;return i(this,void 0,void 0,(function*(){const o=yield fetch(t,s);{const t=null===(n=o.clone().body)||void 0===n?void 0:n.getReader(),s=Number(null===(r=o.headers)||void 0===r?void 0:r.get("Content-Length"));let a=0;const h=(n,r)=>i(this,void 0,void 0,(function*(){if(n)return;a+=(null==r?void 0:r.length)||0;const i=Math.round(a/s*100);return e(i),null==t?void 0:t.read().then((({done:t,value:e})=>h(t,e)))}));null==t||t.read().then((({done:t,value:e})=>h(t,e)))}return o.blob()}))}};class r extends t{constructor(t){super(),t.media?this.media=t.media:this.media=document.createElement("audio"),t.mediaControls&&(this.media.controls=!0),t.autoplay&&(this.media.autoplay=!0),null!=t.playbackRate&&this.onceMediaEvent("canplay",(()=>{null!=t.playbackRate&&(this.media.playbackRate=t.playbackRate)}))}onMediaEvent(t,e,i){return this.media.addEventListener(t,e,i),()=>this.media.removeEventListener(t,e)}onceMediaEvent(t,e){return this.onMediaEvent(t,e,{once:!0})}getSrc(){return this.media.currentSrc||this.media.src||""}revokeSrc(){const t=this.getSrc();t.startsWith("blob:")&&URL.revokeObjectURL(t)}setSrc(t,e){if(this.getSrc()===t)return;this.revokeSrc();const i=e instanceof Blob?URL.createObjectURL(e):t;this.media.src=i,this.media.load()}destroy(){this.media.pause(),this.revokeSrc(),this.media.src="",this.media.load()}play(){return this.media.play()}pause(){this.media.pause()}isPlaying(){return this.media.currentTime>0&&!this.media.paused&&!this.media.ended}setTime(t){this.media.currentTime=t}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}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 o extends t{constructor(t,e){let i;if(super(),this.timeouts=[],this.isScrolling=!1,this.audioData=null,this.resizeObserver=null,this.isDragging=!1,this.options=t,"string"==typeof t.container?i=document.querySelector(t.container):t.container instanceof HTMLElement&&(i=t.container),!i)throw new Error("Container not found");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()}initEvents(){this.wrapper.addEventListener("click",(t=>{const e=this.wrapper.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.emit("click",i)})),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)}));const t=this.createDelay(100);this.resizeObserver=new ResizeObserver((()=>{t((()=>this.reRender()))})),this.resizeObserver.observe(this.scrollContainer)}initDrag(){!function(t,e,i,s,n=5){let r=()=>{};if(!t)return r;const o=o=>{if(2===o.button)return;o.preventDefault(),o.stopPropagation();let a=o.clientX,h=o.clientY,l=!1;const d=s=>{s.preventDefault(),s.stopPropagation();const r=s.clientX,o=s.clientY;if(l||Math.abs(r-a)>=n||Math.abs(o-h)>=n){const{left:s,top:n}=t.getBoundingClientRect();l||(l=!0,null==i||i(a-s,h-n)),e(r-a,o-h,r-s,o-n),a=r,h=o}},c=t=>{l&&(t.preventDefault(),t.stopPropagation())},u=()=>{l&&(null==s||s()),r()};document.addEventListener("pointermove",d),document.addEventListener("pointerup",u),document.addEventListener("pointerleave",u),document.addEventListener("click",c,!0),r=()=>{document.removeEventListener("pointermove",d),document.removeEventListener("pointerup",u),document.removeEventListener("pointerleave",u),setTimeout((()=>{document.removeEventListener("click",c,!0)}),10)}};t.addEventListener("pointerdown",o)}(this.wrapper,((t,e,i)=>{this.emit("drag",Math.max(0,Math.min(1,i/this.wrapper.clientWidth)))}),(()=>this.isDragging=!0),(()=>this.isDragging=!1))}getHeight(){return null==this.options.height?128:isNaN(Number(this.options.height))?"auto"===this.options.height&&this.parent.clientHeight||128:Number(this.options.height)}initHtml(){const t=document.createElement("div"),e=t.attachShadow({mode:"open"});return e.innerHTML=`\n <style>\n :host {\n user-select: none;\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 touch-action: none;\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()}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">\n <div class="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){this.options=t,this.reRender()}getWrapper(){return this.wrapper}getScroll(){return this.scrollContainer.scrollLeft}destroy(){var t;this.container.remove(),null===(t=this.resizeObserver)||void 0===t||t.disconnect()}createDelay(t=10){const e={};return this.timeouts.push(e),i=>{e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(i,t)}}convertColorValues(t){if(!Array.isArray(t))return t||"";if(t.length<2)return t[0]||"";const e=document.createElement("canvas"),i=e.getContext("2d").createLinearGradient(0,0,0,e.height),s=1/(t.length-1);return t.forEach(((t,e)=>{const n=e*s;i.addColorStop(n,t)})),i}renderBars(t,e,i){if(i.fillStyle=this.convertColorValues(e.waveColor),e.renderFunction)return void e.renderFunction(t,i);const s=t[0],n=t[1]||t[0],r=s.length,o=window.devicePixelRatio||1,{width:a,height:h}=i.canvas,l=h/2,d=e.barHeight||1,c=e.barWidth?e.barWidth*o:1,u=e.barGap?e.barGap*o:e.barWidth?c/2:0,p=e.barRadius||0,m=a/(c+u)/r;let v=1;if(e.normalize){v=0;for(let t=0;t<r;t++){const e=Math.abs(s[t]);e>v&&(v=e)}}const g=l/v*d,f=p&&"roundRect"in i?"roundRect":"rect";i.beginPath();let y=0,b=0,w=0;for(let t=0;t<=r;t++){const r=Math.round(t*m);if(r>y){const t=Math.round(b*g),s=t+Math.round(w*g)||1;let n=l-t;"top"===e.barAlign?n=0:"bottom"===e.barAlign&&(n=h-s),i[f](y*(c+u),n,c,s,p),y=r,b=0,w=0}const o=Math.abs(s[t]||0),a=Math.abs(n[t]||0);o>b&&(b=o),a>w&&(w=a)}i.fill(),i.closePath()}renderSingleCanvas(t,e,i,s,n,r,o,a){const h=window.devicePixelRatio||1,l=document.createElement("canvas"),d=t[0].length;l.width=Math.round(i*(r-n)/d),l.height=s*h,l.style.width=`${Math.floor(l.width/h)}px`,l.style.height=`${s}px`,l.style.left=`${Math.floor(n*i/h/d)}px`,o.appendChild(l);const c=l.getContext("2d");this.renderBars(t.map((t=>t.slice(n,r))),e,c);const u=l.cloneNode();a.appendChild(u);const p=u.getContext("2d");l.width>0&&l.height>0&&p.drawImage(l,0,0),p.globalCompositeOperation="source-in",p.fillStyle=this.convertColorValues(e.progressColor),p.fillRect(0,0,l.width,l.height)}renderWaveform(t,e,i){const s=document.createElement("div"),n=this.getHeight();s.style.height=`${n}px`,this.canvasWrapper.style.minHeight=`${n}px`,this.canvasWrapper.appendChild(s);const r=s.cloneNode();this.progressWrapper.appendChild(r);const{scrollLeft:a,scrollWidth:h,clientWidth:l}=this.scrollContainer,d=t[0].length,c=d/h;let u=Math.min(o.MAX_CANVAS_WIDTH,l);if(e.barWidth||e.barGap){const t=e.barWidth||.5,i=t+(e.barGap||t/2);u%i!=0&&(u=Math.floor(u/i)*i)}const p=Math.floor(Math.abs(a)*c),m=Math.floor(p+u*c),v=m-p,g=(o,a)=>{this.renderSingleCanvas(t,e,i,n,Math.max(0,o),Math.min(a,d),s,r)},f=this.createDelay(),y=this.createDelay(),b=(t,e)=>{g(t,e),t>0&&f((()=>{b(t-v,e-v)}))},w=(t,e)=>{g(t,e),e<d&&y((()=>{w(t+v,e+v)}))};b(p,m),m<d&&w(m,m+v)}render(t){this.timeouts.forEach((t=>t.timeout&&clearTimeout(t.timeout))),this.timeouts=[],this.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="",this.wrapper.style.width="";const e=window.devicePixelRatio||1,i=this.scrollContainer.clientWidth,s=Math.ceil(t.duration*(this.options.minPxPerSec||0));this.isScrolling=s>i;const n=this.options.fillParent&&!this.isScrolling,r=(n?i:s)*e;if(this.wrapper.style.width=n?"100%":`${s}px`,this.scrollContainer.style.overflowX=this.isScrolling?"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.options.splitChannels)for(let e=0;e<t.numberOfChannels;e++){const i=Object.assign(Object.assign({},this.options),this.options.splitChannels[e]);this.renderWaveform([t.getChannelData(e)],i,r)}else{const e=[t.getChannelData(0)];t.numberOfChannels>1&&e.push(t.getChannelData(1)),this.renderWaveform(e,this.options,r)}this.audioData=t,this.emit("render")}reRender(){if(!this.audioData)return;const t=this.progressWrapper.clientWidth;this.render(this.audioData);const e=this.progressWrapper.clientWidth;this.scrollContainer.scrollLeft+=e-t}zoom(t){this.options.minPxPerSec=t,this.reRender()}scrollIntoView(t,e=!1){const{clientWidth:i,scrollLeft:s,scrollWidth:n}=this.scrollContainer,r=n*t,o=i/2;if(r>s+(e&&this.options.autoCenter&&!this.isDragging?o:i)||r<s)if(this.options.autoCenter&&!this.isDragging){const t=o/20;r-(s+o)>=t&&r<s+i?this.scrollContainer.scrollLeft+=t:this.scrollContainer.scrollLeft=r-o}else if(this.isDragging){const t=10;this.scrollContainer.scrollLeft=r<s?r-t:r-i+t}else this.scrollContainer.scrollLeft=r;{const{scrollLeft:t}=this.scrollContainer,e=t/n,s=(t+i)/n;this.emit("scroll",e,s)}}renderProgress(t,e){isNaN(t)||(this.progressWrapper.style.width=100*t+"%",this.cursor.style.left=100*t+"%",this.cursor.style.marginLeft=100===Math.round(100*t)?`-${this.options.cursorWidth}px`:"",this.isScrolling&&this.options.autoScroll&&this.scrollIntoView(t,e))}}o.MAX_CANVAS_WIDTH=4e3;class a extends t{constructor(){super(...arguments),this.unsubscribe=()=>{}}start(){this.unsubscribe=this.on("tick",(()=>{requestAnimationFrame((()=>{this.emit("tick")}))})),this.emit("tick")}stop(){this.unsubscribe()}destroy(){this.unsubscribe()}}const h={waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,autoScroll:!0,autoCenter:!0,sampleRate:8e3};class l extends r{static create(t){return new l(t)}constructor(t){var e,i;super({media:t.media,mediaControls:t.mediaControls,autoplay:t.autoplay,playbackRate:t.audioRate}),this.plugins=[],this.decodedData=null,this.duration=null,this.subscriptions=[],this.options=Object.assign({},h,t),this.timer=new a;const s=t.media?void 0:this.getMediaElement();this.renderer=new o(this.options,s),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initPlugins();const n=this.options.url||(null===(e=this.options.media)||void 0===e?void 0:e.currentSrc)||(null===(i=this.options.media)||void 0===i?void 0:i.src);n&&this.load(n,this.options.peaks,this.options.duration)}initTimerEvents(){this.subscriptions.push(this.timer.on("tick",(()=>{const t=this.getCurrentTime();this.renderer.renderProgress(t/this.getDuration(),!0),this.emit("timeupdate",t),this.emit("audioprocess",t)})))}initPlayerEvents(){this.subscriptions.push(this.onMediaEvent("timeupdate",(()=>{const t=this.getCurrentTime();this.renderer.renderProgress(t/this.getDuration(),this.isPlaying()),this.emit("timeupdate",t)})),this.onMediaEvent("play",(()=>{this.emit("play"),this.timer.start()})),this.onMediaEvent("pause",(()=>{this.emit("pause"),this.timer.stop()})),this.onMediaEvent("ended",(()=>{this.emit("finish")})),this.onMediaEvent("seeking",(()=>{this.emit("seeking",this.getCurrentTime())})))}initRendererEvents(){this.subscriptions.push(this.renderer.on("click",(t=>{this.options.interact&&(this.seekTo(t),this.emit("interaction",this.getCurrentTime()),this.emit("click",t))})),this.renderer.on("scroll",((t,e)=>{const i=this.getDuration();this.emit("scroll",t*i,e*i)})),this.renderer.on("render",(()=>{this.emit("redraw")})));{let t;this.subscriptions.push(this.renderer.on("drag",(e=>{this.options.interact&&(this.renderer.renderProgress(e),clearTimeout(t),t=setTimeout((()=>{this.seekTo(e)}),this.isPlaying()?0:200),this.emit("interaction",e*this.getDuration()),this.emit("drag",e))})))}}initPlugins(){var t;(null===(t=this.options.plugins)||void 0===t?void 0:t.length)&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}setOptions(t){this.options=Object.assign({},this.options,t),this.renderer.setOptions(this.options),t.audioRate&&this.setPlaybackRate(t.audioRate),null!=t.mediaControls&&(this.getMediaElement().controls=t.mediaControls)}registerPlugin(t){return t.init(this),this.plugins.push(t),this.subscriptions.push(t.once("destroy",(()=>{this.plugins=this.plugins.filter((e=>e!==t))}))),t}getWrapper(){return this.renderer.getWrapper()}getScroll(){return this.renderer.getScroll()}getActivePlugins(){return this.plugins}loadAudio(t,e,r,o){return i(this,void 0,void 0,(function*(){if(this.emit("load",t),this.isPlaying()&&this.pause(),this.decodedData=null,this.duration=null,!e&&!r){const i=t=>this.emit("loading",t);e=yield n.fetchBlob(t,i,this.options.fetchParams)}if(this.setSrc(t,e),this.duration=(yield Promise.resolve(o||this.getDuration()))||(yield new Promise((t=>{this.onceMediaEvent("loadedmetadata",(()=>t(this.getDuration())))})))||(yield Promise.resolve(0)),r)this.decodedData=s.createBuffer(r,this.duration);else if(e){const t=yield e.arrayBuffer();this.decodedData=yield s.decode(t,this.options.sampleRate),0!==this.duration&&this.duration!==1/0||(this.duration=this.decodedData.duration)}this.emit("decode",this.duration),this.decodedData&&this.renderer.render(this.decodedData),this.emit("ready",this.duration)}))}load(t,e,s){return i(this,void 0,void 0,(function*(){this.loadAudio(t,void 0,e,s)}))}loadBlob(t,e,s){return i(this,void 0,void 0,(function*(){this.loadAudio("blob",t,e,s)}))}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=1,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=Math.min(s.length,e),o=s.length/r,a=[];for(let t=0;t<r;t++){const e=s[Math.round(t*o)];a.push(Math.round(e*i)/i)}n.push(a)}return n}getDuration(){return null!==this.duration?this.duration:super.getDuration()}toggleInteraction(t){this.options.interact=t}seekTo(t){const e=this.getDuration()*t;this.setTime(e)}playPause(){return i(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)}destroy(){this.emit("destroy"),this.plugins.forEach((t=>t.destroy())),this.subscriptions.forEach((t=>t())),this.timer.destroy(),this.renderer.destroy(),super.destroy()}}const d={height:50,overlayColor:"rgba(100, 100, 100, 0.1)",insertPosition:"afterend"};class c extends e{constructor(t){super(t),this.miniWavesurfer=null,this.container=null,this.options=Object.assign({},d,t),this.minimapWrapper=this.initMinimapWrapper(),this.overlay=this.initOverlay()}static create(t){return new c(t)}onInit(){var t,e;if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");this.options.container?("string"==typeof this.options.container?this.container=document.querySelector(this.options.container):this.options.container instanceof HTMLElement&&(this.container=this.options.container),null===(t=this.container)||void 0===t||t.appendChild(this.minimapWrapper)):(this.container=this.wavesurfer.getWrapper().parentElement,null===(e=this.container)||void 0===e||e.insertAdjacentElement(this.options.insertPosition,this.minimapWrapper)),this.initWaveSurferEvents()}initMinimapWrapper(){const t=document.createElement("div");return t.style.position="relative",t.setAttribute("part","minimap"),t}initOverlay(){const t=document.createElement("div");return t.setAttribute("style","position: absolute; z-index: 2; left: 0; top: 0; bottom: 0; transition: left 100ms ease-out; pointer-events: none;"),t.style.backgroundColor=this.options.overlayColor,this.minimapWrapper.appendChild(t),t}initMinimap(){if(this.miniWavesurfer&&(this.miniWavesurfer.destroy(),this.miniWavesurfer=null),!this.wavesurfer)return;const t=this.wavesurfer.getDecodedData(),e=this.wavesurfer.getMediaElement();t&&e&&(this.miniWavesurfer=l.create(Object.assign(Object.assign({},this.options),{container:this.minimapWrapper,minPxPerSec:0,fillParent:!0,media:e,peaks:[t.getChannelData(0)],duration:t.duration})),this.subscriptions.push(this.miniWavesurfer.on("ready",(()=>{this.emit("ready")})),this.miniWavesurfer.on("interaction",(()=>{this.emit("interaction")}))))}getOverlayWidth(){var t;const e=(null===(t=this.wavesurfer)||void 0===t?void 0:t.getWrapper().clientWidth)||1;return Math.round(this.minimapWrapper.clientWidth/e*100)}onRedraw(){const t=this.getOverlayWidth();this.overlay.style.width=`${t}%`}onScroll(t){if(!this.wavesurfer)return;const e=this.wavesurfer.getDuration();this.overlay.style.left=t/e*100+"%"}initWaveSurferEvents(){this.wavesurfer&&this.subscriptions.push(this.wavesurfer.on("decode",(()=>{this.initMinimap()})),this.wavesurfer.on("scroll",(t=>{this.onScroll(t)})),this.wavesurfer.on("redraw",(()=>{this.onRedraw()})))}destroy(){var t;null===(t=this.miniWavesurfer)||void 0===t||t.destroy(),this.minimapWrapper.remove(),super.destroy()}}module.exports=c;
|
|
1
|
+
"use strict";class t{constructor(){this.listeners={}}on(t,e){return this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e),()=>this.un(t,e)}once(t,e){const i=this.on(t,e),s=this.on(t,(()=>{i(),s()}));return i}un(t,e){this.listeners[t]&&(e?this.listeners[t].delete(e):delete this.listeners[t])}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}}class e extends t{constructor(t){super(),this.subscriptions=[],this.options=t}onInit(){}init(t){this.wavesurfer=t,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((t=>t()))}}function i(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;const s={decode:function(t,e){return i(this,void 0,void 0,(function*(){const i=new AudioContext({sampleRate:e}),s=i.decodeAudioData(t);return s.finally((()=>i.close())),s}))},createBuffer:function(t,e){return"number"==typeof t[0]&&(t=[t]),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}}};const n={fetchBlob:function(t,e,s){var n,r;return i(this,void 0,void 0,(function*(){const o=yield fetch(t,s);{const t=null===(n=o.clone().body)||void 0===n?void 0:n.getReader(),s=Number(null===(r=o.headers)||void 0===r?void 0:r.get("Content-Length"));let a=0;const h=(n,r)=>i(this,void 0,void 0,(function*(){if(n)return;a+=(null==r?void 0:r.length)||0;const i=Math.round(a/s*100);return e(i),null==t?void 0:t.read().then((({done:t,value:e})=>h(t,e)))}));null==t||t.read().then((({done:t,value:e})=>h(t,e)))}return o.blob()}))}};class r extends t{constructor(t){super(),t.media?this.media=t.media:this.media=document.createElement("audio"),t.mediaControls&&(this.media.controls=!0),t.autoplay&&(this.media.autoplay=!0),null!=t.playbackRate&&this.onceMediaEvent("canplay",(()=>{null!=t.playbackRate&&(this.media.playbackRate=t.playbackRate)}))}onMediaEvent(t,e,i){return this.media.addEventListener(t,e,i),()=>this.media.removeEventListener(t,e)}onceMediaEvent(t,e){return this.onMediaEvent(t,e,{once:!0})}getSrc(){return this.media.currentSrc||this.media.src||""}revokeSrc(){const t=this.getSrc();t.startsWith("blob:")&&URL.revokeObjectURL(t)}setSrc(t,e){if(this.getSrc()===t)return;this.revokeSrc();const i=e instanceof Blob?URL.createObjectURL(e):t;this.media.src=i,this.media.load()}destroy(){this.media.pause(),this.revokeSrc(),this.media.src="",this.media.load()}play(){return this.media.play()}pause(){this.media.pause()}isPlaying(){return this.media.currentTime>0&&!this.media.paused&&!this.media.ended}setTime(t){this.media.currentTime=t}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}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 o extends t{constructor(t,e){let i;if(super(),this.timeouts=[],this.isScrolling=!1,this.audioData=null,this.resizeObserver=null,this.isDragging=!1,this.options=t,"string"==typeof t.container?i=document.querySelector(t.container):t.container instanceof HTMLElement&&(i=t.container),!i)throw new Error("Container not found");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()}initEvents(){this.wrapper.addEventListener("click",(t=>{const e=this.wrapper.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.emit("click",i)})),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)}));const t=this.createDelay(100);this.resizeObserver=new ResizeObserver((()=>{t((()=>this.reRender()))})),this.resizeObserver.observe(this.scrollContainer)}initDrag(){!function(t,e,i,s,n=5){let r=()=>{};if(!t)return r;const o=o=>{if(2===o.button)return;o.preventDefault(),o.stopPropagation();let a=o.clientX,h=o.clientY,l=!1;const d=s=>{s.preventDefault(),s.stopPropagation();const r=s.clientX,o=s.clientY;if(l||Math.abs(r-a)>=n||Math.abs(o-h)>=n){const{left:s,top:n}=t.getBoundingClientRect();l||(l=!0,null==i||i(a-s,h-n)),e(r-a,o-h,r-s,o-n),a=r,h=o}},c=t=>{l&&(t.preventDefault(),t.stopPropagation())},u=()=>{l&&(null==s||s()),r()};document.addEventListener("pointermove",d),document.addEventListener("pointerup",u),document.addEventListener("pointerleave",u),document.addEventListener("click",c,!0),r=()=>{document.removeEventListener("pointermove",d),document.removeEventListener("pointerup",u),document.removeEventListener("pointerleave",u),setTimeout((()=>{document.removeEventListener("click",c,!0)}),10)}};t.addEventListener("pointerdown",o)}(this.wrapper,((t,e,i)=>{this.emit("drag",Math.max(0,Math.min(1,i/this.wrapper.clientWidth)))}),(()=>this.isDragging=!0),(()=>this.isDragging=!1))}getHeight(){return null==this.options.height?128:isNaN(Number(this.options.height))?"auto"===this.options.height&&this.parent.clientHeight||128:Number(this.options.height)}initHtml(){const t=document.createElement("div"),e=t.attachShadow({mode:"open"});return e.innerHTML=`\n <style>\n :host {\n user-select: none;\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 touch-action: none;\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()}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">\n <div class="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){this.options=t,this.reRender()}getWrapper(){return this.wrapper}getScroll(){return this.scrollContainer.scrollLeft}destroy(){var t;this.container.remove(),null===(t=this.resizeObserver)||void 0===t||t.disconnect()}createDelay(t=10){const e={};return this.timeouts.push(e),i=>{e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(i,t)}}convertColorValues(t){if(!Array.isArray(t))return t||"";if(t.length<2)return t[0]||"";const e=document.createElement("canvas"),i=e.getContext("2d").createLinearGradient(0,0,0,e.height),s=1/(t.length-1);return t.forEach(((t,e)=>{const n=e*s;i.addColorStop(n,t)})),i}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=window.devicePixelRatio||1,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,v=p&&"roundRect"in i?"roundRect":"rect";i.beginPath();let g=0,f=0,y=0;for(let t=0;t<=o;t++){const o=Math.round(t*m);if(o>g){const t=Math.round(f*l*s),n=t+Math.round(y*l*s)||1;let r=l-t;"top"===e.barAlign?r=0:"bottom"===e.barAlign&&(r=h-n),i[v](g*(c+u),r,c,n,p),g=o,f=0,y=0}const a=Math.abs(n[t]||0),d=Math.abs(r[t]||0);a>f&&(f=a),d>y&&(y=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?1/e:1}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,a){const h=window.devicePixelRatio||1,l=document.createElement("canvas"),d=t[0].length;l.width=Math.round(i*(r-n)/d),l.height=s*h,l.style.width=`${Math.floor(l.width/h)}px`,l.style.height=`${s}px`,l.style.left=`${Math.floor(n*i/h/d)}px`,o.appendChild(l);const c=l.getContext("2d");this.renderWaveform(t.map((t=>t.slice(n,r))),e,c);const u=l.cloneNode();a.appendChild(u);const p=u.getContext("2d");l.width>0&&l.height>0&&p.drawImage(l,0,0),p.globalCompositeOperation="source-in",p.fillStyle=this.convertColorValues(e.progressColor),p.fillRect(0,0,l.width,l.height)}renderChannel(t,e,i){const s=document.createElement("div"),n=this.getHeight();s.style.height=`${n}px`,this.canvasWrapper.style.minHeight=`${n}px`,this.canvasWrapper.appendChild(s);const r=s.cloneNode();this.progressWrapper.appendChild(r);const{scrollLeft:a,scrollWidth:h,clientWidth:l}=this.scrollContainer,d=t[0].length,c=d/h;let u=Math.min(o.MAX_CANVAS_WIDTH,l);if(e.barWidth||e.barGap){const t=e.barWidth||.5,i=t+(e.barGap||t/2);u%i!=0&&(u=Math.floor(u/i)*i)}const p=Math.floor(Math.abs(a)*c),m=Math.floor(p+u*c),v=m-p,g=(o,a)=>{this.renderSingleCanvas(t,e,i,n,Math.max(0,o),Math.min(a,d),s,r)},f=this.createDelay(),y=this.createDelay(),b=(t,e)=>{g(t,e),t>0&&f((()=>{b(t-v,e-v)}))},w=(t,e)=>{g(t,e),e<d&&y((()=>{w(t+v,e+v)}))};b(p,m),m<d&&w(m,m+v)}render(t){this.timeouts.forEach((t=>t.timeout&&clearTimeout(t.timeout))),this.timeouts=[],this.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="",this.wrapper.style.width="";const e=window.devicePixelRatio||1,i=this.scrollContainer.clientWidth,s=Math.ceil(t.duration*(this.options.minPxPerSec||0));this.isScrolling=s>i;const n=this.options.fillParent&&!this.isScrolling,r=(n?i:s)*e;if(this.wrapper.style.width=n?"100%":`${s}px`,this.scrollContainer.style.overflowX=this.isScrolling?"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.options.splitChannels)for(let e=0;e<t.numberOfChannels;e++){const i=Object.assign(Object.assign({},this.options),this.options.splitChannels[e]);this.renderChannel([t.getChannelData(e)],i,r)}else{const e=[t.getChannelData(0)];t.numberOfChannels>1&&e.push(t.getChannelData(1)),this.renderChannel(e,this.options,r)}this.audioData=t,this.emit("render")}reRender(){if(!this.audioData)return;const t=this.progressWrapper.clientWidth;this.render(this.audioData);const e=this.progressWrapper.clientWidth;this.scrollContainer.scrollLeft+=e-t}zoom(t){this.options.minPxPerSec=t,this.reRender()}scrollIntoView(t,e=!1){const{clientWidth:i,scrollLeft:s,scrollWidth:n}=this.scrollContainer,r=n*t,o=i/2;if(r>s+(e&&this.options.autoCenter&&!this.isDragging?o:i)||r<s)if(this.options.autoCenter&&!this.isDragging){const t=o/20;r-(s+o)>=t&&r<s+i?this.scrollContainer.scrollLeft+=t:this.scrollContainer.scrollLeft=r-o}else if(this.isDragging){const t=10;this.scrollContainer.scrollLeft=r<s?r-t:r-i+t}else this.scrollContainer.scrollLeft=r;{const{scrollLeft:t}=this.scrollContainer,e=t/n,s=(t+i)/n;this.emit("scroll",e,s)}}renderProgress(t,e){isNaN(t)||(this.progressWrapper.style.width=100*t+"%",this.cursor.style.left=100*t+"%",this.cursor.style.marginLeft=100===Math.round(100*t)?`-${this.options.cursorWidth}px`:"",this.isScrolling&&this.options.autoScroll&&this.scrollIntoView(t,e))}}o.MAX_CANVAS_WIDTH=4e3;class a extends t{constructor(){super(...arguments),this.unsubscribe=()=>{}}start(){this.unsubscribe=this.on("tick",(()=>{requestAnimationFrame((()=>{this.emit("tick")}))})),this.emit("tick")}stop(){this.unsubscribe()}destroy(){this.unsubscribe()}}const h={waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,autoScroll:!0,autoCenter:!0,sampleRate:8e3};class l extends r{static create(t){return new l(t)}constructor(t){var e,i;super({media:t.media,mediaControls:t.mediaControls,autoplay:t.autoplay,playbackRate:t.audioRate}),this.plugins=[],this.decodedData=null,this.subscriptions=[],this.options=Object.assign({},h,t),this.timer=new a;const s=t.media?void 0:this.getMediaElement();this.renderer=new o(this.options,s),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initPlugins();const n=this.options.url||(null===(e=this.options.media)||void 0===e?void 0:e.currentSrc)||(null===(i=this.options.media)||void 0===i?void 0:i.src);n&&this.load(n,this.options.peaks,this.options.duration)}initTimerEvents(){this.subscriptions.push(this.timer.on("tick",(()=>{const t=this.getCurrentTime();this.renderer.renderProgress(t/this.getDuration(),!0),this.emit("timeupdate",t),this.emit("audioprocess",t)})))}initPlayerEvents(){this.subscriptions.push(this.onMediaEvent("timeupdate",(()=>{const t=this.getCurrentTime();this.renderer.renderProgress(t/this.getDuration(),this.isPlaying()),this.emit("timeupdate",t)})),this.onMediaEvent("play",(()=>{this.emit("play"),this.timer.start()})),this.onMediaEvent("pause",(()=>{this.emit("pause"),this.timer.stop()})),this.onMediaEvent("emptied",(()=>{this.timer.stop()})),this.onMediaEvent("ended",(()=>{this.emit("finish")})),this.onMediaEvent("seeking",(()=>{this.emit("seeking",this.getCurrentTime())})))}initRendererEvents(){this.subscriptions.push(this.renderer.on("click",(t=>{this.options.interact&&(this.seekTo(t),this.emit("interaction",t*this.getDuration()),this.emit("click",t))})),this.renderer.on("scroll",((t,e)=>{const i=this.getDuration();this.emit("scroll",t*i,e*i)})),this.renderer.on("render",(()=>{this.emit("redraw")})));{let t;this.subscriptions.push(this.renderer.on("drag",(e=>{this.options.interact&&(this.renderer.renderProgress(e),clearTimeout(t),t=setTimeout((()=>{this.seekTo(e)}),this.isPlaying()?0:200),this.emit("interaction",e*this.getDuration()),this.emit("drag",e))})))}}initPlugins(){var t;(null===(t=this.options.plugins)||void 0===t?void 0:t.length)&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}setOptions(t){this.options=Object.assign({},this.options,t),this.renderer.setOptions(this.options),t.audioRate&&this.setPlaybackRate(t.audioRate),null!=t.mediaControls&&(this.getMediaElement().controls=t.mediaControls)}registerPlugin(t){return t.init(this),this.plugins.push(t),this.subscriptions.push(t.once("destroy",(()=>{this.plugins=this.plugins.filter((e=>e!==t))}))),t}getWrapper(){return this.renderer.getWrapper()}getScroll(){return this.renderer.getScroll()}getActivePlugins(){return this.plugins}loadAudio(t,e,r,o){return i(this,void 0,void 0,(function*(){if(this.emit("load",t),this.isPlaying()&&this.pause(),this.decodedData=null,!e&&!r){const i=t=>this.emit("loading",t);e=yield n.fetchBlob(t,i,this.options.fetchParams)}if(this.setSrc(t,e),r)o=(yield Promise.resolve(o||this.getDuration()))||(yield new Promise((t=>{this.onceMediaEvent("loadedmetadata",(()=>t(this.getDuration())))})))||(yield Promise.resolve(0)),this.decodedData=s.createBuffer(r,o);else if(e){const t=yield e.arrayBuffer();this.decodedData=yield s.decode(t,this.options.sampleRate)}this.emit("decode",this.getDuration()),this.decodedData&&this.renderer.render(this.decodedData),this.emit("ready",this.getDuration())}))}load(t,e,s){return i(this,void 0,void 0,(function*(){this.loadAudio(t,void 0,e,s)}))}loadBlob(t,e,s){return i(this,void 0,void 0,(function*(){this.loadAudio("blob",t,e,s)}))}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=1,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=Math.min(s.length,e),o=s.length/r,a=[];for(let t=0;t<r;t++){const e=s[Math.round(t*o)];a.push(Math.round(e*i)/i)}n.push(a)}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}seekTo(t){const e=this.getDuration()*t;this.setTime(e)}playPause(){return i(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)}destroy(){this.emit("destroy"),this.plugins.forEach((t=>t.destroy())),this.subscriptions.forEach((t=>t())),this.timer.destroy(),this.renderer.destroy(),super.destroy()}}const d={height:50,overlayColor:"rgba(100, 100, 100, 0.1)",insertPosition:"afterend"};class c extends e{constructor(t){super(t),this.miniWavesurfer=null,this.container=null,this.options=Object.assign({},d,t),this.minimapWrapper=this.initMinimapWrapper(),this.overlay=this.initOverlay()}static create(t){return new c(t)}onInit(){var t,e;if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");this.options.container?("string"==typeof this.options.container?this.container=document.querySelector(this.options.container):this.options.container instanceof HTMLElement&&(this.container=this.options.container),null===(t=this.container)||void 0===t||t.appendChild(this.minimapWrapper)):(this.container=this.wavesurfer.getWrapper().parentElement,null===(e=this.container)||void 0===e||e.insertAdjacentElement(this.options.insertPosition,this.minimapWrapper)),this.initWaveSurferEvents()}initMinimapWrapper(){const t=document.createElement("div");return t.style.position="relative",t.setAttribute("part","minimap"),t}initOverlay(){const t=document.createElement("div");return t.setAttribute("style","position: absolute; z-index: 2; left: 0; top: 0; bottom: 0; transition: left 100ms ease-out; pointer-events: none;"),t.style.backgroundColor=this.options.overlayColor,this.minimapWrapper.appendChild(t),t}initMinimap(){if(this.miniWavesurfer&&(this.miniWavesurfer.destroy(),this.miniWavesurfer=null),!this.wavesurfer)return;const t=this.wavesurfer.getDecodedData(),e=this.wavesurfer.getMediaElement();t&&e&&(this.miniWavesurfer=l.create(Object.assign(Object.assign({},this.options),{container:this.minimapWrapper,minPxPerSec:0,fillParent:!0,media:e,peaks:[t.getChannelData(0)],duration:t.duration})),this.subscriptions.push(this.miniWavesurfer.on("ready",(()=>{this.emit("ready")})),this.miniWavesurfer.on("interaction",(()=>{this.emit("interaction")}))))}getOverlayWidth(){var t;const e=(null===(t=this.wavesurfer)||void 0===t?void 0:t.getWrapper().clientWidth)||1;return Math.round(this.minimapWrapper.clientWidth/e*100)}onRedraw(){const t=this.getOverlayWidth();this.overlay.style.width=`${t}%`}onScroll(t){if(!this.wavesurfer)return;const e=this.wavesurfer.getDuration();this.overlay.style.left=t/e*100+"%"}initWaveSurferEvents(){this.wavesurfer&&this.subscriptions.push(this.wavesurfer.on("decode",(()=>{this.initMinimap()})),this.wavesurfer.on("scroll",(t=>{this.onScroll(t)})),this.wavesurfer.on("redraw",(()=>{this.onRedraw()})))}destroy(){var t;null===(t=this.miniWavesurfer)||void 0===t||t.destroy(),this.minimapWrapper.remove(),super.destroy()}}module.exports=c;
|