wavesurfer.js 7.0.0-alpha.3 → 7.0.0-alpha.30

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