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