wavesurfer.js 7.0.0-alpha.41 → 7.0.0-alpha.43
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 -0
- package/dist/decoder.js +3 -13
- package/dist/plugins/minimap.min.js +1 -1
- package/dist/plugins/multitrack.min.js +1 -1
- package/dist/plugins/regions.d.ts +0 -2
- package/dist/plugins/regions.js +0 -4
- package/dist/plugins/regions.min.js +1 -1
- package/dist/plugins/timeline.d.ts +6 -2
- package/dist/plugins/timeline.js +29 -6
- package/dist/plugins/timeline.min.js +1 -1
- package/dist/renderer.d.ts +5 -1
- package/dist/renderer.js +39 -12
- package/dist/wavesurfer.d.ts +6 -1
- package/dist/wavesurfer.js +4 -0
- package/dist/wavesurfer.min.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -54,6 +54,7 @@ Most options, events, and methods are similar to those in previous versions.
|
|
|
54
54
|
|
|
55
55
|
### Removed methods
|
|
56
56
|
* `getFilters`, `setFilter` – as there's no Web Audio "backend"
|
|
57
|
+
* `drawBuffer` – to redraw the waveform, use `setOptions` instead and pass new rendering options
|
|
57
58
|
* `cancelAjax` – ajax is replaced by `fetch`
|
|
58
59
|
* `loadBlob` – use `URL.createObjectURL()` to convert a blob to a URL and call `load(url)` instead
|
|
59
60
|
* `skipForward`, `skipBackward`, `setPlayEnd` – can be implemented using `setTime(time)`
|
package/dist/decoder.js
CHANGED
|
@@ -1,18 +1,8 @@
|
|
|
1
1
|
/** Decode an array buffer into an audio buffer */
|
|
2
2
|
async function decode(audioData) {
|
|
3
|
-
const
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
try {
|
|
7
|
-
audioCtx = new AudioContext({
|
|
8
|
-
sampleRate: MIN_SAMPLE_RATE,
|
|
9
|
-
});
|
|
10
|
-
}
|
|
11
|
-
catch (_) {
|
|
12
|
-
audioCtx = new AudioContext({
|
|
13
|
-
sampleRate: DEFAULT_SAMPLE_RATE,
|
|
14
|
-
});
|
|
15
|
-
}
|
|
3
|
+
const audioCtx = new AudioContext({
|
|
4
|
+
sampleRate: 8000, // the lowsest sample rate of all browsers
|
|
5
|
+
});
|
|
16
6
|
const decode = audioCtx.decodeAudioData(audioData);
|
|
17
7
|
decode.finally(() => audioCtx.close());
|
|
18
8
|
return decode;
|
|
@@ -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.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:()=>m});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}init(t){this.wavesurfer=t.wavesurfer,this.container=t.container,this.wrapper=t.wrapper}destroy(){this.subscriptions.forEach((t=>t()))}},n={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}}};class r extends i{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 n=null!=this.options.barWidth?this.options.barWidth*s:1,o=null!=this.options.barGap?this.options.barGap*s:this.options.barWidth?n/2:0,a=this.options.barRadius??0,h=this.options.barHeight??1,l=t[0],d=l.length,c=Math.floor(e/(n+o))/d,p=i/2,u=1===t.length,m=u?l:t[1],g=u&&m.some((t=>t<0)),y=(t,i)=>{let r=0,u=0,y=0;const f=document.createElement("canvas");f.width=Math.round(e*(i-t)/d),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/d)}px`,this.canvasWrapper.appendChild(f);const v=f.getContext("2d",{desynchronized:!0});v.beginPath(),v.fillStyle=this.options.waveColor??"",v.roundRect||(v.roundRect=v.fillRect);for(let e=t;e<i;e++){const i=Math.round((e-t)*c);if(i>r){const t=Math.round(u*p*h),e=Math.round(y*p*h);v.roundRect(r*(n+o),p-t,n,t+(e||1),a),r=i,u=0,y=0}const s=g?l[e]:Math.abs(l[e]),d=g?m[e]:Math.abs(m[e]);s>u&&(u=s),(g?d<-y:d>y)&&(y=d<0?-d:d)}v.fill(),v.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:v,clientWidth:b}=this.scrollContainer,w=d/v;let C=Math.min(r.MAX_CANVAS_WIDTH,b);C-=C%((n+o)/s);const W=Math.floor(Math.abs(f)*w),M=Math.ceil(W+C*w);y(W,M);const P=M-W;for(let t=M;t<d;t+=P)await this.delay((()=>{y(t,Math.min(d,t+P))}));for(let t=W-1;t>=0;t-=P)await this.delay((()=>{y(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)}}}r.MAX_CANVAS_WIDTH=4e3;const o=r,a=class extends i{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)}},h=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()}},l={height:128,waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,autoCenter:!0};class d extends a{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.options=Object.assign({},l,t),this.fetcher=new class{async load(t){return fetch(t).then((t=>t.arrayBuffer()))}},this.timer=new h,this.renderer=new o({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(t,e,i){if(this.decodedData=null,this.canPlay=!1,this.loadUrl(t),this.emit("load",t),e)i||(i=await new Promise((t=>{this.onceMediaEvent("loadedmetadata",(()=>t(this.getMediaElement().duration)))}))||0),this.decodedData=n.createBuffer(e,i);else{const e=await this.fetcher.load(t);this.decodedData=await n.decode(e)}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=d,p={height:50,overlayColor:"rgba(100, 100, 100, 0.1)",insertPosition:"afterend"};class u extends s{constructor(t){super(t),this.miniWavesurfer=null,this.options=Object.assign({},p,t),this.minimapWrapper=this.initMinimapWrapper(),this.overlay=this.initOverlay()}static create(t){return new u(t)}init(t){if(super.init(t),!this.wavesurfer)throw Error("WaveSurfer is not initialized");if(this.options.container){let t=null;"string"==typeof this.options.container?t=document.querySelector(this.options.container):this.options.container instanceof HTMLElement&&(t=this.options.container),t?.appendChild(this.minimapWrapper)}else this.container?.insertAdjacentElement(this.options.insertPosition,this.minimapWrapper);this.subscriptions.push(this.wavesurfer.on("decode",(()=>{this.initMinimap()})))}initMinimapWrapper(){const t=document.createElement("div");return t.style.position="relative",t}initOverlay(){const t=document.createElement("div");return t.setAttribute("style","position: absolute; z-index: 2; left: 0; top: 0; bottom: 0;"),t.style.backgroundColor=this.options.overlayColor,this.minimapWrapper.appendChild(t),t}initMinimap(){if(!this.wavesurfer||!this.wrapper)return;const t=this.wavesurfer.getDecodedData(),e=this.wavesurfer.getMediaElement();if(!t||!e)return;this.miniWavesurfer=c.create({...this.options,container:this.minimapWrapper,minPxPerSec:0,fillParent:!0,media:e,peaks:[t.getChannelData(0)],duration:t.duration});const i=Math.round(this.minimapWrapper.clientWidth/this.wrapper.clientWidth*100);this.overlay.style.width=`${i}%`,this.subscriptions.push(this.wavesurfer.on("timeupdate",(e=>{const s=Math.max(0,Math.min(e/t.duration*100-i/2,100-i)).toFixed(2);this.overlay.style.left=`${s}%`}))),this.subscriptions.push(this.miniWavesurfer.on("interaction",(()=>{this.wavesurfer&&this.miniWavesurfer&&this.wavesurfer.setTime(this.miniWavesurfer.getCurrentTime()),this.container&&(this.container.scrollLeft=this.minimapWrapper.scrollLeft/this.minimapWrapper.scrollWidth*this.container.scrollWidth),this.emit("interaction")})),this.miniWavesurfer.on("ready",(()=>{this.emit("ready")})))}destroy(){this.miniWavesurfer?.destroy(),this.minimapWrapper.remove(),super.destroy()}}const m=u;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.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:()=>m});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}init(t){this.wavesurfer=t.wavesurfer,this.container=t.container,this.wrapper=t.wrapper}destroy(){this.subscriptions.forEach((t=>t()))}},n={decode:async function(t){const e=new AudioContext({sampleRate:8e3}),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}}};class r extends i{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.initEvents()}initEvents(){this.wrapper.addEventListener("click",(t=>{const e=this.wrapper.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.emit("click",i)})),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)})),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 n=null!=this.options.barWidth?this.options.barWidth*s:1,o=null!=this.options.barGap?this.options.barGap*s:this.options.barWidth?n/2:0,a=this.options.barRadius??0,h=this.options.barHeight??1,l=t[0],c=l.length,d=Math.floor(e/(n+o))/c,p=i/2,u=1===t.length,m=u?l:t[1],g=u&&m.some((t=>t<0)),y=(t,i)=>{let r=0,u=0,y=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 v=f.getContext("2d",{desynchronized:!0});v.beginPath(),v.fillStyle=this.options.waveColor??"",v.roundRect||(v.roundRect=v.fillRect);for(let e=t;e<i;e++){const i=Math.round((e-t)*d);if(i>r){const t=Math.round(u*p*h),e=Math.round(y*p*h);v.roundRect(r*(n+o),p-t,n,t+(e||1),a),r=i,u=0,y=0}const s=g?l[e]:Math.abs(l[e]),c=g?m[e]:Math.abs(m[e]);s>u&&(u=s),(g?c<-y:c>y)&&(y=c<0?-c:c)}v.fill(),v.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:v,clientWidth:b}=this.scrollContainer,w=c/v;let C=Math.min(r.MAX_CANVAS_WIDTH,b);C-=C%((n+o)/s);const W=Math.floor(Math.abs(f)*w),M=Math.ceil(W+C*w);y(W,M);const E=M-W;for(let t=M;t<c;t+=E)await this.delay((()=>{y(t,Math.min(c,t+E))}));for(let t=W-1;t>=0;t-=E)await this.delay((()=>{y(Math.max(0,t-E),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()}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?o:i)||r<s)if(this.options.autoCenter){const t=o/20;r-(s+o)>=t&&r<s+i?this.scrollContainer.scrollLeft+=t:this.scrollContainer.scrollLeft=r-o}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.isScrolling&&this.options.autoScroll&&this.scrollIntoView(t,e))}}r.MAX_CANVAS_WIDTH=4e3;const o=r,a=class extends i{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)}},h=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()}},l={height:128,waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,autoScroll:!0,autoCenter:!0};class c extends a{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.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 h,this.renderer=new o({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"))})),this.renderer.on("scroll",((t,e)=>{const i=this.getDuration();this.emit("scroll",t*i,e*i)})))}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(t,e,i){if(this.decodedData=null,this.canPlay=!1,this.loadUrl(t),this.emit("load",t),e)i||(i=await new Promise((t=>{this.onceMediaEvent("loadedmetadata",(()=>t(this.getMediaElement().duration)))}))||0),this.decodedData=n.createBuffer(e,i);else{const e=await this.fetcher.load(t);this.decodedData=await n.decode(e)}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 d=c,p={height:50,overlayColor:"rgba(100, 100, 100, 0.1)",insertPosition:"afterend"};class u extends s{constructor(t){super(t),this.miniWavesurfer=null,this.options=Object.assign({},p,t),this.minimapWrapper=this.initMinimapWrapper(),this.overlay=this.initOverlay()}static create(t){return new u(t)}init(t){if(super.init(t),!this.wavesurfer)throw Error("WaveSurfer is not initialized");if(this.options.container){let t=null;"string"==typeof this.options.container?t=document.querySelector(this.options.container):this.options.container instanceof HTMLElement&&(t=this.options.container),t?.appendChild(this.minimapWrapper)}else this.container?.insertAdjacentElement(this.options.insertPosition,this.minimapWrapper);this.subscriptions.push(this.wavesurfer.on("decode",(()=>{this.initMinimap()})))}initMinimapWrapper(){const t=document.createElement("div");return t.style.position="relative",t}initOverlay(){const t=document.createElement("div");return t.setAttribute("style","position: absolute; z-index: 2; left: 0; top: 0; bottom: 0;"),t.style.backgroundColor=this.options.overlayColor,this.minimapWrapper.appendChild(t),t}initMinimap(){if(!this.wavesurfer||!this.wrapper)return;const t=this.wavesurfer.getDecodedData(),e=this.wavesurfer.getMediaElement();if(!t||!e)return;this.miniWavesurfer=d.create({...this.options,container:this.minimapWrapper,minPxPerSec:0,fillParent:!0,media:e,peaks:[t.getChannelData(0)],duration:t.duration});const i=Math.round(this.minimapWrapper.clientWidth/this.wrapper.clientWidth*100);this.overlay.style.width=`${i}%`,this.subscriptions.push(this.wavesurfer.on("timeupdate",(e=>{const s=Math.max(0,Math.min(e/t.duration*100-i/2,100-i)).toFixed(2);this.overlay.style.left=`${s}%`}))),this.subscriptions.push(this.miniWavesurfer.on("interaction",(()=>{this.wavesurfer&&this.miniWavesurfer&&this.wavesurfer.setTime(this.miniWavesurfer.getCurrentTime()),this.container&&(this.container.scrollLeft=this.minimapWrapper.scrollLeft/this.minimapWrapper.scrollWidth*this.container.scrollWidth),this.emit("interaction")})),this.miniWavesurfer.on("ready",(()=>{this.emit("ready")})))}destroy(){this.miniWavesurfer?.destroy(),this.minimapWrapper.remove(),super.destroy()}}const m=u;return e.default})()));
|
|
@@ -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.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})()));
|
|
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}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");const e=this.options.container??this.wrapper;this.options.insertPosition?(e.firstElementChild||e).insertAdjacentElement(this.options.insertPosition,this.timelineWrapper):e.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="beforebegin"===this.options.insertPosition,o=document.createElement("div");if(o.setAttribute("style",`\n height: ${this.options.height}px;\n overflow: hidden;\n display: flex;\n justify-content: space-between;\n align-items: ${r?"flex-start":"flex-end"};\n font-size: ${this.options.height/2}px;\n white-space: nowrap;\n `),r){const t="\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n z-index: 2;\n ";o.setAttribute("style",o.getAttribute("style")+t)}"string"==typeof this.options.style?o.setAttribute("style",o.getAttribute("style")+this.options.style):"object"==typeof this.options.style&&Object.assign(o.style,this.options.style);const a=document.createElement("div");a.setAttribute("style",`\n width: 1px;\n height: 50%;\n display: flex;\n flex-direction: column;\n justify-content: ${r?"flex-start":"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=a.cloneNode(),i=Math.round(100*e)/100%s==0,r=Math.round(100*e)/100%n==0;(i||r)&&(t.style.height="100%",t.style.textIndent="3px",t.textContent=this.formatTime(e),i&&(t.style.opacity="1")),o.appendChild(t)}this.timelineWrapper.appendChild(o),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){const e=new AudioContext({sampleRate:8e3}),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.initEvents()}initEvents(){this.wrapper.addEventListener("click",(t=>{const e=this.wrapper.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.emit("click",i)})),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)})),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()}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?o:i)||r<s)if(this.options.autoCenter){const t=o/20;r-(s+o)>=t&&r<s+i?this.scrollContainer.scrollLeft+=t:this.scrollContainer.scrollLeft=r-o}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.isScrolling&&this.options.autoScroll&&this.scrollIntoView(t,e))}}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,autoScroll:!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"))})),this.renderer.on("scroll",((t,e)=>{const i=this.getDuration();this.emit("scroll",t*i,e*i)})))}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})()));
|
|
@@ -80,8 +80,6 @@ declare class RegionsPlugin extends BasePlugin<RegionsPluginEvents, RegionsPlugi
|
|
|
80
80
|
private saveRegion;
|
|
81
81
|
/** Create a region with given parameters */
|
|
82
82
|
addRegion(options: RegionParams): Region;
|
|
83
|
-
/** The same as addRegion but with spread params */
|
|
84
|
-
add(start: number, end: number, content?: string, color?: string): Region;
|
|
85
83
|
/**
|
|
86
84
|
* Enable creation of regions by dragging on an empty space on the waveform.
|
|
87
85
|
* Returns a function to disable the drag selection.
|
package/dist/plugins/regions.js
CHANGED
|
@@ -319,10 +319,6 @@ class RegionsPlugin extends BasePlugin {
|
|
|
319
319
|
}
|
|
320
320
|
return region;
|
|
321
321
|
}
|
|
322
|
-
/** The same as addRegion but with spread params */
|
|
323
|
-
add(start, end, content, color) {
|
|
324
|
-
return this.addRegion({ start, end, content, color });
|
|
325
|
-
}
|
|
326
322
|
/**
|
|
327
323
|
* Enable creation of regions by dragging on an empty space on the waveform.
|
|
328
324
|
* Returns a function to disable the drag selection.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Regions=t():e.Regions=t()}(WaveSurfer,(()=>(()=>{"use strict";var e={284:(e,t,i)=>{i.d(t,{Z:()=>r});var
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Regions=t():e.Regions=t()}(WaveSurfer,(()=>(()=>{"use strict";var e={284:(e,t,i)=>{i.d(t,{Z:()=>r});var s=i(139);class n extends s.Z{constructor(e){super(),this.subscriptions=[],this.options=e}init(e){this.wavesurfer=e.wavesurfer,this.container=e.container,this.wrapper=e.wrapper}destroy(){this.subscriptions.forEach((e=>e()))}}const r=n},139:(e,t,i)=>{i.d(t,{Z:()=>s});const s=class{constructor(){this.listeners={}}on(e,t){return this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t),()=>this.un(e,t)}once(e,t){const i=this.on(e,t),s=this.on(e,(()=>{i(),s()}));return i}un(e,t){this.listeners[e]&&(t?this.listeners[e].delete(t):delete this.listeners[e])}unAll(){this.listeners={}}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach((e=>e(...t)))}}}},t={};function i(s){var n=t[s];if(void 0!==n)return n.exports;var r=t[s]={exports:{}};return e[s](r,r.exports,i),r.exports}i.d=(e,t)=>{for(var s in t)i.o(t,s)&&!i.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var s={};return(()=>{i.d(s,{default:()=>a});var e=i(284),t=i(139);function n(e,t,i,s){if(!e)return()=>{};let n=0,r=!1;const o=e=>{r&&e.stopPropagation()},a=e=>{e.stopPropagation();let o=e.clientX;t(o);const a=e=>{const t=e.clientX,s=t-o;n+=s,o=t,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 e.addEventListener("click",o),e.addEventListener("mousedown",a),()=>{e.removeEventListener("click",o),e.removeEventListener("mousedown",a)}}class r extends t.Z{constructor(e,t){super(),this.totalDuration=t,this.id=e.id||Math.random().toString(32).slice(2),this.start=e.start,this.end=e.end??e.start,this.drag=e.drag??!0,this.resize=e.resize??!0,this.color=e.color??"rgba(0, 0, 0, 0.1)",this.element=this.initElement(e.content),this.renderPosition(),this.initMouseEvents()}initElement(e){const t=document.createElement("div"),i=this.start===this.end;if(t.id=this.id,t.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 `),e&&("string"==typeof e?(this.content=document.createElement("div"),this.content.textContent=e):this.content=e,t.appendChild(this.content)),!i){const e=document.createElement("div");e.setAttribute("data-resize","left"),e.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=e.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",t.appendChild(e),t.appendChild(i)}return t}renderPosition(){const e=this.start/this.totalDuration,t=this.end/this.totalDuration;this.element.style.left=100*e+"%",this.element.style.width=100*(t-e)+"%"}initMouseEvents(){const{element:e}=this;e.addEventListener("click",(e=>this.emit("click",e))),e.addEventListener("mouseenter",(e=>this.emit("over",e))),e.addEventListener("mouseleave",(e=>this.emit("leave",e))),e.addEventListener("dblclick",(e=>this.emit("dblclick",e))),n(e,(()=>this.onStartMoving()),(e=>this.onMove(e)),(()=>this.onEndMoving())),n(e.querySelector('[data-resize="left"]'),(()=>null),(e=>this.onResize(e,"start")),(()=>this.onEndResizing())),n(e.querySelector('[data-resize="right"]'),(()=>null),(e=>this.onResize(e,"end")),(()=>this.onEndResizing()))}onStartMoving(){this.drag&&(this.element.style.cursor="grabbing")}onEndMoving(){this.drag&&(this.element.style.cursor="grab",this.emit("update-end"))}onUpdate(e,t){if(!this.element.parentElement)return;const i=e/this.element.parentElement.clientWidth*this.totalDuration;t.forEach((e=>{this[e]+=i,"start"===e?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(e){this.drag&&this.onUpdate(e,["start","end"])}onResize(e,t){this.resize&&this.onUpdate(e,[t])}onEndResizing(){this.resize&&this.emit("update-end")}_setTotalDuration(e){this.totalDuration=e,this.renderPosition()}play(){this.emit("play")}setOptions(e){e.color&&(this.color=e.color,this.element.style.backgroundColor=this.color),void 0!==e.drag&&(this.drag=e.drag,this.element.style.cursor=this.drag?"grab":"default"),void 0!==e.resize&&(this.resize=e.resize,this.element.querySelectorAll("[data-resize]").forEach((e=>{e.style.cursor=this.resize?"ew-resize":"default"}))),void 0===e.start&&void 0===e.end||(this.start=e.start??this.start,this.end=e.end??this.end,this.renderPosition())}remove(){this.emit("remove"),this.element.remove(),this.element=null}}class o extends e.Z{constructor(e){super(e),this.regions=[],this.regionsContainer=this.initRegionsContainer()}static create(e){return new o(e)}init(e){if(super.init(e),!this.wavesurfer||!this.wrapper)throw Error("WaveSurfer is not initialized");this.wrapper.appendChild(this.regionsContainer)}initRegionsContainer(){const e=document.createElement("div");return e.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 "),e}getRegions(){return this.regions}avoidOverlapping(e){if(!e.content)return;const t=e.content,i=t.getBoundingClientRect().left,s=e.element.scrollWidth,n=this.regions.filter((t=>{if(t===e||!t.content)return!1;const n=t.content.getBoundingClientRect().left,r=t.element.scrollWidth;return i<n+r&&n<i+s})).map((e=>e.content?.getBoundingClientRect().height||0)).reduce(((e,t)=>e+t),0);t.style.marginTop=`${n}px`}saveRegion(e){this.regionsContainer.appendChild(e.element),this.avoidOverlapping(e),this.regions.push(e),this.emit("region-created",e);const t=[e.on("update-end",(()=>{this.avoidOverlapping(e),this.emit("region-updated",e)})),e.on("play",(()=>{this.wavesurfer?.play(),this.wavesurfer?.setTime(e.start)})),e.on("click",(t=>{this.emit("region-clicked",e,t)})),e.once("remove",(()=>{t.forEach((e=>e())),this.regions=this.regions.filter((t=>t!==e))}))];this.subscriptions.push(...t)}addRegion(e){if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");const t=this.wavesurfer.getDuration(),i=new r(e,t);return t?this.saveRegion(i):this.subscriptions.push(this.wavesurfer.once("canplay",(e=>{i._setTotalDuration(e),this.saveRegion(i)}))),i}enableDragSelection(e){let t=null,i=0,s=0;return n(this.wrapper,(e=>i=e),(n=>{if(this.wavesurfer&&this.wrapper){if(!t){const s=this.wavesurfer.getDuration(),o=this.wrapper.getBoundingClientRect();let a=(i-o.left)/o.width*s,h=(i+n-o.left)/o.width*s;a>h&&([a,h]=[h,a]),t=new r({...e,start:a,end:h},s),this.regionsContainer.appendChild(t.element)}s+=n,t&&t.onUpdate(n,[s>0?"end":"start"])}}),(()=>{if(t&&(this.saveRegion(t),t=null,s=0,this.wavesurfer)){const{interact:e}=this.wavesurfer.options;e&&(this.wavesurfer.toggleInteraction(!1),setTimeout((()=>this.wavesurfer?.toggleInteraction(e)),10))}}))}clearRegions(){this.regions.forEach((e=>e.remove()))}destroy(){this.clearRegions(),super.destroy()}}const a=o})(),s.default})()));
|
|
@@ -7,6 +7,8 @@ export type TimelinePluginOptions = {
|
|
|
7
7
|
height?: number;
|
|
8
8
|
/** HTML container for the timeline, defaults to wavesufer's container */
|
|
9
9
|
container?: HTMLElement;
|
|
10
|
+
/** Pass 'beforebegin' to insert the timeline on top of the waveform */
|
|
11
|
+
insertPosition?: InsertPosition;
|
|
10
12
|
/** The duration of the timeline in seconds, defaults to wavesurfer's duration */
|
|
11
13
|
duration?: number;
|
|
12
14
|
/** Interval between ticks in seconds */
|
|
@@ -15,6 +17,8 @@ export type TimelinePluginOptions = {
|
|
|
15
17
|
primaryLabelInterval?: number;
|
|
16
18
|
/** Interval between secondary numeric labels */
|
|
17
19
|
secondaryLabelInterval?: number;
|
|
20
|
+
/** Custom inline style to apply to the container */
|
|
21
|
+
style?: CSSStyleDeclaration | string;
|
|
18
22
|
};
|
|
19
23
|
declare const defaultOptions: {
|
|
20
24
|
height: number;
|
|
@@ -25,8 +29,8 @@ export type TimelinePluginEvents = {
|
|
|
25
29
|
declare class TimelinePlugin extends BasePlugin<TimelinePluginEvents, TimelinePluginOptions> {
|
|
26
30
|
private timelineWrapper;
|
|
27
31
|
protected options: TimelinePluginOptions & typeof defaultOptions;
|
|
28
|
-
constructor(options
|
|
29
|
-
static create(options
|
|
32
|
+
constructor(options?: TimelinePluginOptions);
|
|
33
|
+
static create(options?: TimelinePluginOptions): TimelinePlugin;
|
|
30
34
|
/** Called by wavesurfer, don't call manually */
|
|
31
35
|
init(params: WaveSurferPluginParams): void;
|
|
32
36
|
/** Unmount */
|
package/dist/plugins/timeline.js
CHANGED
|
@@ -7,7 +7,7 @@ const defaultOptions = {
|
|
|
7
7
|
};
|
|
8
8
|
class TimelinePlugin extends BasePlugin {
|
|
9
9
|
constructor(options) {
|
|
10
|
-
super(options);
|
|
10
|
+
super(options || {});
|
|
11
11
|
this.options = Object.assign({}, defaultOptions, options);
|
|
12
12
|
this.timelineWrapper = this.initTimelineWrapper();
|
|
13
13
|
}
|
|
@@ -21,7 +21,13 @@ class TimelinePlugin extends BasePlugin {
|
|
|
21
21
|
throw Error('WaveSurfer is not initialized');
|
|
22
22
|
}
|
|
23
23
|
const container = this.options.container ?? this.wrapper;
|
|
24
|
-
|
|
24
|
+
if (this.options.insertPosition) {
|
|
25
|
+
;
|
|
26
|
+
(container.firstElementChild || container).insertAdjacentElement(this.options.insertPosition, this.timelineWrapper);
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
container.appendChild(this.timelineWrapper);
|
|
30
|
+
}
|
|
25
31
|
if (this.options.duration) {
|
|
26
32
|
this.initTimeline(this.options.duration);
|
|
27
33
|
}
|
|
@@ -94,31 +100,48 @@ class TimelinePlugin extends BasePlugin {
|
|
|
94
100
|
const timeInterval = this.options.timeInterval ?? this.defaultTimeInterval(pxPerSec);
|
|
95
101
|
const primaryLabelInterval = this.options.primaryLabelInterval ?? this.defaultPrimaryLabelInterval(pxPerSec);
|
|
96
102
|
const secondaryLabelInterval = this.options.secondaryLabelInterval ?? this.defaultSecondaryLabelInterval(pxPerSec);
|
|
103
|
+
const isTop = this.options.insertPosition === 'beforebegin';
|
|
97
104
|
const timeline = document.createElement('div');
|
|
98
105
|
timeline.setAttribute('style', `
|
|
99
106
|
height: ${this.options.height}px;
|
|
100
107
|
overflow: hidden;
|
|
101
108
|
display: flex;
|
|
102
109
|
justify-content: space-between;
|
|
103
|
-
align-items: flex-end;
|
|
110
|
+
align-items: ${isTop ? 'flex-start' : 'flex-end'};
|
|
104
111
|
font-size: ${this.options.height / 2}px;
|
|
105
112
|
white-space: nowrap;
|
|
106
113
|
`);
|
|
114
|
+
if (isTop) {
|
|
115
|
+
const topStyle = `
|
|
116
|
+
position: absolute;
|
|
117
|
+
top: 0;
|
|
118
|
+
left: 0;
|
|
119
|
+
right: 0;
|
|
120
|
+
z-index: 2;
|
|
121
|
+
`;
|
|
122
|
+
timeline.setAttribute('style', timeline.getAttribute('style') + topStyle);
|
|
123
|
+
}
|
|
124
|
+
if (typeof this.options.style === 'string') {
|
|
125
|
+
timeline.setAttribute('style', timeline.getAttribute('style') + this.options.style);
|
|
126
|
+
}
|
|
127
|
+
else if (typeof this.options.style === 'object') {
|
|
128
|
+
Object.assign(timeline.style, this.options.style);
|
|
129
|
+
}
|
|
107
130
|
const notchEl = document.createElement('div');
|
|
108
131
|
notchEl.setAttribute('style', `
|
|
109
132
|
width: 1px;
|
|
110
133
|
height: 50%;
|
|
111
134
|
display: flex;
|
|
112
135
|
flex-direction: column;
|
|
113
|
-
justify-content: flex-end;
|
|
136
|
+
justify-content: ${isTop ? 'flex-start' : 'flex-end'};
|
|
114
137
|
overflow: visible;
|
|
115
138
|
border-left: 1px solid currentColor;
|
|
116
139
|
opacity: 0.25;
|
|
117
140
|
`);
|
|
118
141
|
for (let i = 0; i < duration; i += timeInterval) {
|
|
119
142
|
const notch = notchEl.cloneNode();
|
|
120
|
-
const isPrimary = i % primaryLabelInterval === 0;
|
|
121
|
-
const isSecondary = i % secondaryLabelInterval === 0;
|
|
143
|
+
const isPrimary = (Math.round(i * 100) / 100) % primaryLabelInterval === 0;
|
|
144
|
+
const isSecondary = (Math.round(i * 100) / 100) % secondaryLabelInterval === 0;
|
|
122
145
|
if (isPrimary || isSecondary) {
|
|
123
146
|
notch.style.height = '100%';
|
|
124
147
|
notch.style.textIndent = '3px';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Timeline=e():t.Timeline=e()}(WaveSurfer,(()=>(()=>{"use strict";var t={284:(t,e,i)=>{i.d(e,{Z:()=>r});var n=i(139);class s extends n.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=s},139:(t,e,i)=>{i.d(e,{Z:()=>n});const 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),n=this.on(t,(()=>{i(),n()}));return i}un(t,e){this.listeners[t]&&(e?this.listeners[t].delete(e):delete this.listeners[t])}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}}}},e={};function i(n){var s=e[n];if(void 0!==s)return s.exports;var r=e[n]={exports:{}};return t[n](r,r.exports,i),r.exports}i.d=(t,e)=>{for(var n in e)i.o(e,n)&&!i.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},i.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var n={};return(()=>{i.d(n,{default:()=>r});var t=i(284);const e={height:20};class s extends t.Z{constructor(t){super(t||{}),this.options=Object.assign({},e,t),this.timelineWrapper=this.initTimelineWrapper()}static create(t){return new s(t)}init(t){if(super.init(t),!this.wavesurfer||!this.wrapper)throw Error("WaveSurfer is not initialized");const e=this.options.container??this.wrapper;this.options.insertPosition?(e.firstElementChild||e).insertAdjacentElement(this.options.insertPosition,this.timelineWrapper):e.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),n=this.options.primaryLabelInterval??this.defaultPrimaryLabelInterval(e),s=this.options.secondaryLabelInterval??this.defaultSecondaryLabelInterval(e),r="beforebegin"===this.options.insertPosition,o=document.createElement("div");if(o.setAttribute("style",`\n height: ${this.options.height}px;\n overflow: hidden;\n display: flex;\n justify-content: space-between;\n align-items: ${r?"flex-start":"flex-end"};\n font-size: ${this.options.height/2}px;\n white-space: nowrap;\n `),r){const t="\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n z-index: 2;\n ";o.setAttribute("style",o.getAttribute("style")+t)}"string"==typeof this.options.style?o.setAttribute("style",o.getAttribute("style")+this.options.style):"object"==typeof this.options.style&&Object.assign(o.style,this.options.style);const l=document.createElement("div");l.setAttribute("style",`\n width: 1px;\n height: 50%;\n display: flex;\n flex-direction: column;\n justify-content: ${r?"flex-start":"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=l.cloneNode(),i=Math.round(100*e)/100%n==0,r=Math.round(100*e)/100%s==0;(i||r)&&(t.style.height="100%",t.style.textIndent="3px",t.textContent=this.formatTime(e),i&&(t.style.opacity="1")),o.appendChild(t)}this.timelineWrapper.appendChild(o),this.emit("ready")}}const r=s})(),n.default})()));
|
package/dist/renderer.d.ts
CHANGED
|
@@ -16,9 +16,11 @@ export type RendererStyleOptions = {
|
|
|
16
16
|
barHeight?: number;
|
|
17
17
|
hideScrollbar?: boolean;
|
|
18
18
|
autoCenter?: boolean;
|
|
19
|
+
autoScroll?: boolean;
|
|
19
20
|
};
|
|
20
21
|
type RendererEvents = {
|
|
21
22
|
click: [relativeX: number];
|
|
23
|
+
scroll: [relativeStart: number, relativeEnd: number];
|
|
22
24
|
};
|
|
23
25
|
type ChannelData = Float32Array[] | Array<number[]>;
|
|
24
26
|
declare class Renderer extends EventEmitter<RendererEvents> {
|
|
@@ -35,6 +37,7 @@ declare class Renderer extends EventEmitter<RendererEvents> {
|
|
|
35
37
|
private duration;
|
|
36
38
|
private resizeObserver;
|
|
37
39
|
constructor(params: RendererRequiredParams, options: RendererStyleOptions);
|
|
40
|
+
private initEvents;
|
|
38
41
|
private initHtml;
|
|
39
42
|
setOptions(options: RendererStyleOptions): void;
|
|
40
43
|
getContainer(): HTMLElement;
|
|
@@ -45,6 +48,7 @@ declare class Renderer extends EventEmitter<RendererEvents> {
|
|
|
45
48
|
render(channelData: ChannelData, duration: number): void;
|
|
46
49
|
reRender(): void;
|
|
47
50
|
zoom(minPxPerSec: number): void;
|
|
48
|
-
|
|
51
|
+
private scrollIntoView;
|
|
52
|
+
renderProgress(progress: number, isPlaying?: boolean): void;
|
|
49
53
|
}
|
|
50
54
|
export default Renderer;
|
package/dist/renderer.js
CHANGED
|
@@ -28,13 +28,23 @@ class Renderer extends EventEmitter {
|
|
|
28
28
|
this.wrapper = shadow.querySelector('.wrapper');
|
|
29
29
|
this.canvasWrapper = shadow.querySelector('.canvases');
|
|
30
30
|
this.progressWrapper = shadow.querySelector('.progress');
|
|
31
|
-
|
|
31
|
+
this.initEvents();
|
|
32
|
+
}
|
|
33
|
+
initEvents() {
|
|
34
|
+
// Add a click listener
|
|
32
35
|
this.wrapper.addEventListener('click', (e) => {
|
|
33
36
|
const rect = this.wrapper.getBoundingClientRect();
|
|
34
37
|
const x = e.clientX - rect.left;
|
|
35
38
|
const relativeX = x / rect.width;
|
|
36
39
|
this.emit('click', relativeX);
|
|
37
40
|
});
|
|
41
|
+
// Add a scroll listener
|
|
42
|
+
this.scrollContainer.addEventListener('scroll', () => {
|
|
43
|
+
const { scrollLeft, scrollWidth, clientWidth } = this.scrollContainer;
|
|
44
|
+
const startX = scrollLeft / scrollWidth;
|
|
45
|
+
const endX = (scrollLeft + clientWidth) / scrollWidth;
|
|
46
|
+
this.emit('scroll', startX, endX);
|
|
47
|
+
});
|
|
38
48
|
// Re-render the waveform on container resize
|
|
39
49
|
this.resizeObserver = new ResizeObserver(() => {
|
|
40
50
|
this.delay(() => this.reRender(), 100);
|
|
@@ -262,17 +272,15 @@ class Renderer extends EventEmitter {
|
|
|
262
272
|
this.options.minPxPerSec = minPxPerSec;
|
|
263
273
|
this.reRender();
|
|
264
274
|
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
const minDiff = center / 20;
|
|
275
|
-
if (progressWidth > scrollLeft + minScroll || progressWidth < scrollLeft) {
|
|
275
|
+
scrollIntoView(progress, isPlaying = false) {
|
|
276
|
+
const { clientWidth, scrollLeft, scrollWidth } = this.scrollContainer;
|
|
277
|
+
const progressWidth = scrollWidth * progress;
|
|
278
|
+
const center = clientWidth / 2;
|
|
279
|
+
const minScroll = isPlaying && this.options.autoCenter ? center : clientWidth;
|
|
280
|
+
if (progressWidth > scrollLeft + minScroll || progressWidth < scrollLeft) {
|
|
281
|
+
// Scroll to the center
|
|
282
|
+
if (this.options.autoCenter) {
|
|
283
|
+
const minDiff = center / 20;
|
|
276
284
|
// If the cursor is in viewport but not centered, scroll to the center slowly
|
|
277
285
|
if (progressWidth - (scrollLeft + center) >= minDiff && progressWidth < scrollLeft + clientWidth) {
|
|
278
286
|
this.scrollContainer.scrollLeft += minDiff;
|
|
@@ -282,6 +290,25 @@ class Renderer extends EventEmitter {
|
|
|
282
290
|
this.scrollContainer.scrollLeft = progressWidth - center;
|
|
283
291
|
}
|
|
284
292
|
}
|
|
293
|
+
else {
|
|
294
|
+
// Scroll to the beginning
|
|
295
|
+
this.scrollContainer.scrollLeft = progressWidth;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
// Emit the scroll event
|
|
299
|
+
{
|
|
300
|
+
const { scrollLeft } = this.scrollContainer;
|
|
301
|
+
const startX = scrollLeft / scrollWidth;
|
|
302
|
+
const endX = (scrollLeft + clientWidth) / scrollWidth;
|
|
303
|
+
this.emit('scroll', startX, endX);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
renderProgress(progress, isPlaying) {
|
|
307
|
+
if (isNaN(progress))
|
|
308
|
+
return;
|
|
309
|
+
this.progressWrapper.style.width = `${progress * 100}%`;
|
|
310
|
+
if (this.isScrolling && this.options.autoScroll) {
|
|
311
|
+
this.scrollIntoView(progress, isPlaying);
|
|
285
312
|
}
|
|
286
313
|
}
|
|
287
314
|
}
|
package/dist/wavesurfer.d.ts
CHANGED
|
@@ -42,7 +42,9 @@ export type WaveSurferOptions = {
|
|
|
42
42
|
hideScrollbar?: boolean;
|
|
43
43
|
/** Audio rate */
|
|
44
44
|
audioRate?: number;
|
|
45
|
-
/**
|
|
45
|
+
/** Automatically scroll the container to keep the current position in viewport */
|
|
46
|
+
autoScroll?: boolean;
|
|
47
|
+
/** If autoScroll is enabled, keep the cursor in the center of the waveform during playback */
|
|
46
48
|
autoCenter?: boolean;
|
|
47
49
|
/** The list of plugins to initialize on start */
|
|
48
50
|
plugins?: GenericPlugin[];
|
|
@@ -55,6 +57,7 @@ declare const defaultOptions: {
|
|
|
55
57
|
minPxPerSec: number;
|
|
56
58
|
fillParent: boolean;
|
|
57
59
|
interact: boolean;
|
|
60
|
+
autoScroll: boolean;
|
|
58
61
|
autoCenter: boolean;
|
|
59
62
|
};
|
|
60
63
|
export type WaveSurferEvents = {
|
|
@@ -82,6 +85,8 @@ export type WaveSurferEvents = {
|
|
|
82
85
|
seeking: [currentTime: number];
|
|
83
86
|
/** When a user interaction (i.e. a click on the waveform) happens */
|
|
84
87
|
interaction: [];
|
|
88
|
+
/** When the waveform is scrolled (panned) */
|
|
89
|
+
scroll: [visibleStartTime: number, visibleEndTime: number];
|
|
85
90
|
/** When the zoom level changes */
|
|
86
91
|
zoom: [minPxPerSec: number];
|
|
87
92
|
/** Just before the waveform is destroyed so you can clean up your events */
|
package/dist/wavesurfer.js
CHANGED
|
@@ -11,6 +11,7 @@ const defaultOptions = {
|
|
|
11
11
|
minPxPerSec: 0,
|
|
12
12
|
fillParent: true,
|
|
13
13
|
interact: true,
|
|
14
|
+
autoScroll: true,
|
|
14
15
|
autoCenter: true,
|
|
15
16
|
};
|
|
16
17
|
class WaveSurfer extends Player {
|
|
@@ -76,6 +77,9 @@ class WaveSurfer extends Player {
|
|
|
76
77
|
this.canPlay && this.seekTo(relativeX);
|
|
77
78
|
this.emit('interaction');
|
|
78
79
|
}
|
|
80
|
+
}), this.renderer.on('scroll', (startX, endX) => {
|
|
81
|
+
const duration = this.getDuration();
|
|
82
|
+
this.emit('scroll', startX * duration, endX * duration);
|
|
79
83
|
}));
|
|
80
84
|
}
|
|
81
85
|
initTimerEvents() {
|
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){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}}},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)))}};class n extends s{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,l=t[0],d=l.length,c=Math.floor(e/(r+o))/d,p=i/2,u=1===t.length,m=u?l:t[1],g=u&&m.some((t=>t<0)),y=(t,i)=>{let n=0,u=0,y=0;const f=document.createElement("canvas");f.width=Math.round(e*(i-t)/d),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/d)}px`,this.canvasWrapper.appendChild(f);const v=f.getContext("2d",{desynchronized:!0});v.beginPath(),v.fillStyle=this.options.waveColor??"",v.roundRect||(v.roundRect=v.fillRect);for(let e=t;e<i;e++){const i=Math.round((e-t)*c);if(i>n){const t=Math.round(u*p*h),e=Math.round(y*p*h);v.roundRect(n*(r+o),p-t,r,t+(e||1),a),n=i,u=0,y=0}const s=g?l[e]:Math.abs(l[e]),d=g?m[e]:Math.abs(m[e]);s>u&&(u=s),(g?d<-y:d>y)&&(y=d<0?-d:d)}v.fill(),v.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:v,clientWidth:b}=this.scrollContainer,w=d/v;let C=Math.min(n.MAX_CANVAS_WIDTH,b);C-=C%((r+o)/s);const P=Math.floor(Math.abs(f)*w),M=Math.ceil(P+C*w);y(P,M);const x=M-P;for(let t=M;t<d;t+=x)await this.delay((()=>{y(t,Math.min(d,t+x))}));for(let t=P-1;t>=0;t-=x)await this.delay((()=>{y(Math.max(0,t-x),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,o=class extends s{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)}},a=class extends s{constructor(){super(...arguments),this.unsubscribe=()=>{}}start(){this.unsubscribe=this.on("tick",(()=>{requestAnimationFrame((()=>{this.emit("tick")}))})),this.emit("tick")}stop(){this.unsubscribe()}destroy(){this.unsubscribe()}},h={height:128,waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,autoCenter:!0};class l extends o{static create(t){return new l(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({},h,t),this.fetcher=new class{async load(t){return fetch(t).then((t=>t.arrayBuffer()))}},this.timer=new a,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(t,e,s){if(this.decodedData=null,this.canPlay=!1,this.loadUrl(t),this.emit("load",t),e)s||(s=await new Promise((t=>{this.onceMediaEvent("loadedmetadata",(()=>t(this.getMediaElement().duration)))}))||0),this.decodedData=i.createBuffer(e,s);else{const e=await this.fetcher.load(t);this.decodedData=await i.decode(e)}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 d=l;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){const e=new AudioContext({sampleRate:8e3}),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}}},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)))}};class n extends s{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.initEvents()}initEvents(){this.wrapper.addEventListener("click",(t=>{const e=this.wrapper.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.emit("click",i)})),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)})),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,l=t[0],d=l.length,c=Math.floor(e/(r+o))/d,p=i/2,u=1===t.length,m=u?l:t[1],g=u&&m.some((t=>t<0)),y=(t,i)=>{let n=0,u=0,y=0;const f=document.createElement("canvas");f.width=Math.round(e*(i-t)/d),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/d)}px`,this.canvasWrapper.appendChild(f);const v=f.getContext("2d",{desynchronized:!0});v.beginPath(),v.fillStyle=this.options.waveColor??"",v.roundRect||(v.roundRect=v.fillRect);for(let e=t;e<i;e++){const i=Math.round((e-t)*c);if(i>n){const t=Math.round(u*p*h),e=Math.round(y*p*h);v.roundRect(n*(r+o),p-t,r,t+(e||1),a),n=i,u=0,y=0}const s=g?l[e]:Math.abs(l[e]),d=g?m[e]:Math.abs(m[e]);s>u&&(u=s),(g?d<-y:d>y)&&(y=d<0?-d:d)}v.fill(),v.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:v,clientWidth:b}=this.scrollContainer,w=d/v;let C=Math.min(n.MAX_CANVAS_WIDTH,b);C-=C%((r+o)/s);const P=Math.floor(Math.abs(f)*w),M=Math.ceil(P+C*w);y(P,M);const E=M-P;for(let t=M;t<d;t+=E)await this.delay((()=>{y(t,Math.min(d,t+E))}));for(let t=P-1;t>=0;t-=E)await this.delay((()=>{y(Math.max(0,t-E),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()}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?o:i)||r<s)if(this.options.autoCenter){const t=o/20;r-(s+o)>=t&&r<s+i?this.scrollContainer.scrollLeft+=t:this.scrollContainer.scrollLeft=r-o}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.isScrolling&&this.options.autoScroll&&this.scrollIntoView(t,e))}}n.MAX_CANVAS_WIDTH=4e3;const r=n,o=class extends s{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)}},a=class extends s{constructor(){super(...arguments),this.unsubscribe=()=>{}}start(){this.unsubscribe=this.on("tick",(()=>{requestAnimationFrame((()=>{this.emit("tick")}))})),this.emit("tick")}stop(){this.unsubscribe()}destroy(){this.unsubscribe()}},h={height:128,waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,autoScroll:!0,autoCenter:!0};class l extends o{static create(t){return new l(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({},h,t),this.fetcher=new class{async load(t){return fetch(t).then((t=>t.arrayBuffer()))}},this.timer=new a,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"))})),this.renderer.on("scroll",((t,e)=>{const i=this.getDuration();this.emit("scroll",t*i,e*i)})))}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(t,e,s){if(this.decodedData=null,this.canPlay=!1,this.loadUrl(t),this.emit("load",t),e)s||(s=await new Promise((t=>{this.onceMediaEvent("loadedmetadata",(()=>t(this.getMediaElement().duration)))}))||0),this.decodedData=i.createBuffer(e,s);else{const e=await this.fetcher.load(t);this.decodedData=await i.decode(e)}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 d=l;return e.default})()));
|