wavesurfer.js 7.0.0-beta.5 → 7.0.0-beta.7
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 +1 -5
- package/dist/decoder.d.ts +1 -1
- package/dist/draggable.d.ts +1 -0
- package/dist/draggable.js +57 -0
- package/dist/plugins/envelope.js +4 -25
- package/dist/plugins/envelope.min.js +1 -1
- package/dist/plugins/minimap.min.js +1 -1
- package/dist/plugins/regions.js +13 -51
- package/dist/plugins/regions.min.js +1 -1
- package/dist/plugins/timeline.min.js +1 -1
- package/dist/renderer.d.ts +3 -0
- package/dist/renderer.js +86 -78
- package/dist/wavesurfer.d.ts +7 -2
- package/dist/wavesurfer.js +2 -9
- package/dist/wavesurfer.min.js +1 -1
- package/package.json +4 -1
- package/dist/plugins/envelope.min.cjs +0 -1
- package/dist/plugins/minimap.min.cjs +0 -1
- package/dist/plugins/multitrack.d.ts +0 -117
- package/dist/plugins/multitrack.js +0 -507
- package/dist/plugins/multitrack.min.cjs +0 -1
- package/dist/plugins/multitrack.min.js +0 -1
- package/dist/plugins/record.min.cjs +0 -1
- package/dist/plugins/regions.min.cjs +0 -1
- package/dist/plugins/spectrogram.min.cjs +0 -1
- package/dist/plugins/timeline.min.cjs +0 -1
- package/dist/wavesurfer.min.cjs +0 -1
package/dist/renderer.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { makeDraggable } from './draggable.js';
|
|
1
2
|
import EventEmitter from './event-emitter.js';
|
|
2
3
|
class Renderer extends EventEmitter {
|
|
3
4
|
constructor(options) {
|
|
@@ -8,18 +9,19 @@ class Renderer extends EventEmitter {
|
|
|
8
9
|
this.resizeObserver = null;
|
|
9
10
|
this.isDragging = false;
|
|
10
11
|
this.options = options;
|
|
11
|
-
let
|
|
12
|
+
let parent;
|
|
12
13
|
if (typeof options.container === 'string') {
|
|
13
|
-
|
|
14
|
+
parent = document.querySelector(options.container);
|
|
14
15
|
}
|
|
15
16
|
else if (options.container instanceof HTMLElement) {
|
|
16
|
-
|
|
17
|
+
parent = options.container;
|
|
17
18
|
}
|
|
18
|
-
if (!
|
|
19
|
+
if (!parent) {
|
|
19
20
|
throw new Error('Container not found');
|
|
20
21
|
}
|
|
22
|
+
this.parent = parent;
|
|
21
23
|
const [div, shadow] = this.initHtml();
|
|
22
|
-
|
|
24
|
+
parent.appendChild(div);
|
|
23
25
|
this.container = div;
|
|
24
26
|
this.scrollContainer = shadow.querySelector('.scroll');
|
|
25
27
|
this.wrapper = shadow.querySelector('.wrapper');
|
|
@@ -53,25 +55,19 @@ class Renderer extends EventEmitter {
|
|
|
53
55
|
this.resizeObserver.observe(this.scrollContainer);
|
|
54
56
|
}
|
|
55
57
|
initDrag() {
|
|
56
|
-
this.wrapper
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
document.removeEventListener('mouseup', up);
|
|
70
|
-
this.isDragging = false;
|
|
71
|
-
};
|
|
72
|
-
document.addEventListener('mousemove', move);
|
|
73
|
-
document.addEventListener('mouseup', up);
|
|
74
|
-
});
|
|
58
|
+
makeDraggable(this.wrapper,
|
|
59
|
+
// On drag
|
|
60
|
+
(_, __, x) => {
|
|
61
|
+
this.emit('drag', Math.max(0, Math.min(1, x / this.wrapper.clientWidth)));
|
|
62
|
+
},
|
|
63
|
+
// On start drag
|
|
64
|
+
() => (this.isDragging = true),
|
|
65
|
+
// On end drag
|
|
66
|
+
() => (this.isDragging = false));
|
|
67
|
+
}
|
|
68
|
+
getHeight() {
|
|
69
|
+
const defaultHeight = 128;
|
|
70
|
+
return this.options.height ?? (this.parent.clientHeight || defaultHeight);
|
|
75
71
|
}
|
|
76
72
|
initHtml() {
|
|
77
73
|
const div = document.createElement('div');
|
|
@@ -101,7 +97,7 @@ class Renderer extends EventEmitter {
|
|
|
101
97
|
z-index: 2;
|
|
102
98
|
}
|
|
103
99
|
:host .canvases {
|
|
104
|
-
min-height: ${this.
|
|
100
|
+
min-height: ${this.getHeight()}px;
|
|
105
101
|
}
|
|
106
102
|
:host .canvases > div {
|
|
107
103
|
position: relative;
|
|
@@ -185,66 +181,77 @@ class Renderer extends EventEmitter {
|
|
|
185
181
|
});
|
|
186
182
|
return gradient;
|
|
187
183
|
}
|
|
188
|
-
|
|
184
|
+
renderBars(channelData, options, ctx) {
|
|
185
|
+
ctx.fillStyle = this.convertColorValues(options.waveColor);
|
|
186
|
+
// Custom rendering function
|
|
187
|
+
if (options.renderFunction) {
|
|
188
|
+
options.renderFunction(channelData, ctx);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const topChannel = channelData[0];
|
|
192
|
+
const bottomChannel = channelData[1] || channelData[0];
|
|
193
|
+
const length = topChannel.length;
|
|
189
194
|
const pixelRatio = window.devicePixelRatio || 1;
|
|
190
|
-
const height =
|
|
191
|
-
const barWidth = options.barWidth != null && !isNaN(options.barWidth) ? options.barWidth * pixelRatio : 1;
|
|
192
|
-
const barGap = options.barGap != null && !isNaN(options.barGap)
|
|
193
|
-
? options.barGap * pixelRatio
|
|
194
|
-
: options.barWidth
|
|
195
|
-
? barWidth / 2
|
|
196
|
-
: 0;
|
|
197
|
-
const barRadius = options.barRadius || 0;
|
|
198
|
-
const barScale = options.barHeight || 1;
|
|
199
|
-
const isMono = channelData.length === 1;
|
|
200
|
-
const leftChannel = channelData[0];
|
|
201
|
-
const rightChannel = isMono ? leftChannel : channelData[1];
|
|
202
|
-
const useNegative = isMono && rightChannel.some((v) => v < 0);
|
|
203
|
-
const length = leftChannel.length;
|
|
204
|
-
const barCount = Math.floor(width / (barWidth + barGap));
|
|
205
|
-
const barIndexScale = barCount / length;
|
|
195
|
+
const { width, height } = ctx.canvas;
|
|
206
196
|
const halfHeight = height / 2;
|
|
197
|
+
const barHeight = options.barHeight || 1;
|
|
198
|
+
const barWidth = options.barWidth ? options.barWidth * pixelRatio : 1;
|
|
199
|
+
const barGap = options.barGap ? options.barGap * pixelRatio : options.barWidth ? barWidth / 2 : 0;
|
|
200
|
+
const barRadius = options.barRadius || 0;
|
|
201
|
+
const barIndexScale = width / (barWidth + barGap) / length;
|
|
202
|
+
let max = 1;
|
|
203
|
+
if (options.normalize) {
|
|
204
|
+
max = 0;
|
|
205
|
+
for (let i = 0; i < length; i++) {
|
|
206
|
+
const value = Math.abs(topChannel[i]);
|
|
207
|
+
if (value > max)
|
|
208
|
+
max = value;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const vScale = (halfHeight / max) * barHeight;
|
|
212
|
+
ctx.beginPath();
|
|
207
213
|
let prevX = 0;
|
|
208
|
-
let
|
|
209
|
-
let
|
|
214
|
+
let maxTop = 0;
|
|
215
|
+
let maxBottom = 0;
|
|
216
|
+
for (let i = 0; i <= length; i++) {
|
|
217
|
+
const x = Math.round(i * barIndexScale);
|
|
218
|
+
if (x > prevX) {
|
|
219
|
+
const leftBarHeight = Math.round(maxTop * vScale);
|
|
220
|
+
const rightBarHeight = Math.round(maxBottom * vScale);
|
|
221
|
+
const barHeight = leftBarHeight + rightBarHeight || 1;
|
|
222
|
+
// Vertical alignment
|
|
223
|
+
let y = halfHeight - leftBarHeight;
|
|
224
|
+
if (options.barAlign === 'top')
|
|
225
|
+
y = 0;
|
|
226
|
+
else if (options.barAlign === 'bottom')
|
|
227
|
+
y = height - barHeight;
|
|
228
|
+
ctx.roundRect(prevX * (barWidth + barGap), y, barWidth, barHeight, barRadius);
|
|
229
|
+
prevX = x;
|
|
230
|
+
maxTop = 0;
|
|
231
|
+
maxBottom = 0;
|
|
232
|
+
}
|
|
233
|
+
const magnitudeTop = Math.abs(topChannel[i] || 0);
|
|
234
|
+
const magnitudeBottom = Math.abs(bottomChannel[i] || 0);
|
|
235
|
+
if (magnitudeTop > maxTop)
|
|
236
|
+
maxTop = magnitudeTop;
|
|
237
|
+
if (magnitudeBottom > maxBottom)
|
|
238
|
+
maxBottom = magnitudeBottom;
|
|
239
|
+
}
|
|
240
|
+
ctx.fill();
|
|
241
|
+
ctx.closePath();
|
|
242
|
+
}
|
|
243
|
+
renderSingleCanvas(channelData, options, width, height, start, end, canvasContainer, progressContainer) {
|
|
244
|
+
const pixelRatio = window.devicePixelRatio || 1;
|
|
210
245
|
const canvas = document.createElement('canvas');
|
|
246
|
+
const length = channelData[0].length;
|
|
211
247
|
canvas.width = Math.round((width * (end - start)) / length);
|
|
212
248
|
canvas.height = height;
|
|
213
249
|
canvas.style.width = `${Math.floor(canvas.width / pixelRatio)}px`;
|
|
214
|
-
canvas.style.height = `${
|
|
250
|
+
canvas.style.height = `${height}px`;
|
|
215
251
|
canvas.style.left = `${Math.floor((start * width) / pixelRatio / length)}px`;
|
|
216
252
|
canvasContainer.appendChild(canvas);
|
|
217
|
-
const ctx = canvas.getContext('2d'
|
|
218
|
-
|
|
219
|
-
});
|
|
220
|
-
ctx.beginPath();
|
|
221
|
-
ctx.fillStyle = this.convertColorValues(options.waveColor);
|
|
222
|
-
// Firefox shim until 2023.04.11
|
|
223
|
-
if (!ctx.roundRect)
|
|
224
|
-
ctx.roundRect = ctx.fillRect;
|
|
225
|
-
for (let i = start; i < end; i++) {
|
|
226
|
-
const barIndex = Math.round((i - start) * barIndexScale);
|
|
227
|
-
if (barIndex > prevX) {
|
|
228
|
-
const leftBarHeight = Math.round(prevLeft * halfHeight * barScale);
|
|
229
|
-
const rightBarHeight = Math.round(prevRight * halfHeight * barScale);
|
|
230
|
-
ctx.roundRect(prevX * (barWidth + barGap), halfHeight - leftBarHeight, barWidth, leftBarHeight + (rightBarHeight || 1), barRadius);
|
|
231
|
-
prevX = barIndex;
|
|
232
|
-
prevLeft = 0;
|
|
233
|
-
prevRight = 0;
|
|
234
|
-
}
|
|
235
|
-
const leftValue = useNegative ? leftChannel[i] : Math.abs(leftChannel[i]);
|
|
236
|
-
const rightValue = useNegative ? rightChannel[i] : Math.abs(rightChannel[i]);
|
|
237
|
-
if (leftValue > prevLeft) {
|
|
238
|
-
prevLeft = leftValue;
|
|
239
|
-
}
|
|
240
|
-
// If stereo, both channels are drawn as max values
|
|
241
|
-
// If mono with negative values, the bottom channel will be the min negative values
|
|
242
|
-
if (useNegative ? rightValue < -prevRight : rightValue > prevRight) {
|
|
243
|
-
prevRight = rightValue < 0 ? -rightValue : rightValue;
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
ctx.fill();
|
|
247
|
-
ctx.closePath();
|
|
253
|
+
const ctx = canvas.getContext('2d');
|
|
254
|
+
this.renderBars(channelData.map((channel) => channel.slice(start, end)), options, ctx);
|
|
248
255
|
// Draw a progress canvas
|
|
249
256
|
const progressCanvas = canvas.cloneNode();
|
|
250
257
|
progressContainer.appendChild(progressCanvas);
|
|
@@ -263,7 +270,8 @@ class Renderer extends EventEmitter {
|
|
|
263
270
|
renderWaveform(channelData, options, width) {
|
|
264
271
|
// A container for canvases
|
|
265
272
|
const canvasContainer = document.createElement('div');
|
|
266
|
-
|
|
273
|
+
const height = this.getHeight();
|
|
274
|
+
canvasContainer.style.height = `${height}px`;
|
|
267
275
|
this.canvasWrapper.appendChild(canvasContainer);
|
|
268
276
|
// A container for progress canvases
|
|
269
277
|
const progressContainer = canvasContainer.cloneNode();
|
|
@@ -278,7 +286,7 @@ class Renderer extends EventEmitter {
|
|
|
278
286
|
const viewportLen = end - start;
|
|
279
287
|
// Draw a portion of the waveform from start peak to end peak
|
|
280
288
|
const draw = (start, end) => {
|
|
281
|
-
this.renderSingleCanvas(channelData, options, width, Math.max(0, start), Math.min(end, len), canvasContainer, progressContainer);
|
|
289
|
+
this.renderSingleCanvas(channelData, options, width, height, Math.max(0, start), Math.min(end, len), canvasContainer, progressContainer);
|
|
282
290
|
};
|
|
283
291
|
// Draw the waveform in viewport chunks, each with a delay
|
|
284
292
|
const headDelay = this.createDelay();
|
package/dist/wavesurfer.d.ts
CHANGED
|
@@ -22,6 +22,8 @@ export type WaveSurferOptions = {
|
|
|
22
22
|
barRadius?: number;
|
|
23
23
|
/** A vertical scaling factor for the waveform */
|
|
24
24
|
barHeight?: number;
|
|
25
|
+
/** Vertical bar alignment **/
|
|
26
|
+
barAlign?: 'top' | 'bottom';
|
|
25
27
|
/** Minimum pixels per second of audio (i.e. zoom level) */
|
|
26
28
|
minPxPerSec?: number;
|
|
27
29
|
/** Stretch the waveform to fill the container, true by default */
|
|
@@ -29,7 +31,7 @@ export type WaveSurferOptions = {
|
|
|
29
31
|
/** Audio URL */
|
|
30
32
|
url?: string;
|
|
31
33
|
/** Pre-computed audio data */
|
|
32
|
-
peaks?: Float32Array
|
|
34
|
+
peaks?: Array<Float32Array | number[]>;
|
|
33
35
|
/** Pre-computed duration */
|
|
34
36
|
duration?: number;
|
|
35
37
|
/** Use an existing media element instead of creating one */
|
|
@@ -50,11 +52,14 @@ export type WaveSurferOptions = {
|
|
|
50
52
|
sampleRate?: number;
|
|
51
53
|
/** Render each audio channel as a separate waveform */
|
|
52
54
|
splitChannels?: WaveSurferOptions[];
|
|
55
|
+
/** Stretch the waveform to the full height */
|
|
56
|
+
normalize?: boolean;
|
|
53
57
|
/** The list of plugins to initialize on start */
|
|
54
58
|
plugins?: GenericPlugin[];
|
|
59
|
+
/** Custom render function */
|
|
60
|
+
renderFunction?: (peaks: Array<Float32Array | number[]>, ctx: CanvasRenderingContext2D) => void;
|
|
55
61
|
};
|
|
56
62
|
declare const defaultOptions: {
|
|
57
|
-
height: number;
|
|
58
63
|
waveColor: WaveSurferColor;
|
|
59
64
|
progressColor: WaveSurferColor;
|
|
60
65
|
cursorWidth: number;
|
package/dist/wavesurfer.js
CHANGED
|
@@ -4,7 +4,6 @@ import Player from './player.js';
|
|
|
4
4
|
import Renderer from './renderer.js';
|
|
5
5
|
import Timer from './timer.js';
|
|
6
6
|
const defaultOptions = {
|
|
7
|
-
height: 128,
|
|
8
7
|
waveColor: '#999',
|
|
9
8
|
progressColor: '#555',
|
|
10
9
|
cursorWidth: 1,
|
|
@@ -191,14 +190,8 @@ class WaveSurfer extends Player {
|
|
|
191
190
|
this.setTime(time);
|
|
192
191
|
}
|
|
193
192
|
/** Play or pause the audio */
|
|
194
|
-
playPause() {
|
|
195
|
-
|
|
196
|
-
this.pause();
|
|
197
|
-
return Promise.resolve();
|
|
198
|
-
}
|
|
199
|
-
else {
|
|
200
|
-
return this.play();
|
|
201
|
-
}
|
|
193
|
+
async playPause() {
|
|
194
|
+
return this.isPlaying() ? this.pause() : this.play();
|
|
202
195
|
}
|
|
203
196
|
/** Stop the audio and go to the beginning */
|
|
204
197
|
stop() {
|
package/dist/wavesurfer.min.js
CHANGED
|
@@ -1 +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.WaveSurfer=e():t.WaveSurfer=e()}(this,(()=>(()=>{"use strict";var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{default:()=>d});const i={decode:async function(t,e){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=>t?.[e],copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}},s=async function(t){return fetch(t).then((t=>t.arrayBuffer()))},r=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)))}},n=class extends r{constructor(t){super(),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})}revokeSrc(){(this.media.currentSrc||this.media.src||"").startsWith("blob:")&&URL.revokeObjectURL(this.media.currentSrc)}setSrc(t,e){if((this.media.currentSrc||this.media.src||"")===t)return;this.revokeSrc();const i=e?URL.createObjectURL(new Blob([e],{type:"audio/wav"})):t;this.media.src=i}destroy(){this.media.pause(),this.revokeSrc(),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)}};class o extends r{constructor(t){let e;if(super(),this.timeouts=[],this.isScrolling=!1,this.audioData=null,this.resizeObserver=null,this.isDragging=!1,this.options=t,"string"==typeof t.container?e=document.querySelector(t.container):t.container instanceof HTMLElement&&(e=t.container),!e)throw new Error("Container not found");const[i,s]=this.initHtml();e.appendChild(i),this.container=i,this.scrollContainer=s.querySelector(".scroll"),this.wrapper=s.querySelector(".wrapper"),this.canvasWrapper=s.querySelector(".canvases"),this.progressWrapper=s.querySelector(".progress"),this.cursor=s.querySelector(".cursor"),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,r=(t+i)/e;this.emit("scroll",s,r)}));const t=this.createDelay(100);this.resizeObserver=new ResizeObserver((()=>{t((()=>this.reRender()))})),this.resizeObserver.observe(this.scrollContainer)}initDrag(){this.wrapper.addEventListener("mousedown",(t=>{const e=t.clientX,i=t=>{if(Math.abs(t.clientX-e)>=5){this.isDragging=!0;const e=this.wrapper.getBoundingClientRect();this.emit("drag",Math.max(0,Math.min(1,(t.clientX-e.left)/e.width)))}},s=()=>{document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",s),this.isDragging=!1};document.addEventListener("mousemove",i),document.addEventListener("mouseup",s)}))}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 min-height: ${this.options.height}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"></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(){this.container.remove(),this.resizeObserver?.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 1===t.length?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 r=e*s;i.addColorStop(r,t)})),i}renderSingleCanvas(t,e,i,s,r,n,o){const a=window.devicePixelRatio||1,h=e.height||0,l=null==e.barWidth||isNaN(e.barWidth)?1:e.barWidth*a,c=null==e.barGap||isNaN(e.barGap)?e.barWidth?l/2:0:e.barGap*a,d=e.barRadius||0,u=e.barHeight||1,p=1===t.length,m=t[0],g=p?m:t[1],f=p&&g.some((t=>t<0)),v=m.length,y=Math.floor(i/(l+c))/v,b=h/2;let C=0,w=0,S=0;const E=document.createElement("canvas");E.width=Math.round(i*(r-s)/v),E.height=h,E.style.width=`${Math.floor(E.width/a)}px`,E.style.height=`${e.height}px`,E.style.left=`${Math.floor(s*i/a/v)}px`,n.appendChild(E);const M=E.getContext("2d",{desynchronized:!0});M.beginPath(),M.fillStyle=this.convertColorValues(e.waveColor),M.roundRect||(M.roundRect=M.fillRect);for(let t=s;t<r;t++){const e=Math.round((t-s)*y);if(e>C){const t=Math.round(w*b*u),i=Math.round(S*b*u);M.roundRect(C*(l+c),b-t,l,t+(i||1),d),C=e,w=0,S=0}const i=f?m[t]:Math.abs(m[t]),r=f?g[t]:Math.abs(g[t]);i>w&&(w=i),(f?r<-S:r>S)&&(S=r<0?-r:r)}M.fill(),M.closePath();const D=E.cloneNode();o.appendChild(D);const R=D.getContext("2d",{desynchronized:!0});E.width>0&&E.height>0&&R.drawImage(E,0,0),R.globalCompositeOperation="source-in",R.fillStyle=this.convertColorValues(e.progressColor),R.fillRect(0,0,E.width,E.height)}renderWaveform(t,e,i){const s=document.createElement("div");s.style.height=`${e.height}px`,this.canvasWrapper.appendChild(s);const r=s.cloneNode();this.progressWrapper.appendChild(r);const{scrollLeft:n,scrollWidth:a,clientWidth:h}=this.scrollContainer,l=t[0].length,c=l/a,d=Math.min(o.MAX_CANVAS_WIDTH,h),u=Math.floor(Math.abs(n)*c),p=Math.ceil(u+d*c),m=p-u,g=(n,o)=>{this.renderSingleCanvas(t,e,i,Math.max(0,n),Math.min(o,l),s,r)},f=this.createDelay(),v=this.createDelay(),y=(t,e)=>{g(t,e),t>0&&f((()=>{y(t-m,e-m)}))},b=(t,e)=>{g(t,e),e<l&&v((()=>{b(t+m,e+m)}))};y(u,p),p<l&&b(p,p+m)}render(t){this.timeouts.forEach((t=>t.timeout&&clearTimeout(t.timeout))),this.timeouts=[];const e=window.devicePixelRatio||1,i=this.scrollContainer.clientWidth,s=Math.ceil(t.duration*(this.options.minPxPerSec||0));this.isScrolling=s>i;const r=this.options.fillParent&&!this.isScrolling,n=(r?i:s)*e;if(this.wrapper.style.width=r?"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.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="",this.options.splitChannels)for(let e=0;e<t.numberOfChannels;e++){const i={...this.options,...this.options.splitChannels[e]};this.renderWaveform([t.getChannelData(e)],i,n)}else{const e=[t.getChannelData(0)];t.numberOfChannels>1&&e.push(t.getChannelData(1)),this.renderWaveform(e,this.options,n)}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:r}=this.scrollContainer,n=r*t,o=i/2;if(n>s+(e&&this.options.autoCenter&&!this.isDragging?o:i)||n<s)if(this.options.autoCenter&&!this.isDragging){const t=o/20;n-(s+o)>=t&&n<s+i?this.scrollContainer.scrollLeft+=t:this.scrollContainer.scrollLeft=n-o}else if(this.isDragging){const t=10;this.scrollContainer.scrollLeft=n<s?n-t:n-i+t}else this.scrollContainer.scrollLeft=n;{const{scrollLeft:t}=this.scrollContainer,e=t/r,s=(t+i)/r;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;const a=o,h=class extends r{constructor(){super(...arguments),this.unsubscribe=()=>{}}start(){this.unsubscribe=this.on("tick",(()=>{requestAnimationFrame((()=>{this.emit("tick")}))})),this.emit("tick")}stop(){this.unsubscribe()}destroy(){this.unsubscribe()}},l={height:128,waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,autoScroll:!0,autoCenter:!0,sampleRate:8e3};class c extends n{static create(t){return new c(t)}constructor(t){super({media:t.media,autoplay:t.autoplay,playbackRate:t.audioRate}),this.plugins=[],this.decodedData=null,this.subscriptions=[],this.options=Object.assign({},l,t),this.timer=new h,this.renderer=new a(this.options),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initPlugins();const e=this.options.url||this.options.media?.currentSrc||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),t.audioRate&&this.setPlaybackRate(t.audioRate)}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.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"),this.emit("drag",e))})))}}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)})))}initPlugins(){this.options.plugins?.length&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}registerPlugin(t){return t.init(this),this.plugins.push(t),t}getWrapper(){return this.renderer.getWrapper()}getScroll(){return this.renderer.getScroll()}getActivePlugins(){return this.plugins}async load(t,e,r){if(this.decodedData=null,this.emit("load",t),e)this.setSrc(t),r||(r=await new Promise((t=>{this.onceMediaEvent("loadedmetadata",(()=>t(this.getMediaElement().duration)))}))||0),this.decodedData=i.createBuffer(e,r);else{const e=await s(t);this.setSrc(t,e),this.decodedData=await i.decode(e,this.options.sampleRate)}this.emit("decode",this.getDuration()),this.emit("ready",this.getDuration()),this.renderer.render(this.decodedData)}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.subscriptions.forEach((t=>t())),this.plugins.forEach((t=>t.destroy())),this.timer.destroy(),this.renderer.destroy(),super.destroy()}}const d=c;return e.default})()));
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.WaveSurfer=e():t.WaveSurfer=e()}(this,(()=>(()=>{"use strict";var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{default:()=>d});const i={decode:async function(t,e){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=>t?.[e],copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}},s=async function(t){return fetch(t).then((t=>t.arrayBuffer()))},n=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)))}},r=class extends n{constructor(t){super(),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})}revokeSrc(){(this.media.currentSrc||this.media.src||"").startsWith("blob:")&&URL.revokeObjectURL(this.media.currentSrc)}setSrc(t,e){if((this.media.currentSrc||this.media.src||"")===t)return;this.revokeSrc();const i=e?URL.createObjectURL(new Blob([e],{type:"audio/wav"})):t;this.media.src=i}destroy(){this.media.pause(),this.revokeSrc(),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)}};class o extends n{constructor(t){let e;if(super(),this.timeouts=[],this.isScrolling=!1,this.audioData=null,this.resizeObserver=null,this.isDragging=!1,this.options=t,"string"==typeof t.container?e=document.querySelector(t.container):t.container instanceof HTMLElement&&(e=t.container),!e)throw new Error("Container not found");this.parent=e;const[i,s]=this.initHtml();e.appendChild(i),this.container=i,this.scrollContainer=s.querySelector(".scroll"),this.wrapper=s.querySelector(".wrapper"),this.canvasWrapper=s.querySelector(".canvases"),this.progressWrapper=s.querySelector(".progress"),this.cursor=s.querySelector(".cursor"),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;t.addEventListener("pointerdown",(o=>{o.preventDefault(),o.stopPropagation();let a=o.clientX,h=o.clientY,l=!1;const c=s=>{s.preventDefault(),s.stopPropagation();const r=s.clientX,o=s.clientY;if(l||Math.abs(r-a)>=n||Math.abs(o-h)>=n){l||(l=!0,i?.(a,h));const{left:s,top:n}=t.getBoundingClientRect();e(r-a,o-h,r-s,o-n),a=r,h=o}},d=t=>{l&&(t.preventDefault(),t.stopPropagation())};r=()=>{document.removeEventListener("pointermove",c),document.removeEventListener("pointerup",u),setTimeout((()=>{document.removeEventListener("click",d,!0)}),10)};const u=()=>{l&&s?.(),r()};document.addEventListener("pointermove",c),document.addEventListener("pointerup",u),document.addEventListener("click",d,!0)}))}(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 this.options.height??(this.parent.clientHeight||128)}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 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"></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(){this.container.remove(),this.resizeObserver?.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 1===t.length?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,c=e.barHeight||1,d=e.barWidth?e.barWidth*o:1,u=e.barGap?e.barGap*o:e.barWidth?d/2:0,p=e.barRadius||0,m=a/(d+u)/r;let g=1;if(e.normalize){g=0;for(let t=0;t<r;t++){const e=Math.abs(s[t]);e>g&&(g=e)}}const v=l/g*c;i.beginPath();let f=0,y=0,b=0;for(let t=0;t<=r;t++){const r=Math.round(t*m);if(r>f){const t=Math.round(y*v),s=t+Math.round(b*v)||1;let n=l-t;"top"===e.barAlign?n=0:"bottom"===e.barAlign&&(n=h-s),i.roundRect(f*(d+u),n,d,s,p),f=r,y=0,b=0}const o=Math.abs(s[t]||0),a=Math.abs(n[t]||0);o>y&&(y=o),a>b&&(b=a)}i.fill(),i.closePath()}renderSingleCanvas(t,e,i,s,n,r,o,a){const h=window.devicePixelRatio||1,l=document.createElement("canvas"),c=t[0].length;l.width=Math.round(i*(r-n)/c),l.height=s,l.style.width=`${Math.floor(l.width/h)}px`,l.style.height=`${s}px`,l.style.left=`${Math.floor(n*i/h/c)}px`,o.appendChild(l);const d=l.getContext("2d");this.renderBars(t.map((t=>t.slice(n,r))),e,d);const u=l.cloneNode();a.appendChild(u);const p=u.getContext("2d",{desynchronized:!0});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.appendChild(s);const r=s.cloneNode();this.progressWrapper.appendChild(r);const{scrollLeft:a,scrollWidth:h,clientWidth:l}=this.scrollContainer,c=t[0].length,d=c/h,u=Math.min(o.MAX_CANVAS_WIDTH,l),p=Math.floor(Math.abs(a)*d),m=Math.ceil(p+u*d),g=m-p,v=(o,a)=>{this.renderSingleCanvas(t,e,i,n,Math.max(0,o),Math.min(a,c),s,r)},f=this.createDelay(),y=this.createDelay(),b=(t,e)=>{v(t,e),t>0&&f((()=>{b(t-g,e-g)}))},C=(t,e)=>{v(t,e),e<c&&y((()=>{C(t+g,e+g)}))};b(p,m),m<c&&C(m,m+g)}render(t){this.timeouts.forEach((t=>t.timeout&&clearTimeout(t.timeout))),this.timeouts=[];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.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="",this.options.splitChannels)for(let e=0;e<t.numberOfChannels;e++){const i={...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;const a=o,h=class extends n{constructor(){super(...arguments),this.unsubscribe=()=>{}}start(){this.unsubscribe=this.on("tick",(()=>{requestAnimationFrame((()=>{this.emit("tick")}))})),this.emit("tick")}stop(){this.unsubscribe()}destroy(){this.unsubscribe()}},l={waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,autoScroll:!0,autoCenter:!0,sampleRate:8e3};class c extends r{static create(t){return new c(t)}constructor(t){super({media:t.media,autoplay:t.autoplay,playbackRate:t.audioRate}),this.plugins=[],this.decodedData=null,this.subscriptions=[],this.options=Object.assign({},l,t),this.timer=new h,this.renderer=new a(this.options),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initPlugins();const e=this.options.url||this.options.media?.currentSrc||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),t.audioRate&&this.setPlaybackRate(t.audioRate)}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.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"),this.emit("drag",e))})))}}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)})))}initPlugins(){this.options.plugins?.length&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}registerPlugin(t){return t.init(this),this.plugins.push(t),t}getWrapper(){return this.renderer.getWrapper()}getScroll(){return this.renderer.getScroll()}getActivePlugins(){return this.plugins}async load(t,e,n){if(this.decodedData=null,this.emit("load",t),e)this.setSrc(t),n||(n=await new Promise((t=>{this.onceMediaEvent("loadedmetadata",(()=>t(this.getMediaElement().duration)))}))||0),this.decodedData=i.createBuffer(e,n);else{const e=await s(t);this.setSrc(t,e),this.decodedData=await i.decode(e,this.options.sampleRate)}this.emit("decode",this.getDuration()),this.emit("ready",this.getDuration()),this.renderer.render(this.decodedData)}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)}async playPause(){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.subscriptions.forEach((t=>t())),this.plugins.forEach((t=>t.destroy())),this.timer.destroy(),this.renderer.destroy(),super.destroy()}}const d=c;return e.default})()));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wavesurfer.js",
|
|
3
|
-
"version": "7.0.0-beta.
|
|
3
|
+
"version": "7.0.0-beta.7",
|
|
4
4
|
"license": "BSD-3-Clause",
|
|
5
5
|
"author": "katspaugh",
|
|
6
6
|
"description": "Navigable audio waveform player",
|
|
@@ -28,6 +28,9 @@
|
|
|
28
28
|
"import": "./dist/wavesurfer.js",
|
|
29
29
|
"require": "./dist/wavesurfer.min.js"
|
|
30
30
|
},
|
|
31
|
+
"./dist/*": {
|
|
32
|
+
"import": "./dist/*"
|
|
33
|
+
},
|
|
31
34
|
"./dist/plugins/*": {
|
|
32
35
|
"import": "./dist/plugins/*.js",
|
|
33
36
|
"require": "./dist/plugins/*.min.js"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Envelope=e():t.Envelope=e()}(WaveSurfer,(()=>(()=>{"use strict";var t={284:(t,e,i)=>{i.d(e,{Z:()=>o});var s=i(139);class n extends s.Z{constructor(t){super(),this.subscriptions=[],this.options=t}onInit(){}init(t){this.wavesurfer=t,this.onInit()}destroy(){this.subscriptions.forEach((t=>t()))}}const o=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)))}}}},e={};function i(s){var n=e[s];if(void 0!==n)return n.exports;var o=e[s]={exports:{}};return t[s](o,o.exports,i),o.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:()=>a});var t=i(284),e=i(139);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 o extends e.Z{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 s=document.createElementNS("http://www.w3.org/2000/svg","polyline");s.setAttribute("points","0,0 0,0 0,0 0,0"),s.setAttribute("stroke",t.lineColor),s.setAttribute("stroke-width",t.lineWidth),s.setAttribute("fill","none"),s.setAttribute("style","pointer-events: none;"),s.setAttribute("part","polyline"),i.appendChild(s);const n=document.createElementNS("http://www.w3.org/2000/svg","line");n.setAttribute("stroke","transparent"),n.setAttribute("stroke-width",(3*t.lineWidth).toString()),n.setAttribute("style","cursor: ns-resize; pointer-events: all;"),n.setAttribute("part","line"),i.appendChild(n),[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:s}=i.viewBox.baseVal;if(e<-.5||e>s)return;const n=Math.min(1,Math.max(0,(s-e)/s));this.emit("line-move",n)},e=(t,e)=>{const n=s.points.getItem(t).x+e,{width:o}=i.viewBox.baseVal;this.emit("point-move",t,n/o)};this.makeDraggable(n,((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){t.addEventListener("click",(t=>{t.preventDefault(),t.stopPropagation()})),t.addEventListener("mousedown",(t=>{t.preventDefault(),t.stopPropagation();let i=t.clientX,s=t.clientY;const n=t=>{const n=t.clientX-i,o=t.clientY-s;i=t.clientX,s=t.clientY,e(n,o)},o=()=>{document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",o)};document.addEventListener("mousemove",n),document.addEventListener("mouseup",o)}))}update({x1:t,x2:e,x3:i,x4:s,y:n}){const o=this.svg.clientWidth,r=this.svg.clientHeight;this.top=r-n*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:h}=u;h.getItem(0).x=t*o,h.getItem(0).y=r,h.getItem(1).x=e*o,h.getItem(1).y=a,h.getItem(2).x=i*o,h.getItem(2).y=a,h.getItem(3).x=s*o,h.getItem(3).y=r;const d=this.svg.querySelector("line");d.setAttribute("x1",h.getItem(1).x.toString()),d.setAttribute("x2",h.getItem(2).x.toString()),d.setAttribute("y1",a.toString()),d.setAttribute("y2",a.toString());const l=this.svg.querySelectorAll("circle");Array.from(l).forEach(((t,e)=>{const i=h.getItem(e+1);t.setAttribute("cx",i.x.toString()),t.setAttribute("cy",i.y.toString())}))}destroy(){this.svg.remove()}}class r extends t.Z{constructor(t){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({},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)}destroy(){this.polyline?.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",(()=>{const t=this.wavesurfer?.getDuration();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.renderPolyline())})))}initSvg(){if(!this.wavesurfer)return;const t=this.wavesurfer.getWrapper();this.polyline=new o(this.options,t),this.subscriptions.push(this.polyline.on("line-move",(t=>{this.setVolume(this.naturalVolume(t))})),this.polyline.on("point-move",((t,e)=>{const i=e*(this.wavesurfer?.getDuration()||0);if(1===t){if(i<this.options.fadeInStart||i>this.options.fadeOutStart)return;this.options.fadeInEnd=i,this.emit("fade-in-change",i)}else if(2===t){if(i>this.options.fadeOutEnd||i<this.options.fadeInEnd)return;this.options.fadeOutStart=i,this.emit("fade-out-change",i)}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(){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.setGainValue(),e.createMediaElementSource(t).connect(this.gainNode),this.gainNode.connect(e.destination),this.audioContext=e}invertNaturalVolume(t){return Math.pow((t-1e-4)/.9999,1/this.naturalVolumeExponent)}naturalVolume(t){return 1e-4+.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=>{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,this.gainNode.gain.setValueAtTime(this.volume,this.audioContext.currentTime),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.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()}setVolume(t){this.volume=t,this.setGainValue(),this.renderPolyline(),this.emit("volume-change",t)}}const a=r})(),s.default})()));
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Minimap=e():t.Minimap=e()}(WaveSurfer,(()=>(()=>{"use strict";var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{default:()=>g});const i=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)))}},s=class extends i{constructor(t){super(),this.subscriptions=[],this.options=t}onInit(){}init(t){this.wavesurfer=t,this.onInit()}destroy(){this.subscriptions.forEach((t=>t()))}},r={decode:async function(t,e){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=>t?.[e],copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}},n=async function(t){return fetch(t).then((t=>t.arrayBuffer()))},o=class extends i{constructor(t){super(),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})}revokeSrc(){(this.media.currentSrc||this.media.src||"").startsWith("blob:")&&URL.revokeObjectURL(this.media.currentSrc)}setSrc(t,e){if((this.media.currentSrc||this.media.src||"")===t)return;this.revokeSrc();const i=e?URL.createObjectURL(new Blob([e],{type:"audio/wav"})):t;this.media.src=i}destroy(){this.media.pause(),this.revokeSrc(),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)}};class a extends i{constructor(t,e){if(super(),this.options={height:0},this.timeout=null,this.isScrolling=!1,this.audioData=null,this.resizeObserver=null,this.isDragging=!1,this.options={...e},"string"==typeof t&&(t=document.querySelector(t)),!t)throw new Error("Container not found");const[i,s]=this.initHtml();t.appendChild(i),this.container=i,this.scrollContainer=s.querySelector(".scroll"),this.wrapper=s.querySelector(".wrapper"),this.canvasWrapper=s.querySelector(".canvases"),this.progressWrapper=s.querySelector(".progress"),this.cursor=s.querySelector(".cursor"),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,r=(t+i)/e;this.emit("scroll",s,r)})),this.resizeObserver=new ResizeObserver((()=>{this.delay((()=>this.reRender()),100)})),this.resizeObserver.observe(this.scrollContainer)}initDrag(){this.wrapper.addEventListener("mousedown",(t=>{const e=t.clientX,i=t=>{if(Math.abs(t.clientX-e)>=5){this.isDragging=!0;const e=this.wrapper.getBoundingClientRect();this.emit("drag",Math.max(0,Math.min(1,(t.clientX-e.left)/e.width)))}},s=()=>{document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",s),this.isDragging=!1};document.addEventListener("mousemove",i),document.addEventListener("mouseup",s)}))}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 }\n :host .cursor {\n pointer-events: none;\n position: absolute;\n z-index: 2;\n top: 0;\n left: 0;\n height: 100%;\n border-radius: 2px;\n width: ${this.options.cursorWidth}px;\n background-color: ${this.options.cursorColor||this.options.progressColor};\n }\n </style>\n\n <div class="scroll" part="scroll">\n <div class="wrapper">\n <div class="canvases"></div>\n <div class="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(){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||isNaN(this.options.barWidth)?1:this.options.barWidth*s,n=null==this.options.barGap||isNaN(this.options.barGap)?this.options.barWidth?r/2:0:this.options.barGap*s,o=this.options.barRadius||0,h=this.options.barHeight||1,l=t.getChannelData(0),c=l.length,d=Math.floor(e/(r+n))/c,p=i/2,u=1===t.numberOfChannels,m=u?l:t.getChannelData(1),g=u&&m.some((t=>t<0)),v=(t,i)=>{let a=0,u=0,v=0;const f=document.createElement("canvas");f.width=Math.round(e*(i-t)/c),f.height=this.options.height,f.style.width=`${Math.floor(f.width/s)}px`,f.style.height=`${this.options.height}px`,f.style.left=`${Math.floor(t*e/s/c)}px`,this.canvasWrapper.appendChild(f);const y=f.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)*d);if(i>a){const t=Math.round(u*p*h),e=Math.round(v*p*h);y.roundRect(a*(r+n),p-t,r,t+(e||1),o),a=i,u=0,v=0}const s=g?l[e]:Math.abs(l[e]),c=g?m[e]:Math.abs(m[e]);s>u&&(u=s),(g?c<-v:c>v)&&(v=c<0?-c:c)}y.fill(),y.closePath();const b=f.cloneNode();this.progressWrapper.appendChild(b);const w=b.getContext("2d",{desynchronized:!0});f.width>0&&f.height>0&&w.drawImage(f,0,0),w.globalCompositeOperation="source-in",w.fillStyle=this.options.progressColor??"",w.fillRect(0,0,f.width,f.height)};this.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="";const{scrollLeft:f,scrollWidth:y,clientWidth:b}=this.scrollContainer,w=c/y;let W=Math.min(a.MAX_CANVAS_WIDTH,b);W-=W%((r+n)/s);const C=Math.floor(Math.abs(f)*w),E=Math.ceil(C+W*w);v(C,E);const M=E-C;for(let t=E;t<c;t+=M)await this.delay((()=>{v(t,Math.min(c,t+M))}));for(let t=C-1;t>=0;t-=M)await this.delay((()=>{v(Math.max(0,t-M),t)}))}render(t){const e=window.devicePixelRatio||1,i=this.scrollContainer.clientWidth,s=Math.ceil(t.duration*(this.options.minPxPerSec||0));this.isScrolling=s>i;const r=this.options.fillParent&&!this.isScrolling,n=(r?i:s)*e,{height:o}=this.options;this.wrapper.style.width=r?"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.canvasWrapper.style.height=`${this.options.height}px`,this.renderPeaks(t,n,o,e),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:r}=this.scrollContainer,n=r*t,o=i/2;if(n>s+(e&&this.options.autoCenter&&!this.isDragging?o:i)||n<s)if(this.options.autoCenter&&!this.isDragging){const t=o/20;n-(s+o)>=t&&n<s+i?this.scrollContainer.scrollLeft+=t:this.scrollContainer.scrollLeft=n-o}else if(this.isDragging){const t=10;this.scrollContainer.scrollLeft=n<s?n-t:n-i+t}else this.scrollContainer.scrollLeft=n;{const{scrollLeft:t}=this.scrollContainer,e=t/r,s=(t+i)/r;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))}}a.MAX_CANVAS_WIDTH=4e3;const h=a,l=class extends i{constructor(){super(...arguments),this.unsubscribe=()=>{}}start(){this.unsubscribe=this.on("tick",(()=>{requestAnimationFrame((()=>{this.emit("tick")}))})),this.emit("tick")}stop(){this.unsubscribe()}destroy(){this.unsubscribe()}},c={height:128,waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,autoScroll:!0,autoCenter:!0,sampleRate:8e3};class d extends o{static create(t){return new d(t)}constructor(t){super({media:t.media,autoplay:t.autoplay,playbackRate:t.audioRate}),this.plugins=[],this.decodedData=null,this.canPlay=!1,this.subscriptions=[],this.options=Object.assign({},c,t),this.timer=new l,this.renderer=new h(this.options.container,this.options),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initReadyEvent(),this.initPlugins();const e=this.options.url||this.options.media?.currentSrc||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),t.audioRate&&this.setPlaybackRate(t.audioRate)}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("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"),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.canPlay&&(this.renderer.renderProgress(e),clearTimeout(t),t=setTimeout((()=>{this.seekTo(e)}),this.isPlaying()?0:200)),this.emit("interaction"),this.emit("drag",e))})))}}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(this),this.plugins.push(t),t}getWrapper(){return this.renderer.getWrapper()}getScroll(){return this.renderer.getScroll()}getActivePlugins(){return this.plugins}async load(t,e,i){if(this.decodedData=null,this.canPlay=!1,this.emit("load",t),e)this.setSrc(t),i||(i=await new Promise((t=>{this.onceMediaEvent("loadedmetadata",(()=>t(this.getMediaElement().duration)))}))||0),this.decodedData=r.createBuffer(e,i);else{const e=await n(t);this.setSrc(t,e),this.decodedData=await r.decode(e,this.options.sampleRate)}this.emit("decode",this.getDuration()),this.renderer.render(this.decodedData)}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.subscriptions.forEach((t=>t())),this.plugins.forEach((t=>t.destroy())),this.timer.destroy(),this.renderer.destroy(),super.destroy()}}const p=d,u={height:50,overlayColor:"rgba(100, 100, 100, 0.1)",insertPosition:"afterend"};class m extends s{constructor(t){super(t),this.miniWavesurfer=null,this.container=null,this.options=Object.assign({},u,t),this.minimapWrapper=this.initMinimapWrapper(),this.overlay=this.initOverlay()}static create(t){return new m(t)}onInit(){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),this.container?.appendChild(this.minimapWrapper)):(this.container=this.wavesurfer.getWrapper().parentElement,this.container?.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=p.create({...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.wavesurfer&&this.miniWavesurfer&&this.wavesurfer.setTime(this.miniWavesurfer.getCurrentTime()),this.emit("interaction")}))))}getOverlayWidth(){const t=this.wavesurfer?.getWrapper().clientWidth||1;return Math.round(this.minimapWrapper.clientWidth/t*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(){this.miniWavesurfer?.destroy(),this.minimapWrapper.remove(),super.destroy()}}const g=m;return e.default})()));
|
|
@@ -1,117 +0,0 @@
|
|
|
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 { type WaveSurferOptions } from '../wavesurfer.js';
|
|
6
|
-
import { type EnvelopePluginOptions } from './envelope.js';
|
|
7
|
-
import EventEmitter from '../event-emitter.js';
|
|
8
|
-
export type TrackId = string | number;
|
|
9
|
-
export type TrackOptions = {
|
|
10
|
-
id: TrackId;
|
|
11
|
-
url?: string;
|
|
12
|
-
peaks?: WaveSurferOptions['peaks'];
|
|
13
|
-
draggable?: boolean;
|
|
14
|
-
startPosition: number;
|
|
15
|
-
startCue?: number;
|
|
16
|
-
endCue?: number;
|
|
17
|
-
fadeInEnd?: number;
|
|
18
|
-
fadeOutStart?: number;
|
|
19
|
-
volume?: number;
|
|
20
|
-
markers?: Array<{
|
|
21
|
-
time: number;
|
|
22
|
-
label?: string;
|
|
23
|
-
color?: string;
|
|
24
|
-
}>;
|
|
25
|
-
intro?: {
|
|
26
|
-
endTime: number;
|
|
27
|
-
label?: string;
|
|
28
|
-
color?: string;
|
|
29
|
-
};
|
|
30
|
-
options?: WaveSurferOptions;
|
|
31
|
-
};
|
|
32
|
-
export type MultitrackOptions = {
|
|
33
|
-
container: HTMLElement;
|
|
34
|
-
minPxPerSec?: number;
|
|
35
|
-
cursorColor?: string;
|
|
36
|
-
cursorWidth?: number;
|
|
37
|
-
trackBackground?: string;
|
|
38
|
-
trackBorderColor?: string;
|
|
39
|
-
rightButtonDrag?: boolean;
|
|
40
|
-
envelopeOptions?: EnvelopePluginOptions;
|
|
41
|
-
};
|
|
42
|
-
export type MultitrackEvents = {
|
|
43
|
-
canplay: [];
|
|
44
|
-
'start-position-change': [{
|
|
45
|
-
id: TrackId;
|
|
46
|
-
startPosition: number;
|
|
47
|
-
}];
|
|
48
|
-
'start-cue-change': [{
|
|
49
|
-
id: TrackId;
|
|
50
|
-
startCue: number;
|
|
51
|
-
}];
|
|
52
|
-
'end-cue-change': [{
|
|
53
|
-
id: TrackId;
|
|
54
|
-
endCue: number;
|
|
55
|
-
}];
|
|
56
|
-
'fade-in-change': [{
|
|
57
|
-
id: TrackId;
|
|
58
|
-
fadeInEnd: number;
|
|
59
|
-
}];
|
|
60
|
-
'fade-out-change': [{
|
|
61
|
-
id: TrackId;
|
|
62
|
-
fadeOutStart: number;
|
|
63
|
-
}];
|
|
64
|
-
'volume-change': [{
|
|
65
|
-
id: TrackId;
|
|
66
|
-
volume: number;
|
|
67
|
-
}];
|
|
68
|
-
'intro-end-change': [{
|
|
69
|
-
id: TrackId;
|
|
70
|
-
endTime: number;
|
|
71
|
-
}];
|
|
72
|
-
drop: [{
|
|
73
|
-
id: TrackId;
|
|
74
|
-
}];
|
|
75
|
-
};
|
|
76
|
-
export type MultitrackTracks = Array<TrackOptions>;
|
|
77
|
-
declare class MultiTrack extends EventEmitter<MultitrackEvents> {
|
|
78
|
-
private tracks;
|
|
79
|
-
private options;
|
|
80
|
-
private audios;
|
|
81
|
-
private wavesurfers;
|
|
82
|
-
private durations;
|
|
83
|
-
private currentTime;
|
|
84
|
-
private maxDuration;
|
|
85
|
-
private rendering;
|
|
86
|
-
private isDragging;
|
|
87
|
-
private frameRequest;
|
|
88
|
-
private timer;
|
|
89
|
-
private subscriptions;
|
|
90
|
-
private timeline;
|
|
91
|
-
static create(tracks: MultitrackTracks, options: MultitrackOptions): MultiTrack;
|
|
92
|
-
constructor(tracks: MultitrackTracks, options: MultitrackOptions);
|
|
93
|
-
private initDurations;
|
|
94
|
-
private initAudio;
|
|
95
|
-
private initAllAudios;
|
|
96
|
-
private initWavesurfer;
|
|
97
|
-
private initAllWavesurfers;
|
|
98
|
-
private initTimeline;
|
|
99
|
-
private updatePosition;
|
|
100
|
-
private setIsDragging;
|
|
101
|
-
private onDrag;
|
|
102
|
-
private findCurrentTracks;
|
|
103
|
-
private startSync;
|
|
104
|
-
play(): void;
|
|
105
|
-
pause(): void;
|
|
106
|
-
isPlaying(): boolean;
|
|
107
|
-
getCurrentTime(): number;
|
|
108
|
-
/** Position percentage from 0 to 1 */
|
|
109
|
-
seekTo(position: number): void;
|
|
110
|
-
/** Set time in seconds */
|
|
111
|
-
setTime(time: number): void;
|
|
112
|
-
zoom(pxPerSec: number): void;
|
|
113
|
-
addTrack(track: TrackOptions): void;
|
|
114
|
-
destroy(): void;
|
|
115
|
-
setSinkId(sinkId: string): Promise<void[]>;
|
|
116
|
-
}
|
|
117
|
-
export default MultiTrack;
|