wavesurfer.js 7.0.0-alpha.4 → 7.0.0-alpha.41

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.
Files changed (46) hide show
  1. package/README.md +64 -17
  2. package/dist/base-plugin.d.ts +14 -5
  3. package/dist/base-plugin.js +5 -1
  4. package/dist/decoder.d.ts +8 -10
  5. package/dist/decoder.js +37 -44
  6. package/dist/event-emitter.d.ts +16 -10
  7. package/dist/event-emitter.js +38 -16
  8. package/dist/fetcher.js +2 -13
  9. package/dist/legacy-adapter.d.ts +7 -0
  10. package/dist/legacy-adapter.js +15 -0
  11. package/dist/player.d.ts +32 -11
  12. package/dist/player.js +55 -39
  13. package/dist/plugins/envelope.d.ts +57 -0
  14. package/dist/plugins/envelope.js +305 -0
  15. package/dist/plugins/envelope.min.js +1 -0
  16. package/dist/plugins/minimap.d.ts +34 -0
  17. package/dist/plugins/minimap.js +99 -0
  18. package/dist/plugins/minimap.min.js +1 -0
  19. package/dist/plugins/multitrack.d.ts +117 -0
  20. package/dist/plugins/multitrack.js +506 -0
  21. package/dist/plugins/multitrack.min.js +1 -0
  22. package/dist/plugins/record.d.ts +26 -0
  23. package/dist/plugins/record.js +125 -0
  24. package/dist/plugins/record.min.js +1 -0
  25. package/dist/plugins/regions.d.ts +88 -41
  26. package/dist/plugins/regions.js +365 -170
  27. package/dist/plugins/regions.min.js +1 -0
  28. package/dist/plugins/spectrogram.d.ts +24 -0
  29. package/dist/plugins/spectrogram.js +165 -0
  30. package/dist/plugins/timeline.d.ts +41 -0
  31. package/dist/plugins/timeline.js +135 -0
  32. package/dist/plugins/timeline.min.js +1 -0
  33. package/dist/renderer.d.ts +26 -12
  34. package/dist/renderer.js +212 -157
  35. package/dist/timer.d.ts +1 -1
  36. package/dist/wavesurfer.d.ts +136 -0
  37. package/dist/wavesurfer.js +213 -0
  38. package/dist/wavesurfer.min.js +1 -1
  39. package/package.json +49 -24
  40. package/dist/index.d.ts +0 -104
  41. package/dist/index.js +0 -188
  42. package/dist/player-webaudio.d.ts +0 -8
  43. package/dist/player-webaudio.js +0 -32
  44. package/dist/react/useWavesurfer.d.ts +0 -5
  45. package/dist/react/useWavesurfer.js +0 -20
  46. package/dist/wavesurfer.Regions.min.js +0 -1
@@ -0,0 +1,506 @@
1
+ /**
2
+ * Multitrack isn't a plugin, but rather a helper class for creating a multitrack audio player.
3
+ * Individual tracks are synced and played together. They can be dragged to set their start position.
4
+ */
5
+ import WaveSurfer from '../wavesurfer.js';
6
+ import RegionsPlugin from './regions.js';
7
+ import TimelinePlugin from './timeline.js';
8
+ import EnvelopePlugin from './envelope.js';
9
+ import EventEmitter from '../event-emitter.js';
10
+ class MultiTrack extends EventEmitter {
11
+ static create(tracks, options) {
12
+ return new MultiTrack(tracks, options);
13
+ }
14
+ constructor(tracks, options) {
15
+ super();
16
+ this.audios = [];
17
+ this.wavesurfers = [];
18
+ this.durations = [];
19
+ this.currentTime = 0;
20
+ this.maxDuration = 0;
21
+ this.isDragging = false;
22
+ this.frameRequest = null;
23
+ this.timer = null;
24
+ this.subscriptions = [];
25
+ this.timeline = null;
26
+ this.tracks = tracks.map((track) => ({
27
+ ...track,
28
+ startPosition: track.startPosition || 0,
29
+ peaks: track.peaks || (track.url ? undefined : [new Float32Array()]),
30
+ }));
31
+ this.options = options;
32
+ this.rendering = initRendering(this.tracks, this.options);
33
+ this.rendering.addDropHandler((trackId) => {
34
+ this.emit('drop', { id: trackId });
35
+ });
36
+ this.initAllAudios().then((durations) => {
37
+ this.initDurations(durations);
38
+ this.initAllWavesurfers();
39
+ this.rendering.containers.forEach((container, index) => {
40
+ const drag = initDragging(container, (delta) => this.onDrag(index, delta), options.rightButtonDrag);
41
+ this.wavesurfers[index].once('destroy', () => drag?.destroy());
42
+ });
43
+ this.rendering.addClickHandler((position) => {
44
+ if (this.isDragging)
45
+ return;
46
+ this.seekTo(position);
47
+ });
48
+ this.emit('canplay');
49
+ });
50
+ }
51
+ initDurations(durations) {
52
+ this.durations = durations;
53
+ this.maxDuration = this.tracks.reduce((max, track, index) => {
54
+ return Math.max(max, track.startPosition + durations[index]);
55
+ }, 0);
56
+ this.rendering.setMainWidth(durations, this.maxDuration);
57
+ }
58
+ initAudio(track) {
59
+ const audio = new Audio(track.url);
60
+ return new Promise((resolve) => {
61
+ if (!audio.src)
62
+ return resolve(audio);
63
+ audio.addEventListener('loadedmetadata', () => resolve(audio), { once: true });
64
+ });
65
+ }
66
+ async initAllAudios() {
67
+ this.audios = await Promise.all(this.tracks.map((track) => this.initAudio(track)));
68
+ return this.audios.map((a) => (a.src ? a.duration : 0));
69
+ }
70
+ initWavesurfer(track, index) {
71
+ const container = this.rendering.containers[index];
72
+ // Create a wavesurfer instance
73
+ const ws = WaveSurfer.create({
74
+ ...track.options,
75
+ container,
76
+ minPxPerSec: 0,
77
+ media: this.audios[index],
78
+ peaks: track.peaks,
79
+ cursorColor: 'transparent',
80
+ cursorWidth: 0,
81
+ interact: false,
82
+ });
83
+ // Regions and markers
84
+ const wsRegions = RegionsPlugin.create();
85
+ ws.registerPlugin(wsRegions);
86
+ this.subscriptions.push(ws.once('decode', () => {
87
+ // Start and end cues
88
+ if (track.startCue != null || track.endCue != null) {
89
+ const { startCue = 0, endCue = this.durations[index] } = track;
90
+ const startCueRegion = wsRegions.addRegion({
91
+ start: 0,
92
+ end: startCue,
93
+ color: 'rgba(0, 0, 0, 0.7)',
94
+ drag: false,
95
+ });
96
+ const endCueRegion = wsRegions.addRegion({
97
+ start: endCue,
98
+ end: endCue + this.durations[index],
99
+ color: 'rgba(0, 0, 0, 0.7)',
100
+ drag: false,
101
+ });
102
+ // Allow resizing only from one side
103
+ startCueRegion.element.firstElementChild?.remove();
104
+ endCueRegion.element.lastChild?.remove();
105
+ // Prevent clicks when dragging
106
+ // Update the start and end cues on resize
107
+ this.subscriptions.push(startCueRegion.on('update-end', () => {
108
+ track.startCue = startCueRegion.end;
109
+ this.emit('start-cue-change', { id: track.id, startCue: track.startCue });
110
+ }), endCueRegion.on('update-end', () => {
111
+ track.endCue = endCueRegion.start;
112
+ this.emit('end-cue-change', { id: track.id, endCue: track.endCue });
113
+ }));
114
+ }
115
+ // Intro
116
+ if (track.intro) {
117
+ const introRegion = wsRegions.addRegion({
118
+ start: 0,
119
+ end: track.intro.endTime,
120
+ content: track.intro.label,
121
+ color: this.options.trackBackground,
122
+ drag: false,
123
+ });
124
+ introRegion.element.querySelector('[data-resize="left"]')?.remove();
125
+ introRegion.element.parentElement.style.mixBlendMode = 'plus-lighter';
126
+ if (track.intro.color) {
127
+ ;
128
+ introRegion.element.querySelector('[data-resize="right"]').style.borderColor =
129
+ track.intro.color;
130
+ }
131
+ this.subscriptions.push(introRegion.on('update-end', () => {
132
+ this.emit('intro-end-change', { id: track.id, endTime: introRegion.end });
133
+ }));
134
+ }
135
+ // Render markers
136
+ if (track.markers) {
137
+ track.markers.forEach((marker) => {
138
+ wsRegions.addRegion({
139
+ start: marker.time,
140
+ content: marker.label,
141
+ color: marker.color,
142
+ resize: false,
143
+ });
144
+ });
145
+ }
146
+ }));
147
+ // Envelope
148
+ const envelope = ws.registerPlugin(EnvelopePlugin.create({
149
+ ...this.options.envelopeOptions,
150
+ fadeInStart: track.startCue,
151
+ fadeInEnd: track.fadeInEnd,
152
+ fadeOutStart: track.fadeOutStart,
153
+ fadeOutEnd: track.endCue,
154
+ volume: track.volume,
155
+ }));
156
+ this.subscriptions.push(envelope.on('volume-change', (volume) => {
157
+ this.setIsDragging();
158
+ this.emit('volume-change', { id: track.id, volume });
159
+ }), envelope.on('fade-in-change', (time) => {
160
+ this.setIsDragging();
161
+ this.emit('fade-in-change', { id: track.id, fadeInEnd: time });
162
+ }), envelope.on('fade-out-change', (time) => {
163
+ this.setIsDragging();
164
+ this.emit('fade-out-change', { id: track.id, fadeOutStart: time });
165
+ }), this.on('start-cue-change', ({ id, startCue }) => {
166
+ if (id === track.id) {
167
+ envelope.setStartTime(startCue);
168
+ }
169
+ }), this.on('end-cue-change', ({ id, endCue }) => {
170
+ if (id === track.id) {
171
+ envelope.setEndTime(endCue);
172
+ }
173
+ }));
174
+ return ws;
175
+ }
176
+ initAllWavesurfers() {
177
+ const wavesurfers = this.tracks.map((track, index) => {
178
+ return this.initWavesurfer(track, index);
179
+ });
180
+ this.wavesurfers = wavesurfers;
181
+ this.initTimeline();
182
+ }
183
+ initTimeline() {
184
+ if (this.timeline)
185
+ this.timeline.destroy();
186
+ this.timeline = this.wavesurfers[0].registerPlugin(TimelinePlugin.create({
187
+ duration: this.maxDuration,
188
+ container: this.rendering.containers[0].parentElement,
189
+ }));
190
+ }
191
+ updatePosition(time, autoCenter = false) {
192
+ const precisionSeconds = 0.3;
193
+ const isPaused = !this.isPlaying();
194
+ if (time !== this.currentTime) {
195
+ this.currentTime = time;
196
+ this.rendering.updateCursor(time / this.maxDuration, autoCenter);
197
+ }
198
+ // Update the current time of each audio
199
+ this.tracks.forEach((track, index) => {
200
+ const audio = this.audios[index];
201
+ const duration = this.durations[index];
202
+ const newTime = time - track.startPosition;
203
+ if (Math.abs(audio.currentTime - newTime) > precisionSeconds) {
204
+ audio.currentTime = newTime;
205
+ }
206
+ // If the position is out of the track bounds, pause it
207
+ if (isPaused || newTime < 0 || newTime > duration) {
208
+ !audio.paused && audio.pause();
209
+ }
210
+ else if (!isPaused) {
211
+ // If the position is in the track bounds, play it
212
+ audio.paused && audio.play();
213
+ }
214
+ // Unmute if cue is reached
215
+ const newVolume = newTime >= (track.startCue || 0) && newTime < (track.endCue || Infinity) ? 1 : 0;
216
+ if (newVolume !== audio.volume)
217
+ audio.volume = newVolume;
218
+ });
219
+ }
220
+ setIsDragging() {
221
+ // Prevent click events when dragging
222
+ this.isDragging = true;
223
+ if (this.timer)
224
+ clearTimeout(this.timer);
225
+ this.timer = setTimeout(() => (this.isDragging = false), 300);
226
+ }
227
+ onDrag(index, delta) {
228
+ this.setIsDragging();
229
+ const track = this.tracks[index];
230
+ if (!track.draggable)
231
+ return;
232
+ const newStartPosition = track.startPosition + delta * this.maxDuration;
233
+ const mainIndex = this.tracks.findIndex((item) => item.url && !item.draggable);
234
+ const mainTrack = this.tracks[mainIndex];
235
+ const minStart = (mainTrack ? mainTrack.startPosition : 0) - this.durations[index];
236
+ const maxStart = mainTrack ? mainTrack.startPosition + this.durations[mainIndex] : this.maxDuration;
237
+ if (newStartPosition >= minStart && newStartPosition <= maxStart) {
238
+ track.startPosition = newStartPosition;
239
+ this.initDurations(this.durations);
240
+ this.rendering.setContainerOffsets();
241
+ this.updatePosition(this.currentTime);
242
+ this.emit('start-position-change', { id: track.id, startPosition: newStartPosition });
243
+ }
244
+ }
245
+ findCurrentTracks() {
246
+ // Find the audios at the current time
247
+ const indexes = [];
248
+ this.tracks.forEach((track, index) => {
249
+ if (track.url &&
250
+ this.currentTime >= track.startPosition &&
251
+ this.currentTime < track.startPosition + this.durations[index]) {
252
+ indexes.push(index);
253
+ }
254
+ });
255
+ if (indexes.length === 0) {
256
+ const minStartTime = Math.min(...this.tracks.filter((t) => t.url).map((track) => track.startPosition));
257
+ indexes.push(this.tracks.findIndex((track) => track.startPosition === minStartTime));
258
+ }
259
+ return indexes;
260
+ }
261
+ startSync() {
262
+ const onFrame = () => {
263
+ const position = this.audios.reduce((pos, audio, index) => {
264
+ if (!audio.paused) {
265
+ pos = Math.max(pos, audio.currentTime + this.tracks[index].startPosition);
266
+ }
267
+ return pos;
268
+ }, this.currentTime);
269
+ if (position > this.currentTime) {
270
+ this.updatePosition(position, true);
271
+ }
272
+ this.frameRequest = requestAnimationFrame(onFrame);
273
+ };
274
+ onFrame();
275
+ }
276
+ play() {
277
+ this.startSync();
278
+ const indexes = this.findCurrentTracks();
279
+ indexes.forEach((index) => {
280
+ this.audios[index]?.play();
281
+ });
282
+ }
283
+ pause() {
284
+ this.audios.forEach((audio) => audio.pause());
285
+ }
286
+ isPlaying() {
287
+ return this.audios.some((audio) => !audio.paused);
288
+ }
289
+ getCurrentTime() {
290
+ return this.currentTime;
291
+ }
292
+ /** Position percentage from 0 to 1 */
293
+ seekTo(position) {
294
+ const wasPlaying = this.isPlaying();
295
+ this.updatePosition(position * this.maxDuration);
296
+ if (wasPlaying)
297
+ this.play();
298
+ }
299
+ /** Set time in seconds */
300
+ setTime(time) {
301
+ const wasPlaying = this.isPlaying();
302
+ this.updatePosition(time);
303
+ if (wasPlaying)
304
+ this.play();
305
+ }
306
+ zoom(pxPerSec) {
307
+ this.options.minPxPerSec = pxPerSec;
308
+ this.wavesurfers.forEach((ws, index) => this.tracks[index].url && ws.zoom(pxPerSec));
309
+ this.rendering.setMainWidth(this.durations, this.maxDuration);
310
+ this.rendering.setContainerOffsets();
311
+ }
312
+ addTrack(track) {
313
+ const index = this.tracks.findIndex((t) => t.id === track.id);
314
+ if (index !== -1) {
315
+ this.tracks[index] = track;
316
+ this.initAudio(track).then((audio) => {
317
+ this.audios[index] = audio;
318
+ this.durations[index] = audio.duration;
319
+ this.initDurations(this.durations);
320
+ const container = this.rendering.containers[index];
321
+ container.innerHTML = '';
322
+ this.wavesurfers[index].destroy();
323
+ this.wavesurfers[index] = this.initWavesurfer(track, index);
324
+ const drag = initDragging(container, (delta) => this.onDrag(index, delta), this.options.rightButtonDrag);
325
+ this.wavesurfers[index].once('destroy', () => drag?.destroy());
326
+ this.initTimeline();
327
+ this.emit('canplay');
328
+ });
329
+ }
330
+ }
331
+ destroy() {
332
+ if (this.frameRequest)
333
+ cancelAnimationFrame(this.frameRequest);
334
+ this.rendering.destroy();
335
+ this.audios.forEach((audio) => {
336
+ audio.pause();
337
+ audio.src = '';
338
+ });
339
+ this.wavesurfers.forEach((ws) => {
340
+ ws.destroy();
341
+ });
342
+ }
343
+ // See https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/setSinkId
344
+ setSinkId(sinkId) {
345
+ return Promise.all(this.wavesurfers.map((ws) => ws.setSinkId(sinkId)));
346
+ }
347
+ }
348
+ function initRendering(tracks, options) {
349
+ let pxPerSec = 0;
350
+ let durations = [];
351
+ let mainWidth = 0;
352
+ // Create a common container for all tracks
353
+ const scroll = document.createElement('div');
354
+ scroll.setAttribute('style', 'width: 100%; overflow-x: scroll; overflow-y: hidden; user-select: none;');
355
+ const wrapper = document.createElement('div');
356
+ wrapper.style.position = 'relative';
357
+ scroll.appendChild(wrapper);
358
+ options.container.appendChild(scroll);
359
+ // Create a common cursor
360
+ const cursor = document.createElement('div');
361
+ cursor.setAttribute('style', 'height: 100%; position: absolute; z-index: 10; top: 0; left: 0');
362
+ cursor.style.backgroundColor = options.cursorColor || '#000';
363
+ cursor.style.width = `${options.cursorWidth ?? 1}px`;
364
+ wrapper.appendChild(cursor);
365
+ const { clientWidth } = wrapper;
366
+ // Create containers for each track
367
+ const containers = tracks.map((track, index) => {
368
+ const container = document.createElement('div');
369
+ container.style.position = 'relative';
370
+ if (options.trackBorderColor && index > 0) {
371
+ const borderDiv = document.createElement('div');
372
+ borderDiv.setAttribute('style', `width: 100%; height: 2px; background-color: ${options.trackBorderColor}`);
373
+ wrapper.appendChild(borderDiv);
374
+ }
375
+ if (options.trackBackground && track.url) {
376
+ container.style.background = options.trackBackground;
377
+ }
378
+ // No audio on this track, so make it droppable
379
+ if (!track.url) {
380
+ const dropArea = document.createElement('div');
381
+ dropArea.setAttribute('style', `position: absolute; z-index: 10; left: 10px; top: 10px; right: 10px; bottom: 10px; border: 2px dashed ${options.trackBorderColor};`);
382
+ dropArea.addEventListener('dragover', (e) => {
383
+ e.preventDefault();
384
+ dropArea.style.background = options.trackBackground || '';
385
+ });
386
+ dropArea.addEventListener('dragleave', (e) => {
387
+ e.preventDefault();
388
+ dropArea.style.background = '';
389
+ });
390
+ dropArea.addEventListener('drop', (e) => {
391
+ e.preventDefault();
392
+ dropArea.style.background = '';
393
+ });
394
+ container.appendChild(dropArea);
395
+ }
396
+ wrapper.appendChild(container);
397
+ return container;
398
+ });
399
+ // Set the positions of each container
400
+ const setContainerOffsets = () => {
401
+ containers.forEach((container, i) => {
402
+ const offset = tracks[i].startPosition * pxPerSec;
403
+ if (durations[i]) {
404
+ container.style.width = `${durations[i] * pxPerSec}px`;
405
+ }
406
+ container.style.transform = `translateX(${offset}px)`;
407
+ });
408
+ };
409
+ return {
410
+ containers,
411
+ // Set the start offset
412
+ setContainerOffsets,
413
+ // Set the container width
414
+ setMainWidth: (trackDurations, maxDuration) => {
415
+ durations = trackDurations;
416
+ pxPerSec = Math.max(options.minPxPerSec || 0, clientWidth / maxDuration);
417
+ mainWidth = pxPerSec * maxDuration;
418
+ wrapper.style.width = `${mainWidth}px`;
419
+ setContainerOffsets();
420
+ },
421
+ // Update cursor position
422
+ updateCursor: (position, autoCenter) => {
423
+ cursor.style.left = `${Math.min(100, position * 100)}%`;
424
+ // Update scroll
425
+ const { clientWidth, scrollLeft } = scroll;
426
+ const center = clientWidth / 2;
427
+ const minScroll = autoCenter ? center : clientWidth;
428
+ const pos = position * mainWidth;
429
+ if (pos > scrollLeft + minScroll || pos < scrollLeft) {
430
+ scroll.scrollLeft = pos - center;
431
+ }
432
+ },
433
+ // Click to seek
434
+ addClickHandler: (onClick) => {
435
+ wrapper.addEventListener('click', (e) => {
436
+ const rect = wrapper.getBoundingClientRect();
437
+ const x = e.clientX - rect.left;
438
+ const position = x / wrapper.offsetWidth;
439
+ onClick(position);
440
+ });
441
+ },
442
+ // Destroy the container
443
+ destroy: () => {
444
+ scroll.remove();
445
+ },
446
+ // Do something on drop
447
+ addDropHandler: (onDrop) => {
448
+ tracks.forEach((track, index) => {
449
+ if (!track.url) {
450
+ const droppable = containers[index].querySelector('div');
451
+ droppable?.addEventListener('drop', (e) => {
452
+ e.preventDefault();
453
+ onDrop(track.id);
454
+ });
455
+ }
456
+ });
457
+ },
458
+ };
459
+ }
460
+ function initDragging(container, onDrag, rightButtonDrag = false) {
461
+ const wrapper = container.parentElement;
462
+ if (!wrapper)
463
+ return;
464
+ // Dragging tracks to set position
465
+ let dragStart = null;
466
+ container.addEventListener('contextmenu', (e) => {
467
+ rightButtonDrag && e.preventDefault();
468
+ });
469
+ // Drag start
470
+ container.addEventListener('mousedown', (e) => {
471
+ if (rightButtonDrag && e.button !== 2)
472
+ return;
473
+ const rect = wrapper.getBoundingClientRect();
474
+ dragStart = e.clientX - rect.left;
475
+ container.style.cursor = 'grabbing';
476
+ });
477
+ // Drag end
478
+ const onMouseUp = (e) => {
479
+ if (dragStart != null) {
480
+ e.stopPropagation();
481
+ dragStart = null;
482
+ container.style.cursor = '';
483
+ }
484
+ };
485
+ // Drag move
486
+ const onMouseMove = (e) => {
487
+ if (dragStart == null)
488
+ return;
489
+ const rect = wrapper.getBoundingClientRect();
490
+ const x = e.clientX - rect.left;
491
+ const diff = x - dragStart;
492
+ if (diff > 1 || diff < -1) {
493
+ dragStart = x;
494
+ onDrag(diff / wrapper.offsetWidth);
495
+ }
496
+ };
497
+ document.body.addEventListener('mouseup', onMouseUp);
498
+ document.body.addEventListener('mousemove', onMouseMove);
499
+ return {
500
+ destroy: () => {
501
+ document.body.removeEventListener('mouseup', onMouseUp);
502
+ document.body.removeEventListener('mousemove', onMouseMove);
503
+ },
504
+ };
505
+ }
506
+ export default MultiTrack;
@@ -0,0 +1 @@
1
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Multitrack=e():t.Multitrack=e()}(WaveSurfer,(()=>(()=>{"use strict";var t={284:(t,e,i)=>{i.d(e,{Z:()=>r});var s=i(139);class n extends s.Z{constructor(t){super(),this.subscriptions=[],this.options=t}init(t){this.wavesurfer=t.wavesurfer,this.container=t.container,this.wrapper=t.wrapper}destroy(){this.subscriptions.forEach((t=>t()))}}const r=n},139:(t,e,i)=>{i.d(e,{Z:()=>s});const s=class{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)))}}},919:(t,e,i)=>{i.d(e,{default:()=>o});var s=i(284);const n={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 r extends s.Z{constructor(t){super(t),this.svg=null,this.audioContext=null,this.gainNode=null,this.volume=1,this.isFadingIn=!1,this.isFadingOut=!1,this.options=Object.assign({},n,t),this.options.lineColor=this.options.lineColor||n.lineColor,this.options.dragPointFill=this.options.dragPointFill||n.dragPointFill,this.options.dragPointStroke=this.options.dragPointStroke||n.dragPointStroke,this.volume=this.options.volume??1}static create(t){return new r(t)}init(t){if(super.init(t),!this.wavesurfer)throw Error("WaveSurfer is not initialized");let e;this.subscriptions.push(this.wavesurfer.once("decode",(t=>{this.options.fadeInStart=this.options.fadeInStart||0,this.options.fadeOutEnd=this.options.fadeOutEnd||t,this.options.fadeInEnd=this.options.fadeInEnd||this.options.fadeInStart,this.options.fadeOutStart=this.options.fadeOutStart||this.options.fadeOutEnd,this.initWebAudio(),this.initSvg(),this.initFadeEffects()}))),this.subscriptions.push(this.wavesurfer.on("zoom",(()=>{e&&clearTimeout(e),e=setTimeout((()=>{this.svg?.remove(),this.initSvg()}),100)})))}makeDraggable(t,e){t.addEventListener("mousedown",(t=>{let i=t.clientX,s=t.clientY;const n=this.wavesurfer?.options.interact||!0;let r;this.wavesurfer?.toggleInteraction(!1);const o=t=>{const n=t.clientX-i,r=t.clientY-s;i=t.clientX,s=t.clientY,e(n,r)},a=()=>{document.removeEventListener("mousemove",o),document.removeEventListener("mouseup",a),r&&clearTimeout(r),r=setTimeout((()=>{this.wavesurfer?.toggleInteraction(n)}),100)};document.addEventListener("mousemove",o),document.addEventListener("mouseup",a),t.preventDefault(),t.stopPropagation()}))}renderPolyline(){if(!this.svg||!this.wrapper||!this.wavesurfer)return;const t=this.svg.querySelector("polyline"),e=t.points,i=e.getItem(1).y,s=this.wrapper.clientWidth,n=this.wavesurfer.getDuration();e.getItem(0).x=this.options.fadeInStart/n*s,e.getItem(3).x=this.options.fadeOutEnd/n*s;const r=this.svg.querySelector("line");r.setAttribute("x1",e.getItem(1).x.toString()),r.setAttribute("x2",e.getItem(2).x.toString()),r.setAttribute("y1",i.toString()),r.setAttribute("y2",i.toString());const o=this.svg.querySelectorAll("circle");for(let e=0;e<o.length;e++){const s=o[e],n=t.points.getItem(e+1);s.setAttribute("cx",n.x.toString()),s.setAttribute("cy",i.toString())}}initSvg(){if(!this.wrapper||!this.wavesurfer)return;const t=this.wrapper.clientWidth,e=this.wrapper.clientHeight,i=this.wavesurfer.getDuration(),s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.setAttribute("width","100%"),s.setAttribute("height","100%"),s.setAttribute("viewBox",`0 0 ${t} ${e}`),s.setAttribute("preserveAspectRatio","none"),s.setAttribute("style","position: absolute; left: 0; top: 0; z-index: 4; pointer-events: none;"),this.svg=s;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",this.options.lineColor),n.setAttribute("stroke-width",this.options.lineWidth),n.setAttribute("fill","none"),n.setAttribute("style","pointer-events: none"),s.appendChild(n);const r=document.createElementNS("http://www.w3.org/2000/svg","line");r.setAttribute("stroke","none"),r.setAttribute("stroke-width",(3*this.options.lineWidth).toString()),r.setAttribute("style","cursor: ns-resize; pointer-events: all;"),s.appendChild(r);const o=n.points,a=this.options.dragPointSize/2,h=e-this.volume*e+a;o.getItem(0).x=this.options.fadeInStart/i*t,o.getItem(0).y=e,o.getItem(1).x=this.options.fadeInEnd/i*t,o.getItem(1).y=h,o.getItem(2).x=this.options.fadeOutStart/i*t,o.getItem(2).y=h,o.getItem(3).x=this.options.fadeOutEnd/i*t,o.getItem(3).y=e,[1,2].forEach((()=>{const t=document.createElementNS("http://www.w3.org/2000/svg","circle");t.setAttribute("r",(this.options.dragPointSize/2).toString()),t.setAttribute("fill",this.options.dragPointFill),t.setAttribute("stroke",this.options.dragPointStroke||this.options.dragPointFill),t.setAttribute("stroke-width","2"),t.setAttribute("style","cursor: ew-resize; pointer-events: all;"),s.appendChild(t)})),this.wrapper.appendChild(s),this.renderPolyline();const d=t=>{const i=o.getItem(1).y+t-a;if(i<-.5||i>e)return;o.getItem(1).y=i+a,o.getItem(2).y=i+a,this.renderPolyline();const s=Math.min(1,Math.max(0,(e-i)/e));this.onVolumeChange(s),this.renderPolyline()},l=(e,s,r)=>{const o=n.points.getItem(r),a=o.x+e,h=a/t*i;1===r&&h>this.options.fadeOutStart||h<this.options.fadeInStart||2===r&&h<this.options.fadeInEnd||h>this.options.fadeOutEnd||(o.x=a,1===r?(this.options.fadeInEnd=h,this.emit("fade-in-change",h)):2===r&&(this.options.fadeOutStart=h,this.emit("fade-out-change",h)),s>1||s<-1?d(s):this.renderPolyline())};this.makeDraggable(r,((t,e)=>d(e)));const u=s.querySelectorAll("circle");for(let t=0;t<u.length;t++){const e=t+1;this.makeDraggable(u[t],((t,i)=>l(t,i,e)))}}destroy(){this.svg?.remove(),super.destroy()}initWebAudio(){const t=this.wavesurfer?.getMediaElement();if(!t)return null;this.volume=this.options.volume??t.volume;const e=new window.AudioContext;this.gainNode=e.createGain(),this.gainNode.gain.value=this.volume,e.createMediaElementSource(t).connect(this.gainNode),this.gainNode.connect(e.destination),this.audioContext=e}naturalVolume(t){return 1e-4+.9999*Math.pow(t,3)}onVolumeChange(t){t=this.naturalVolume(t),this.volume=t,this.emit("volume-change",t),this.gainNode&&(this.gainNode.gain.value=t)}initFadeEffects(){if(!this.audioContext||!this.wavesurfer)return;const t=this.wavesurfer.on("timeupdate",(t=>{if(!this.audioContext||!this.gainNode)return;if(!this.wavesurfer?.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,void this.gainNode.gain.linearRampToValueAtTime(0,this.audioContext.currentTime+(this.options.fadeOutEnd-t));let e=!1;this.isFadingIn&&(t<this.options.fadeInStart||t>this.options.fadeInEnd)&&(this.isFadingIn=!1,e=!0),this.isFadingOut&&(t<this.options.fadeOutStart||t>=this.options.fadeOutEnd)&&(this.isFadingOut=!1,e=!0),e&&(this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=this.volume)}));this.subscriptions.push(t)}getCurrentVolume(){return this.gainNode?this.gainNode.gain.value:this.volume}setStartTime(t){this.options.fadeInStart=t,this.renderPolyline()}setEndTime(t){this.options.fadeOutEnd=t,this.renderPolyline()}}const o=r},76:(t,e,i)=>{i.d(e,{default:()=>h});var s=i(284),n=i(139);function r(t,e,i,s){if(!t)return()=>{};let n=0,r=!1;const o=t=>{r&&t.stopPropagation()},a=t=>{t.stopPropagation();let o=t.clientX;e(o);const a=t=>{const e=t.clientX,s=e-o;n+=s,o=e,Math.abs(n)>=5&&(r?i(s):(r=!0,i(n)))},h=()=>{n=0,s(),setTimeout((()=>r=!1),10),document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",h)};document.addEventListener("mousemove",a),document.addEventListener("mouseup",h)};return t.addEventListener("click",o),t.addEventListener("mousedown",a),()=>{t.removeEventListener("click",o),t.removeEventListener("mousedown",a)}}class o extends n.Z{constructor(t,e){super(),this.totalDuration=e,this.id=t.id||Math.random().toString(32).slice(2),this.start=t.start,this.end=t.end??t.start,this.drag=t.drag??!0,this.resize=t.resize??!0,this.color=t.color??"rgba(0, 0, 0, 0.1)",this.element=this.initElement(t.content),this.renderPosition(),this.initMouseEvents()}initElement(t){const e=document.createElement("div"),i=this.start===this.end;if(e.id=this.id,e.setAttribute("style",`\n position: absolute;\n height: 100%;\n background-color: ${i?"none":this.color};\n border-left: ${i?"2px solid "+this.color:"none"};\n border-radius: 2px;\n box-sizing: border-box;\n transition: background-color 0.2s ease;\n cursor: ${this.drag?"grab":"default"};\n pointer-events: all;\n padding: 0.2em ${i?.2:.4}em;\n pointer-events: all;\n `),t&&("string"==typeof t?(this.content=document.createElement("div"),this.content.textContent=t):this.content=t,e.appendChild(this.content)),!i){const t=document.createElement("div");t.setAttribute("data-resize","left"),t.setAttribute("style",`\n position: absolute;\n z-index: 2;\n width: 6px;\n height: 100%;\n top: 0;\n left: 0;\n border-left: 2px solid rgba(0, 0, 0, 0.5);\n border-radius: 2px 0 0 2px;\n cursor: ${this.resize?"ew-resize":"default"};\n word-break: keep-all;\n `);const i=t.cloneNode();i.setAttribute("data-resize","right"),i.style.left="",i.style.right="0",i.style.borderRight=i.style.borderLeft,i.style.borderLeft="",i.style.borderRadius="0 2px 2px 0",e.appendChild(t),e.appendChild(i)}return e}renderPosition(){const t=this.start/this.totalDuration,e=this.end/this.totalDuration;this.element.style.left=100*t+"%",this.element.style.width=100*(e-t)+"%"}initMouseEvents(){const{element:t}=this;t.addEventListener("click",(t=>this.emit("click",t))),t.addEventListener("mouseenter",(t=>this.emit("over",t))),t.addEventListener("mouseleave",(t=>this.emit("leave",t))),t.addEventListener("dblclick",(t=>this.emit("dblclick",t))),r(t,(()=>this.onStartMoving()),(t=>this.onMove(t)),(()=>this.onEndMoving())),r(t.querySelector('[data-resize="left"]'),(()=>null),(t=>this.onResize(t,"start")),(()=>this.onEndResizing())),r(t.querySelector('[data-resize="right"]'),(()=>null),(t=>this.onResize(t,"end")),(()=>this.onEndResizing()))}onStartMoving(){this.drag&&(this.element.style.cursor="grabbing")}onEndMoving(){this.drag&&(this.element.style.cursor="grab",this.emit("update-end"))}onUpdate(t,e){if(!this.element.parentElement)return;const i=t/this.element.parentElement.clientWidth*this.totalDuration;e.forEach((t=>{this[t]+=i,"start"===t?this.start=Math.max(0,Math.min(this.start,this.end)):this.end=Math.max(this.start,Math.min(this.end,this.totalDuration))})),this.renderPosition(),this.emit("update")}onMove(t){this.drag&&this.onUpdate(t,["start","end"])}onResize(t,e){this.resize&&this.onUpdate(t,[e])}onEndResizing(){this.resize&&this.emit("update-end")}_setTotalDuration(t){this.totalDuration=t,this.renderPosition()}play(){this.emit("play")}setOptions(t){t.color&&(this.color=t.color,this.element.style.backgroundColor=this.color),void 0!==t.drag&&(this.drag=t.drag,this.element.style.cursor=this.drag?"grab":"default"),void 0!==t.resize&&(this.resize=t.resize,this.element.querySelectorAll("[data-resize]").forEach((t=>{t.style.cursor=this.resize?"ew-resize":"default"}))),void 0===t.start&&void 0===t.end||(this.start=t.start??this.start,this.end=t.end??this.end,this.renderPosition())}remove(){this.emit("remove"),this.element.remove(),this.element=null}}class a extends s.Z{constructor(t){super(t),this.regions=[],this.regionsContainer=this.initRegionsContainer()}static create(t){return new a(t)}init(t){if(super.init(t),!this.wavesurfer||!this.wrapper)throw Error("WaveSurfer is not initialized");this.wrapper.appendChild(this.regionsContainer)}initRegionsContainer(){const t=document.createElement("div");return t.setAttribute("style","\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 3;\n pointer-events: none;\n "),t}getRegions(){return this.regions}avoidOverlapping(t){if(!t.content)return;const e=t.content,i=e.getBoundingClientRect().left,s=t.element.scrollWidth,n=this.regions.filter((e=>{if(e===t||!e.content)return!1;const n=e.content.getBoundingClientRect().left,r=e.element.scrollWidth;return i<n+r&&n<i+s})).map((t=>t.content?.getBoundingClientRect().height||0)).reduce(((t,e)=>t+e),0);e.style.marginTop=`${n}px`}saveRegion(t){this.regionsContainer.appendChild(t.element),this.avoidOverlapping(t),this.regions.push(t),this.emit("region-created",t);const e=[t.on("update-end",(()=>{this.avoidOverlapping(t),this.emit("region-updated",t)})),t.on("play",(()=>{this.wavesurfer?.play(),this.wavesurfer?.setTime(t.start)})),t.on("click",(e=>{this.emit("region-clicked",t,e)})),t.once("remove",(()=>{e.forEach((t=>t())),this.regions=this.regions.filter((e=>e!==t))}))];this.subscriptions.push(...e)}addRegion(t){if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");const e=this.wavesurfer.getDuration(),i=new o(t,e);return e?this.saveRegion(i):this.subscriptions.push(this.wavesurfer.once("canplay",(t=>{i._setTotalDuration(t),this.saveRegion(i)}))),i}add(t,e,i,s){return this.addRegion({start:t,end:e,content:i,color:s})}enableDragSelection(t){let e=null,i=0,s=0;return r(this.wrapper,(t=>i=t),(n=>{if(this.wavesurfer&&this.wrapper){if(!e){const s=this.wavesurfer.getDuration(),r=this.wrapper.getBoundingClientRect();let a=(i-r.left)/r.width*s,h=(i+n-r.left)/r.width*s;a>h&&([a,h]=[h,a]),e=new o({...t,start:a,end:h},s),this.regionsContainer.appendChild(e.element)}s+=n,e&&e.onUpdate(n,[s>0?"end":"start"])}}),(()=>{if(e&&(this.saveRegion(e),e=null,s=0,this.wavesurfer)){const{interact:t}=this.wavesurfer.options;t&&(this.wavesurfer.toggleInteraction(!1),setTimeout((()=>this.wavesurfer?.toggleInteraction(t)),10))}}))}clearRegions(){this.regions.forEach((t=>t.remove()))}destroy(){this.clearRegions(),super.destroy()}}const h=a},954:(t,e,i)=>{i.d(e,{default:()=>o});var s=i(284);const n={height:20};class r extends s.Z{constructor(t){super(t),this.options=Object.assign({},n,t),this.timelineWrapper=this.initTimelineWrapper()}static create(t){return new r(t)}init(t){if(super.init(t),!this.wavesurfer||!this.wrapper)throw Error("WaveSurfer is not initialized");(this.options.container??this.wrapper).appendChild(this.timelineWrapper),this.options.duration?this.initTimeline(this.options.duration):this.subscriptions.push(this.wavesurfer.on("decode",(t=>{this.initTimeline(t)})))}destroy(){this.timelineWrapper.remove(),super.destroy()}initTimelineWrapper(){return document.createElement("div")}formatTime(t){return t/60>1?`${Math.round(t/60)}:${(t=Math.round(t%60))<10?"0":""}${t}`:""+Math.round(1e3*t)/1e3}defaultTimeInterval(t){return t>=25?1:5*t>=25?5:15*t>=25?15:60*Math.ceil(.5/t)}defaultPrimaryLabelInterval(t){return t>=25?10:5*t>=25?6:4}defaultSecondaryLabelInterval(t){return t>=25?5:2}initTimeline(t){const e=this.timelineWrapper.scrollWidth/t,i=this.options.timeInterval??this.defaultTimeInterval(e),s=this.options.primaryLabelInterval??this.defaultPrimaryLabelInterval(e),n=this.options.secondaryLabelInterval??this.defaultSecondaryLabelInterval(e),r=document.createElement("div");r.setAttribute("style",`\n height: ${this.options.height}px;\n overflow: hidden;\n display: flex;\n justify-content: space-between;\n align-items: flex-end;\n font-size: ${this.options.height/2}px;\n white-space: nowrap;\n `);const o=document.createElement("div");o.setAttribute("style","\n width: 1px;\n height: 50%;\n display: flex;\n flex-direction: column;\n justify-content: flex-end;\n overflow: visible;\n border-left: 1px solid currentColor;\n opacity: 0.25;\n ");for(let e=0;e<t;e+=i){const t=o.cloneNode(),i=e%s==0;(i||e%n==0)&&(t.style.height="100%",t.style.textIndent="3px",t.textContent=this.formatTime(e),i&&(t.style.opacity="1")),r.appendChild(t)}this.timelineWrapper.appendChild(r),this.emit("ready")}}const o=r}},e={};function i(s){var n=e[s];if(void 0!==n)return n.exports;var r=e[s]={exports:{}};return t[s](r,r.exports,i),r.exports}i.d=(t,e)=>{for(var s in e)i.o(e,s)&&!i.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},i.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var s={};return(()=>{i.d(s,{default:()=>y});const t={decode:async function(t){let e;try{e=new AudioContext({sampleRate:3e3})}catch(t){e=new AudioContext({sampleRate:8e3})}const i=e.decodeAudioData(t);return i.finally((()=>e.close())),i},createBuffer:function(t,e){if("number"==typeof t[0]&&(t=[t]),t[0].some((t=>t>1||t<-1))){const e=Math.max(...t[0]);t=t.map((t=>t.map((t=>t/e))))}return{length:t[0].length,duration:e,numberOfChannels:t.length,sampleRate:t[0].length/e,getChannelData:e=>t?.[e],copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}};var e=i(139);class n extends e.Z{constructor(t,e){super(),this.options={height:0},this.timeout=null,this.isScrolling=!1,this.channelData=null,this.duration=null,this.resizeObserver=null,this.options={...e};let i=null;if("string"==typeof t.container?i=document.querySelector(t.container):t.container instanceof HTMLElement&&(i=t.container),!i)throw new Error("Container not found");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.wrapper.addEventListener("click",(t=>{const e=this.wrapper.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.emit("click",i)})),this.resizeObserver=new ResizeObserver((()=>{this.delay((()=>this.reRender()),100)})),this.resizeObserver.observe(this.scrollContainer)}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 .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 position: relative;\n height: ${this.options.height}px;\n }\n :host canvas {\n display: block;\n position: absolute;\n top: 0;\n image-rendering: pixelated;\n height: ${this.options.height}px;\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 box-sizing: border-box;\n }\n </style>\n\n <div class="scroll">\n <div class="wrapper">\n <div class="canvases"></div>\n <div class="progress"></div>\n </div>\n </div>\n `,[t,e]}setOptions(t){this.options=t,this.reRender()}getContainer(){return this.scrollContainer}getWrapper(){return this.wrapper}destroy(){this.container.remove(),this.resizeObserver?.disconnect()}delay(t,e=10){return this.timeout&&clearTimeout(this.timeout),new Promise((i=>{this.timeout=setTimeout((()=>{i(t())}),e)}))}async renderPeaks(t,e,i,s){const r=null!=this.options.barWidth?this.options.barWidth*s:1,o=null!=this.options.barGap?this.options.barGap*s:this.options.barWidth?r/2:0,a=this.options.barRadius??0,h=this.options.barHeight??1,d=t[0],l=d.length,u=Math.floor(e/(r+o))/l,c=i/2,p=1===t.length,m=p?d:t[1],g=p&&m.some((t=>t<0)),f=(t,i)=>{let n=0,p=0,f=0;const v=document.createElement("canvas");v.width=Math.round(e*(i-t)/l),v.height=this.options.height,v.style.width=`${Math.floor(v.width/s)}px`,v.style.height=`${this.options.height}px`,v.style.left=`${Math.floor(t*e/s/l)}px`,this.canvasWrapper.appendChild(v);const y=v.getContext("2d",{desynchronized:!0});y.beginPath(),y.fillStyle=this.options.waveColor??"",y.roundRect||(y.roundRect=y.fillRect);for(let e=t;e<i;e++){const i=Math.round((e-t)*u);if(i>n){const t=Math.round(p*c*h),e=Math.round(f*c*h);y.roundRect(n*(r+o),c-t,r,t+(e||1),a),n=i,p=0,f=0}const s=g?d[e]:Math.abs(d[e]),l=g?m[e]:Math.abs(m[e]);s>p&&(p=s),(g?l<-f:l>f)&&(f=l<0?-l:l)}y.fill(),y.closePath();const b=v.cloneNode();this.progressWrapper.appendChild(b);const w=b.getContext("2d",{desynchronized:!0});v.width>0&&v.height>0&&w.drawImage(v,0,0),w.globalCompositeOperation="source-in",w.fillStyle=this.options.progressColor??"",w.fillRect(0,0,v.width,v.height)};this.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="";const{scrollLeft:v,scrollWidth:y,clientWidth:b}=this.scrollContainer,w=l/y;let E=Math.min(n.MAX_CANVAS_WIDTH,b);E-=E%((r+o)/s);const C=Math.floor(Math.abs(v)*w),x=Math.ceil(C+E*w);f(C,x);const P=x-C;for(let t=x;t<l;t+=P)await this.delay((()=>{f(t,Math.min(l,t+P))}));for(let t=C-1;t>=0;t-=P)await this.delay((()=>{f(Math.max(0,t-P),t)}))}render(t,e){const i=window.devicePixelRatio||1,s=this.scrollContainer.clientWidth,n=Math.ceil(e*(this.options.minPxPerSec||0));this.isScrolling=n>s;const r=this.options.fillParent&&!this.isScrolling,o=(r?s:n)*i,{height:a}=this.options;this.wrapper.style.width=r?"100%":`${n}px`,this.scrollContainer.style.overflowX=this.isScrolling?"auto":"hidden",this.scrollContainer.classList.toggle("noScrollbar",!!this.options.hideScrollbar),this.progressWrapper.style.borderRightStyle="solid",this.progressWrapper.style.borderRightColor=`${this.options.cursorColor||this.options.progressColor}`,this.progressWrapper.style.borderRightWidth=`${this.options.cursorWidth}px`,this.canvasWrapper.style.height=`${this.options.height}px`,this.renderPeaks(t,o,a,i),this.channelData=t,this.duration=e}reRender(){if(!this.channelData||!this.duration)return;const t=this.progressWrapper.clientWidth;this.render(this.channelData,this.duration);const e=this.progressWrapper.clientWidth;this.scrollContainer.scrollLeft+=e-t}zoom(t){this.options.minPxPerSec=t,this.reRender()}renderProgress(t,e=!1){if(!isNaN(t)&&(this.progressWrapper.style.width=100*t+"%",this.isScrolling&&this.options.autoCenter)){const{clientWidth:i,scrollLeft:s,scrollWidth:n}=this.scrollContainer,r=n*t,o=i/2,a=o/20;(r>s+(e?o:i)||r<s)&&(r-(s+o)>=a&&r<s+i?this.scrollContainer.scrollLeft+=a:this.scrollContainer.scrollLeft=r-o)}}}n.MAX_CANVAS_WIDTH=4e3;const r=n;class o extends e.Z{constructor(t){super(),this.subscriptions=[],this.isExternalMedia=!1,t.media?(this.media=t.media,this.isExternalMedia=!0):this.media=document.createElement("audio"),t.autoplay&&(this.media.autoplay=!0),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})}loadUrl(t){this.media.src=t}destroy(){this.media.pause(),this.subscriptions.forEach((t=>t())),this.isExternalMedia||this.media.remove()}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)}}const a=o;class h extends e.Z{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 d=h,l={height:128,waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,autoCenter:!0};class u extends a{static create(t){return new u(t)}constructor(t){super({media:t.media,autoplay:t.autoplay,playbackRate:t.audioRate}),this.plugins=[],this.decodedData=null,this.canPlay=!1,this.options=Object.assign({},l,t),this.fetcher=new class{async load(t){return fetch(t).then((t=>t.arrayBuffer()))}},this.timer=new d,this.renderer=new r({container:this.options.container},this.options),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initReadyEvent(),this.initPlugins();const e=this.options.url||this.options.media?.src;e&&this.load(e,this.options.peaks,this.options.duration)}setOptions(t){this.options={...this.options,...t},this.renderer.setOptions(this.options)}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.getCurrentTime()>=this.getDuration()&&this.emit("finish")})),this.onMediaEvent("canplay",(()=>{this.canPlay=!0,this.emit("canplay",this.getDuration())})),this.onMediaEvent("seeking",(()=>{this.emit("seeking",this.getCurrentTime())})))}initRendererEvents(){this.subscriptions.push(this.renderer.on("click",(t=>{this.options.interact&&(this.canPlay&&this.seekTo(t),this.emit("interaction"))})))}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)})))}initReadyEvent(){const t=()=>{this.decodedData&&this.canPlay&&this.emit("ready",this.getDuration())};this.subscriptions.push(this.on("decode",t),this.on("canplay",t))}initPlugins(){this.options.plugins?.length&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}registerPlugin(t){return t.init({wavesurfer:this,container:this.renderer.getContainer(),wrapper:this.renderer.getWrapper()}),this.plugins.push(t),t}getActivePlugins(){return this.plugins}async load(e,i,s){if(this.decodedData=null,this.canPlay=!1,this.loadUrl(e),this.emit("load",e),i)s||(s=await new Promise((t=>{this.onceMediaEvent("loadedmetadata",(()=>t(this.getMediaElement().duration)))}))||0),this.decodedData=t.createBuffer(i,s);else{const i=await this.fetcher.load(e);this.decodedData=await t.decode(i)}this.renderAudio(),this.emit("decode",this.getDuration()),this.emit("redraw")}renderAudio(){if(!this.decodedData)return;const t=[this.decodedData.getChannelData(0)];this.decodedData.numberOfChannels>1&&t.push(this.decodedData.getChannelData(1)),this.renderer.render(t,this.decodedData.duration)}zoom(t){if(!this.decodedData)throw new Error("No audio loaded");this.renderer.zoom(t),this.emit("zoom",t)}getDecodedData(){return this.decodedData}getDuration(){const t=super.getDuration();return t>0&&t<1/0?t:this.decodedData?.duration||0}toggleInteraction(t){this.options.interact=t}seekTo(t){const e=this.getDuration()*t;this.setTime(e)}playPause(){return this.isPlaying()?(this.pause(),Promise.resolve()):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.timer.destroy(),this.renderer.destroy(),super.destroy()}}const c=u;var p=i(76),m=i(954),g=i(919);class f extends e.Z{static create(t,e){return new f(t,e)}constructor(t,e){super(),this.audios=[],this.wavesurfers=[],this.durations=[],this.currentTime=0,this.maxDuration=0,this.isDragging=!1,this.frameRequest=null,this.timer=null,this.subscriptions=[],this.timeline=null,this.tracks=t.map((t=>({...t,startPosition:t.startPosition||0,peaks:t.peaks||(t.url?void 0:[new Float32Array])}))),this.options=e,this.rendering=function(t,e){let i=0,s=[],n=0;const r=document.createElement("div");r.setAttribute("style","width: 100%; overflow-x: scroll; overflow-y: hidden; user-select: none;");const o=document.createElement("div");o.style.position="relative",r.appendChild(o),e.container.appendChild(r);const a=document.createElement("div");a.setAttribute("style","height: 100%; position: absolute; z-index: 10; top: 0; left: 0"),a.style.backgroundColor=e.cursorColor||"#000",a.style.width=`${e.cursorWidth??1}px`,o.appendChild(a);const{clientWidth:h}=o,d=t.map(((t,i)=>{const s=document.createElement("div");if(s.style.position="relative",e.trackBorderColor&&i>0){const t=document.createElement("div");t.setAttribute("style",`width: 100%; height: 2px; background-color: ${e.trackBorderColor}`),o.appendChild(t)}if(e.trackBackground&&t.url&&(s.style.background=e.trackBackground),!t.url){const t=document.createElement("div");t.setAttribute("style",`position: absolute; z-index: 10; left: 10px; top: 10px; right: 10px; bottom: 10px; border: 2px dashed ${e.trackBorderColor};`),t.addEventListener("dragover",(i=>{i.preventDefault(),t.style.background=e.trackBackground||""})),t.addEventListener("dragleave",(e=>{e.preventDefault(),t.style.background=""})),t.addEventListener("drop",(e=>{e.preventDefault(),t.style.background=""})),s.appendChild(t)}return o.appendChild(s),s})),l=()=>{d.forEach(((e,n)=>{const r=t[n].startPosition*i;s[n]&&(e.style.width=s[n]*i+"px"),e.style.transform=`translateX(${r}px)`}))};return{containers:d,setContainerOffsets:l,setMainWidth:(t,r)=>{s=t,i=Math.max(e.minPxPerSec||0,h/r),n=i*r,o.style.width=`${n}px`,l()},updateCursor:(t,e)=>{a.style.left=`${Math.min(100,100*t)}%`;const{clientWidth:i,scrollLeft:s}=r,o=i/2,h=t*n;(h>s+(e?o:i)||h<s)&&(r.scrollLeft=h-o)},addClickHandler:t=>{o.addEventListener("click",(e=>{const i=o.getBoundingClientRect(),s=(e.clientX-i.left)/o.offsetWidth;t(s)}))},destroy:()=>{r.remove()},addDropHandler:e=>{t.forEach(((t,i)=>{if(!t.url){const s=d[i].querySelector("div");s?.addEventListener("drop",(i=>{i.preventDefault(),e(t.id)}))}}))}}}(this.tracks,this.options),this.rendering.addDropHandler((t=>{this.emit("drop",{id:t})})),this.initAllAudios().then((t=>{this.initDurations(t),this.initAllWavesurfers(),this.rendering.containers.forEach(((t,i)=>{const s=v(t,(t=>this.onDrag(i,t)),e.rightButtonDrag);this.wavesurfers[i].once("destroy",(()=>s?.destroy()))})),this.rendering.addClickHandler((t=>{this.isDragging||this.seekTo(t)})),this.emit("canplay")}))}initDurations(t){this.durations=t,this.maxDuration=this.tracks.reduce(((e,i,s)=>Math.max(e,i.startPosition+t[s])),0),this.rendering.setMainWidth(t,this.maxDuration)}initAudio(t){const e=new Audio(t.url);return new Promise((t=>{if(!e.src)return t(e);e.addEventListener("loadedmetadata",(()=>t(e)),{once:!0})}))}async initAllAudios(){return this.audios=await Promise.all(this.tracks.map((t=>this.initAudio(t)))),this.audios.map((t=>t.src?t.duration:0))}initWavesurfer(t,e){const i=this.rendering.containers[e],s=c.create({...t.options,container:i,minPxPerSec:0,media:this.audios[e],peaks:t.peaks,cursorColor:"transparent",cursorWidth:0,interact:!1}),n=p.default.create();s.registerPlugin(n),this.subscriptions.push(s.once("decode",(()=>{if(null!=t.startCue||null!=t.endCue){const{startCue:i=0,endCue:s=this.durations[e]}=t,r=n.addRegion({start:0,end:i,color:"rgba(0, 0, 0, 0.7)",drag:!1}),o=n.addRegion({start:s,end:s+this.durations[e],color:"rgba(0, 0, 0, 0.7)",drag:!1});r.element.firstElementChild?.remove(),o.element.lastChild?.remove(),this.subscriptions.push(r.on("update-end",(()=>{t.startCue=r.end,this.emit("start-cue-change",{id:t.id,startCue:t.startCue})})),o.on("update-end",(()=>{t.endCue=o.start,this.emit("end-cue-change",{id:t.id,endCue:t.endCue})})))}if(t.intro){const e=n.addRegion({start:0,end:t.intro.endTime,content:t.intro.label,color:this.options.trackBackground,drag:!1});e.element.querySelector('[data-resize="left"]')?.remove(),e.element.parentElement.style.mixBlendMode="plus-lighter",t.intro.color&&(e.element.querySelector('[data-resize="right"]').style.borderColor=t.intro.color),this.subscriptions.push(e.on("update-end",(()=>{this.emit("intro-end-change",{id:t.id,endTime:e.end})})))}t.markers&&t.markers.forEach((t=>{n.addRegion({start:t.time,content:t.label,color:t.color,resize:!1})}))})));const r=s.registerPlugin(g.default.create({...this.options.envelopeOptions,fadeInStart:t.startCue,fadeInEnd:t.fadeInEnd,fadeOutStart:t.fadeOutStart,fadeOutEnd:t.endCue,volume:t.volume}));return this.subscriptions.push(r.on("volume-change",(e=>{this.setIsDragging(),this.emit("volume-change",{id:t.id,volume:e})})),r.on("fade-in-change",(e=>{this.setIsDragging(),this.emit("fade-in-change",{id:t.id,fadeInEnd:e})})),r.on("fade-out-change",(e=>{this.setIsDragging(),this.emit("fade-out-change",{id:t.id,fadeOutStart:e})})),this.on("start-cue-change",(({id:e,startCue:i})=>{e===t.id&&r.setStartTime(i)})),this.on("end-cue-change",(({id:e,endCue:i})=>{e===t.id&&r.setEndTime(i)}))),s}initAllWavesurfers(){const t=this.tracks.map(((t,e)=>this.initWavesurfer(t,e)));this.wavesurfers=t,this.initTimeline()}initTimeline(){this.timeline&&this.timeline.destroy(),this.timeline=this.wavesurfers[0].registerPlugin(m.default.create({duration:this.maxDuration,container:this.rendering.containers[0].parentElement}))}updatePosition(t,e=!1){const i=!this.isPlaying();t!==this.currentTime&&(this.currentTime=t,this.rendering.updateCursor(t/this.maxDuration,e)),this.tracks.forEach(((e,s)=>{const n=this.audios[s],r=this.durations[s],o=t-e.startPosition;Math.abs(n.currentTime-o)>.3&&(n.currentTime=o),i||o<0||o>r?!n.paused&&n.pause():i||n.paused&&n.play();const a=o>=(e.startCue||0)&&o<(e.endCue||1/0)?1:0;a!==n.volume&&(n.volume=a)}))}setIsDragging(){this.isDragging=!0,this.timer&&clearTimeout(this.timer),this.timer=setTimeout((()=>this.isDragging=!1),300)}onDrag(t,e){this.setIsDragging();const i=this.tracks[t];if(!i.draggable)return;const s=i.startPosition+e*this.maxDuration,n=this.tracks.findIndex((t=>t.url&&!t.draggable)),r=this.tracks[n],o=(r?r.startPosition:0)-this.durations[t],a=r?r.startPosition+this.durations[n]:this.maxDuration;s>=o&&s<=a&&(i.startPosition=s,this.initDurations(this.durations),this.rendering.setContainerOffsets(),this.updatePosition(this.currentTime),this.emit("start-position-change",{id:i.id,startPosition:s}))}findCurrentTracks(){const t=[];if(this.tracks.forEach(((e,i)=>{e.url&&this.currentTime>=e.startPosition&&this.currentTime<e.startPosition+this.durations[i]&&t.push(i)})),0===t.length){const e=Math.min(...this.tracks.filter((t=>t.url)).map((t=>t.startPosition)));t.push(this.tracks.findIndex((t=>t.startPosition===e)))}return t}startSync(){const t=()=>{const e=this.audios.reduce(((t,e,i)=>(e.paused||(t=Math.max(t,e.currentTime+this.tracks[i].startPosition)),t)),this.currentTime);e>this.currentTime&&this.updatePosition(e,!0),this.frameRequest=requestAnimationFrame(t)};t()}play(){this.startSync(),this.findCurrentTracks().forEach((t=>{this.audios[t]?.play()}))}pause(){this.audios.forEach((t=>t.pause()))}isPlaying(){return this.audios.some((t=>!t.paused))}getCurrentTime(){return this.currentTime}seekTo(t){const e=this.isPlaying();this.updatePosition(t*this.maxDuration),e&&this.play()}setTime(t){const e=this.isPlaying();this.updatePosition(t),e&&this.play()}zoom(t){this.options.minPxPerSec=t,this.wavesurfers.forEach(((e,i)=>this.tracks[i].url&&e.zoom(t))),this.rendering.setMainWidth(this.durations,this.maxDuration),this.rendering.setContainerOffsets()}addTrack(t){const e=this.tracks.findIndex((e=>e.id===t.id));-1!==e&&(this.tracks[e]=t,this.initAudio(t).then((i=>{this.audios[e]=i,this.durations[e]=i.duration,this.initDurations(this.durations);const s=this.rendering.containers[e];s.innerHTML="",this.wavesurfers[e].destroy(),this.wavesurfers[e]=this.initWavesurfer(t,e);const n=v(s,(t=>this.onDrag(e,t)),this.options.rightButtonDrag);this.wavesurfers[e].once("destroy",(()=>n?.destroy())),this.initTimeline(),this.emit("canplay")})))}destroy(){this.frameRequest&&cancelAnimationFrame(this.frameRequest),this.rendering.destroy(),this.audios.forEach((t=>{t.pause(),t.src=""})),this.wavesurfers.forEach((t=>{t.destroy()}))}setSinkId(t){return Promise.all(this.wavesurfers.map((e=>e.setSinkId(t))))}}function v(t,e,i=!1){const s=t.parentElement;if(!s)return;let n=null;t.addEventListener("contextmenu",(t=>{i&&t.preventDefault()})),t.addEventListener("mousedown",(e=>{if(i&&2!==e.button)return;const r=s.getBoundingClientRect();n=e.clientX-r.left,t.style.cursor="grabbing"}));const r=e=>{null!=n&&(e.stopPropagation(),n=null,t.style.cursor="")},o=t=>{if(null==n)return;const i=s.getBoundingClientRect(),r=t.clientX-i.left,o=r-n;(o>1||o<-1)&&(n=r,e(o/s.offsetWidth))};return document.body.addEventListener("mouseup",r),document.body.addEventListener("mousemove",o),{destroy:()=>{document.body.removeEventListener("mouseup",r),document.body.removeEventListener("mousemove",o)}}}const y=f})(),s.default})()));
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Record audio from the microphone, render a waveform and download the audio.
3
+ */
4
+ import BasePlugin from '../base-plugin.js';
5
+ export type RecordPluginOptions = {
6
+ waveColor?: string;
7
+ lineWidth?: number;
8
+ };
9
+ export type RecordPluginEvents = {
10
+ startRecording: [];
11
+ stopRecording: [];
12
+ };
13
+ declare class RecordPlugin extends BasePlugin<RecordPluginEvents, RecordPluginOptions> {
14
+ private mediaRecorder;
15
+ private recordedUrl;
16
+ static create(options?: RecordPluginOptions): RecordPlugin;
17
+ private loadBlob;
18
+ render(stream: MediaStream): () => void;
19
+ private cleanUp;
20
+ startRecording(): Promise<void>;
21
+ isRecording(): boolean;
22
+ stopRecording(): void;
23
+ getRecordedUrl(): string;
24
+ destroy(): void;
25
+ }
26
+ export default RecordPlugin;