@arraypress/waveform-player 1.19.0 → 1.19.1
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/dist/waveform-player.cjs +59 -15
- package/dist/waveform-player.cjs.map +2 -2
- package/dist/waveform-player.esm.js +8 -8
- package/dist/waveform-player.esm.js.map +3 -3
- package/dist/waveform-player.js +59 -15
- package/dist/waveform-player.min.js +8 -8
- package/dist/waveform-player.min.js.map +3 -3
- package/package.json +1 -1
- package/src/js/core.js +56 -24
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
function W(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}function x(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function U(e){if(typeof e!="string"||e==="")return!1;try{let t=new URL(e,"http://localhost/");return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function m(e,t=0,i=1){return Math.max(t,Math.min(e,i))}function at(e){return e===void 0?void 0:e==="true"}function q(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function D(e){let t={},i=(a,o=a)=>{let n=at(e.dataset[o]);n!==void 0&&(t[a]=n)},r=(a,o=a,n=!1)=>{let l=e.dataset[o];l&&(t[a]=n?parseFloat(l):parseInt(l,10))},s=(a,o=a)=>{let n=e.dataset[o];if(n)try{t[a]=JSON.parse(n)}catch(l){console.warn(`[WaveformPlayer] Invalid ${o} JSON:`,l)}};if(e.dataset.src&&(t.url=e.dataset.src),e.dataset.url&&(t.url=e.dataset.url),r("height"),r("samples"),e.dataset.preload&&(t.preload=e.dataset.preload),e.dataset.audioMode&&(t.audioMode=e.dataset.audioMode),e.dataset.style&&(t.waveformStyle=e.dataset.style),e.dataset.waveformStyle&&(t.waveformStyle=e.dataset.waveformStyle),e.dataset.waveformGradient&&(t.waveformGradient=e.dataset.waveformGradient),r("barWidth"),r("barSpacing"),r("barRadius"),e.dataset.buttonAlign&&(t.buttonAlign=e.dataset.buttonAlign),e.dataset.layout&&(t.layout=e.dataset.layout),e.dataset.buttonStyle&&(t.buttonStyle=e.dataset.buttonStyle),e.dataset.buttonSize){let a=e.dataset.buttonSize;t.buttonSize=/^\d+(\.\d+)?$/.test(a.trim())?parseFloat(a):a}return e.dataset.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=q(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=q(e.dataset.progressColor)),e.dataset.color&&(t.waveformColor=e.dataset.color),e.dataset.theme&&(t.colorPreset=e.dataset.theme),i("autoplay"),i("showControls"),i("showInfo"),i("showTime"),i("showHoverTime"),i("seekHandle"),i("showBPM","showBpm"),r("bpm"),i("singlePlay"),i("playOnSeek"),e.dataset.title&&(t.title=e.dataset.title),e.dataset.artist&&(t.artist=e.dataset.artist),e.dataset.album&&(t.album=e.dataset.album),e.dataset.artwork&&(t.artwork=e.dataset.artwork),e.dataset.waveform&&(t.waveform=e.dataset.waveform),s("markers"),r("playbackRate","playbackRate",!0),i("showPlaybackSpeed"),s("playbackRates"),i("enableMediaSession"),i("showMarkers"),i("accessibleSeek"),e.dataset.seekLabel&&(t.seekLabel=e.dataset.seekLabel),e.dataset.errorText&&(t.errorText=e.dataset.errorText),e.dataset.playIcon&&(t.playIcon=e.dataset.playIcon),e.dataset.pauseIcon&&(t.pauseIcon=e.dataset.pauseIcon),t}function S(e){if(!e||isNaN(e)||e<0)return"0:00";let t=Math.floor(e/3600),i=Math.floor(e%3600/60),r=Math.floor(e%60);return t>0?`${t}:${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${i}:${r.toString().padStart(2,"0")}`}var ot=0;function N(e){let t=e||"audio",i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return`wp_${(i>>>0).toString(36)}_${(ot++).toString(36)}`}function H(e){if(!e)return"Audio";let t=e.split("/");return t[t.length-1].split(".")[0].replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase())}function V(e){let t=typeof e=="string"?e.match(/\d+/g):null;if(!t||t.length<3)return null;let[i,r,s]=t.map(Number);return(i*299+r*587+s*114)/1e3}function B(...e){let t={};for(let i of e)for(let r in i)i[r]!==null&&i[r]!==void 0&&(t[r]=i[r]);return t}function j(e,t){let i;return function(...s){let a=()=>{clearTimeout(i),e(...s)};clearTimeout(i),i=setTimeout(a,t)}}function L(e,t){if(e.length===t)return e;if(e.length===0||t===0)return[];let i=[];if(t>e.length){let r=(e.length-1)/(t-1);for(let s=0;s<t;s++){let a=s*r,o=Math.floor(a),n=Math.ceil(a),l=a-o;if(n>=e.length)i.push(e[e.length-1]);else if(o===n)i.push(e[o]);else{let h=e[o]*(1-l)+e[n]*l;i.push(h)}}}else{let r=e.length/t;for(let s=0;s<t;s++){let a=Math.floor(s*r),o=Math.floor((s+1)*r),n=0,l=0;for(let h=a;h<=o&&h<e.length;h++)e[h]>n&&(n=e[h]),l++;if(l===0){let h=Math.min(Math.round(s*r),e.length-1);n=e[h]}i.push(n)}}return i}function E(e,t,i,r){if(!Array.isArray(t))return t;if(t.length<2)return t[0];let s=i.width,a=i.height,o=r&&r.waveformGradient,[n,l,h,d]=o==="horizontal"?[0,0,s,0]:o==="diagonal"?[0,0,s,a]:[0,0,0,a];try{let u=e.createLinearGradient(n,l,h,d);return t.forEach((v,g)=>u.addColorStop(g/(t.length-1),v)),u}catch{return t[0]}}function A(e,t,i,r,s,a){if((Array.isArray(a)?a.some(n=>n>0):a>0)&&typeof e.roundRect=="function"){let n=Math.min(r/2,Math.abs(s)/2),l=h=>m(h,0,n);e.beginPath(),e.roundRect(t,i,r,s,Array.isArray(a)?a.map(l):l(a)),e.fill()}else e.fillRect(t,i,r,s)}function Y(e,t){return(e.barRadius||0)*t}function nt(e,t){let i=Y(e,t);return[i,i,0,0]}function G(e,t,i,r,s){let a=s/2;e.beginPath(),e.moveTo(t,r-a),e.lineTo(i-a,r-a),e.arc(i-a,r,a,-Math.PI/2,Math.PI/2),e.lineTo(t,r+a),e.arc(t,r,a,Math.PI/2,-Math.PI/2),e.closePath()}function I(e,t,i,r,s){let a=window.devicePixelRatio||1,o=s.barWidth*a,n=s.barSpacing*a,l=Math.floor(t.width/(o+n)),h=L(i,l),d=t.height,u=r*t.width,v=nt(s,a),g=E(e,s.color,t,s),w=E(e,s.progressColor,t,s);e.clearRect(0,0,t.width,t.height),e.fillStyle=g;for(let f=0;f<h.length;f++){let p=f*(o+n);if(p+o>t.width)break;let y=h[f]*d*.9,c=d-y;A(e,p,c,o,y,v)}e.save(),e.beginPath(),e.rect(0,0,u,d),e.clip(),e.fillStyle=w;for(let f=0;f<h.length;f++){let p=f*(o+n);if(p>u)break;let y=h[f]*d*.9,c=d-y;A(e,p,c,o,y,v)}e.restore()}function lt(e,t,i,r,s){let a=window.devicePixelRatio||1,o=s.barWidth*a,n=s.barSpacing*a,l=Math.floor(t.width/(o+n)),h=L(i,l),d=t.height,u=d/2,v=r*t.width,g=Y(s,a),w=[g,g,0,0],f=[0,0,g,g],p=E(e,s.color,t,s),y=E(e,s.progressColor,t,s);e.clearRect(0,0,t.width,t.height),e.fillStyle=p;for(let c=0;c<h.length;c++){let b=c*(o+n);if(b+o>t.width)break;let k=h[c]*d*.45;A(e,b,u-k,o,k,w),A(e,b,u,o,k,f)}e.save(),e.beginPath(),e.rect(0,0,v,d),e.clip(),e.fillStyle=y;for(let c=0;c<h.length;c++){let b=c*(o+n);if(b>v)break;let k=h[c]*d*.45;A(e,b,u-k,o,k,w),A(e,b,u,o,k,f)}e.restore()}function ht(e,t,i,r,s){let a=t.width,o=t.height,n=o/2,l=o*.35;e.clearRect(0,0,a,o);let h=(d,u,v=1,g=!1)=>{let w=E(e,d,t,s),f=Array.isArray(d)?d[d.length-1]:d;g&&(e.shadowBlur=12,e.shadowColor=f),e.strokeStyle=w,e.lineWidth=u,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,n);let p=[],y=Math.floor(i.length*v);for(let c=0;c<y;c++){let b=c/(i.length-1)*a,k=i[c],P=Math.sin(c*.1)*k,C=n+P*l;p.push({x:b,y:C})}for(let c=0;c<p.length-1;c++){let b=p[c].x+(p[c+1].x-p[c].x)*.5,k=p[c].y,P=p[c+1].x-(p[c+1].x-p[c].x)*.5,C=p[c+1].y;e.bezierCurveTo(b,k,P,C,p[c+1].x,p[c+1].y)}e.stroke(),g&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,n),e.lineTo(a,n),e.stroke();for(let d=0;d<=10;d++){let u=a/10*d;e.beginPath(),e.moveTo(u,0),e.lineTo(u,o),e.stroke()}h(s.color,2,1,!1),r>0&&h(s.progressColor,3,r,!0)}function J(e,t,i,r,s){let a=window.devicePixelRatio||1,o=(s.barWidth||3)*a,n=(s.barSpacing||1)*a,l=Math.floor(t.width/(o+n)),h=L(i,l),d=t.height,u=4*a,v=2*a,g=r*t.width,w=d/2,f=E(e,s.color,t,s),p=E(e,s.progressColor,t,s);e.clearRect(0,0,t.width,t.height);for(let y=0;y<h.length;y++){let c=y*(o+n);if(c+o>t.width)break;let b=h[y]*d*.9,k=Math.floor(b/(u+v));e.fillStyle=c<g?p:f;for(let P=0;P<k;P++){let C=P*(u+v);e.fillRect(c,w-C-u,o,u),P>0&&e.fillRect(c,w+C,o,u)}}}function K(e,t,i,r,s){let a=window.devicePixelRatio||1,o=(s.barWidth||2)*a,n=(s.barSpacing||3)*a,l=Math.floor(t.width/(o+n)),h=L(i,l),d=t.height,u=Math.max(1.5*a,o/2),v=r*t.width,g=d/2,w=E(e,s.color,t,s),f=E(e,s.progressColor,t,s);e.clearRect(0,0,t.width,t.height);for(let p=0;p<h.length;p++){let y=p*(o+n)+o/2;if(y>t.width)break;let c=h[p]*d*.9;e.fillStyle=y<v?f:w,e.beginPath(),e.arc(y,g-c/2,u,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(y,g+c/2,u,0,Math.PI*2),e.fill()}}function dt(e,t,i,r,s){let a=t.width,o=t.height,n=o/2,l=4,h=l/2,d=!!s.seekActive;if(e.clearRect(0,0,a,o),e.fillStyle=E(e,s.color,t,s)||"rgba(255, 255, 255, 0.2)",G(e,h,a,n,l),e.fill(),r>0){let u=Math.max(h*2,r*a);e.save(),e.globalAlpha=s.seekHandle&&!d?.7:1,e.fillStyle=E(e,s.progressColor,t,s)||"rgba(255, 255, 255, 0.9)",G(e,h,u,n,l),e.fill(),e.restore()}}var ct={bars:I,bar:I,mirror:lt,line:ht,blocks:J,block:J,dots:K,dot:K,seekbar:dt};function X(e,t,i,r,s){(ct[s.waveformStyle]||I)(e,t,i,r,s)}function Q(e){try{let t=e.getChannelData(0),i=e.sampleRate,r=ut(t,i);if(r.length<2)return 120;let s=[];for(let l=1;l<r.length;l++)s.push((r[l]-r[l-1])/i);let a={};s.forEach(l=>{let h=60/l,d=Math.round(h/3)*3;d>60&&d<200&&(a[d]=(a[d]||0)+1)});let o=0,n=120;for(let[l,h]of Object.entries(a))h>o&&(o=h,n=parseInt(l));return n<70&&a[n*2]?n*=2:n>160&&a[Math.round(n/2)]&&(n=Math.round(n/2)),n-1}catch(t){return console.warn("[WaveformPlayer] BPM detection failed:",t),null}}function ut(e,t){let s=[],a=0;for(let o=0;o<e.length-2048;o+=1024){let n=0;for(let d=o;d<o+2048;d++)n+=e[d]*e[d];n=n/2048;let l=n-a,h=a*1.8+.01;if(l>h&&n>.01){let d=s[s.length-1]||0,u=t*.15;o-d>u&&s.push(o)}a=n*.8+a*.2}return s}function pt(e,t=1800){let i=e.length/t,r=e.numberOfChannels,s=[];for(let o=0;o<r;o++){let n=e.getChannelData(o);for(let l=0;l<t;l++){let h=~~(l*i),d=~~(h+i),u=0,v=0;for(let w=h;w<d;w++){let f=n[w];f>v&&(v=f),f<u&&(u=f)}let g=Math.max(Math.abs(v),Math.abs(u));(o===0||g>s[l])&&(s[l]=g)}}let a=W(s);return a>0?s.map(o=>o/a):s}async function z(e,t=1800,i=!1){let r;try{let s=window.AudioContext||window.webkitAudioContext;r=new s;let o=await(await fetch(e)).arrayBuffer(),n=await r.decodeAudioData(o),l=pt(n,t);l=ft(l);let h=null;return i&&(h=Q(n)),{peaks:l,bpm:h}}finally{r&&r.close()}}function Z(e=1800){let t=[];for(let i=0;i<e;i++){let r=Math.random()*.5+.3,s=Math.sin(i/e*Math.PI*4)*.2;t.push(m(r+s,.1,1))}return t}function ft(e,t=.95){let i=W(e);if(i===0||i>t)return e;let r=t/i;return e.map(s=>s*r)}function tt(e){let t=document.documentElement,i=document.body;return t.classList.contains(e)||t.classList.contains(`${e}-mode`)||t.classList.contains(`theme-${e}`)||t.getAttribute("data-theme")===e||t.getAttribute("data-color-scheme")===e||i.classList.contains(e)||i.classList.contains(`${e}-mode`)||i.getAttribute("data-theme")===e}function R(){if(tt("dark"))return"dark";if(tt("light"))return"light";try{let e=getComputedStyle(document.body).backgroundColor,t=V(e);if(t!==null){if(t>128)return"light";if(t<128)return"dark"}}catch{}if(window.matchMedia){if(window.matchMedia("(prefers-color-scheme: dark)").matches)return"dark";if(window.matchMedia("(prefers-color-scheme: light)").matches)return"light"}return"dark"}var _={dark:{waveformColor:"rgba(255, 255, 255, 0.3)",progressColor:"rgba(255, 255, 255, 0.9)"},light:{waveformColor:"rgba(0, 0, 0, 0.2)",progressColor:"rgba(0, 0, 0, 0.8)"}};function F(e){if(e&&_[e])return _[e];let t=R();return _[t]}var et={url:"",height:64,samples:1800,preload:"metadata",audioMode:"self",playbackRate:1,showPlaybackSpeed:!1,playbackRates:[.5,.75,1,1.25,1.5,1.75,2],buttonAlign:"auto",layout:"default",buttonStyle:"circle",buttonSize:null,waveformStyle:"mirror",barWidth:2,barSpacing:0,barRadius:1,waveformGradient:"vertical",colorPreset:null,waveformColor:null,progressColor:null,autoplay:!1,showControls:!0,showInfo:!0,showTime:!0,showHoverTime:!1,seekHandle:!1,showBPM:!1,bpm:null,singlePlay:!0,playOnSeek:!0,enableMediaSession:!0,markers:[],showMarkers:!0,accessibleSeek:!0,seekLabel:null,title:null,artist:null,artwork:null,album:"",errorText:"Unable to load audio",playIcon:'<svg viewBox="0 0 24 24" width="16" height="16"><path d="M8 5v14l11-7z"/></svg>',pauseIcon:'<svg viewBox="0 0 24 24" width="16" height="16"><path d="M6 4h4v16H6zM14 4h4v16h-4z"/></svg>',onLoad:null,onPlay:null,onPause:null,onEnd:null,onError:null,onTimeUpdate:null,onNextTrack:null,onPreviousTrack:null},it={bars:{barWidth:3,barSpacing:1},mirror:{barWidth:2,barSpacing:2},line:{barWidth:2,barSpacing:0},blocks:{barWidth:4,barSpacing:2},dots:{barWidth:3,barSpacing:3},seekbar:{barWidth:1,barSpacing:0}};var mt="data:image/svg+xml,"+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="#71717a" fill-opacity="0.15"/><g fill="none" stroke="#a1a1aa" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="17" r="2.2"/><circle cx="17" cy="15" r="2.2"/><path d="M10.2 17V7l9-1.6v9"/></g></svg>'),st=5,rt=10,gt='button, a[href], input, [role="slider"]',T=class e{static instances=new Map;static currentlyPlaying=null;constructor(t,i={}){if(this.container=typeof t=="string"?document.querySelector(t):t,!this.container)throw new Error("[WaveformPlayer] Container element not found");let r=D(this.container),s={...i};s.style&&!s.waveformStyle&&(s.waveformStyle=s.style),s.src&&!s.url&&(s.url=s.src),this.options=B(et,r,s);let a=F(this.options.colorPreset);this._autoTheme=this.options.colorPreset==null||!_[this.options.colorPreset],this._presetKeys=[],this._scheme=this.options.colorPreset&&_[this.options.colorPreset]?this.options.colorPreset:R();for(let[n,l]of Object.entries(a))(this.options[n]===null||this.options[n]===void 0)&&(this.options[n]=l,this._presetKeys.push(n));let o=it[this.options.waveformStyle];o&&(r.barWidth===void 0&&i.barWidth===void 0&&(this.options.barWidth=o.barWidth),r.barSpacing===void 0&&i.barSpacing===void 0&&(this.options.barSpacing=o.barSpacing)),this.audio=null,this.canvas=null,this.ctx=null,this.waveformData=[],this.progress=0,this._activeMarkerIndex=-1,this._markerLabelTimer=null,this.isPlaying=!1,this.isLoading=!1,this.hasError=!1,this.updateTimer=null,this.resizeObserver=null,this._ac=new AbortController,this.id=this.container.id||N(this.options.url),e.instances.set(this.id,this),e._watchTheme(),this.init(),setTimeout(()=>{this._emit("waveformplayer:ready",{player:this,url:this.options.url})},100)}_emit(t,i,r=!1){let s=new CustomEvent(t,{bubbles:!0,cancelable:r,detail:i});return this.container.dispatchEvent(s),s}_requestSeek(t){this._emit("waveformplayer:request-seek",{...this._buildTrackDetail(),percent:t},!0).defaultPrevented||(this.progress=t,this.drawWaveform?.())}init(){this.createDOM(),this.createAudio(),this.initPlaybackSpeed(),this.initKeyboardControls(),this.initSeekControl(),this.bindEvents(),this.setupResizeObserver(),requestAnimationFrame(()=>{this.resizeCanvas(),this.options.url&&this.load(this.options.url).then(()=>{this.options.autoplay&&this.play()?.catch(()=>{})}).catch(t=>{console.error("[WaveformPlayer] Failed to load audio:",t)})})}createDOM(){this.container.innerHTML="",this.container.className="waveform-player";let t=this.options.buttonAlign;t==="auto"&&(this.options.waveformStyle==="bars"?t="bottom":t="center"),this.options.layout==="preview"&&this.container.classList.add("waveform-layout-preview"),this.container.classList.toggle("waveform-theme-light",this._scheme==="light");let r=this.options.showControls?`
|
|
1
|
+
function W(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}function x(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function U(e){if(typeof e!="string"||e==="")return!1;try{let t=new URL(e,"http://localhost/");return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function m(e,t=0,i=1){return Math.max(t,Math.min(e,i))}function at(e){return e===void 0?void 0:e==="true"}function q(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function D(e){let t={},i=(a,o=a)=>{let n=at(e.dataset[o]);n!==void 0&&(t[a]=n)},s=(a,o=a,n=!1)=>{let l=e.dataset[o];l&&(t[a]=n?parseFloat(l):parseInt(l,10))},r=(a,o=a)=>{let n=e.dataset[o];if(n)try{t[a]=JSON.parse(n)}catch(l){console.warn(`[WaveformPlayer] Invalid ${o} JSON:`,l)}};if(e.dataset.src&&(t.url=e.dataset.src),e.dataset.url&&(t.url=e.dataset.url),s("height"),s("samples"),e.dataset.preload&&(t.preload=e.dataset.preload),e.dataset.audioMode&&(t.audioMode=e.dataset.audioMode),e.dataset.style&&(t.waveformStyle=e.dataset.style),e.dataset.waveformStyle&&(t.waveformStyle=e.dataset.waveformStyle),e.dataset.waveformGradient&&(t.waveformGradient=e.dataset.waveformGradient),s("barWidth"),s("barSpacing"),s("barRadius"),e.dataset.buttonAlign&&(t.buttonAlign=e.dataset.buttonAlign),e.dataset.layout&&(t.layout=e.dataset.layout),e.dataset.buttonStyle&&(t.buttonStyle=e.dataset.buttonStyle),e.dataset.buttonSize){let a=e.dataset.buttonSize;t.buttonSize=/^\d+(\.\d+)?$/.test(a.trim())?parseFloat(a):a}return e.dataset.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=q(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=q(e.dataset.progressColor)),e.dataset.color&&(t.waveformColor=e.dataset.color),e.dataset.theme&&(t.colorPreset=e.dataset.theme),i("autoplay"),i("showControls"),i("showInfo"),i("showTime"),i("showHoverTime"),i("seekHandle"),i("showBPM","showBpm"),s("bpm"),i("singlePlay"),i("playOnSeek"),e.dataset.title&&(t.title=e.dataset.title),e.dataset.artist&&(t.artist=e.dataset.artist),e.dataset.album&&(t.album=e.dataset.album),e.dataset.artwork&&(t.artwork=e.dataset.artwork),e.dataset.waveform&&(t.waveform=e.dataset.waveform),r("markers"),s("playbackRate","playbackRate",!0),i("showPlaybackSpeed"),r("playbackRates"),i("enableMediaSession"),i("showMarkers"),i("accessibleSeek"),e.dataset.seekLabel&&(t.seekLabel=e.dataset.seekLabel),e.dataset.errorText&&(t.errorText=e.dataset.errorText),e.dataset.playIcon&&(t.playIcon=e.dataset.playIcon),e.dataset.pauseIcon&&(t.pauseIcon=e.dataset.pauseIcon),t}function S(e){if(!e||isNaN(e)||e<0)return"0:00";let t=Math.floor(e/3600),i=Math.floor(e%3600/60),s=Math.floor(e%60);return t>0?`${t}:${i.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${i}:${s.toString().padStart(2,"0")}`}var ot=0;function N(e){let t=e||"audio",i=5381;for(let s=0;s<t.length;s++)i=(i<<5)+i+t.charCodeAt(s)|0;return`wp_${(i>>>0).toString(36)}_${(ot++).toString(36)}`}function H(e){if(!e)return"Audio";let t=e.split("/");return t[t.length-1].split(".")[0].replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function V(e){let t=typeof e=="string"?e.match(/\d+/g):null;if(!t||t.length<3)return null;let[i,s,r]=t.map(Number);return(i*299+s*587+r*114)/1e3}function B(...e){let t={};for(let i of e)for(let s in i)i[s]!==null&&i[s]!==void 0&&(t[s]=i[s]);return t}function j(e,t){let i;return function(...r){let a=()=>{clearTimeout(i),e(...r)};clearTimeout(i),i=setTimeout(a,t)}}function L(e,t){if(e.length===t)return e;if(e.length===0||t===0)return[];let i=[];if(t>e.length){let s=(e.length-1)/(t-1);for(let r=0;r<t;r++){let a=r*s,o=Math.floor(a),n=Math.ceil(a),l=a-o;if(n>=e.length)i.push(e[e.length-1]);else if(o===n)i.push(e[o]);else{let h=e[o]*(1-l)+e[n]*l;i.push(h)}}}else{let s=e.length/t;for(let r=0;r<t;r++){let a=Math.floor(r*s),o=Math.floor((r+1)*s),n=0,l=0;for(let h=a;h<=o&&h<e.length;h++)e[h]>n&&(n=e[h]),l++;if(l===0){let h=Math.min(Math.round(r*s),e.length-1);n=e[h]}i.push(n)}}return i}function E(e,t,i,s){if(!Array.isArray(t))return t;if(t.length<2)return t[0];let r=i.width,a=i.height,o=s&&s.waveformGradient,[n,l,h,d]=o==="horizontal"?[0,0,r,0]:o==="diagonal"?[0,0,r,a]:[0,0,0,a];try{let u=e.createLinearGradient(n,l,h,d);return t.forEach((v,g)=>u.addColorStop(g/(t.length-1),v)),u}catch{return t[0]}}function C(e,t,i,s,r,a){if((Array.isArray(a)?a.some(n=>n>0):a>0)&&typeof e.roundRect=="function"){let n=Math.min(s/2,Math.abs(r)/2),l=h=>m(h,0,n);e.beginPath(),e.roundRect(t,i,s,r,Array.isArray(a)?a.map(l):l(a)),e.fill()}else e.fillRect(t,i,s,r)}function Y(e,t){return(e.barRadius||0)*t}function nt(e,t){let i=Y(e,t);return[i,i,0,0]}function G(e,t,i,s,r){let a=r/2;e.beginPath(),e.moveTo(t,s-a),e.lineTo(i-a,s-a),e.arc(i-a,s,a,-Math.PI/2,Math.PI/2),e.lineTo(t,s+a),e.arc(t,s,a,Math.PI/2,-Math.PI/2),e.closePath()}function I(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,n=r.barSpacing*a,l=Math.floor(t.width/(o+n)),h=L(i,l),d=t.height,u=s*t.width,v=nt(r,a),g=E(e,r.color,t,r),b=E(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=g;for(let f=0;f<h.length;f++){let p=f*(o+n);if(p+o>t.width)break;let y=h[f]*d*.9,c=d-y;C(e,p,c,o,y,v)}e.save(),e.beginPath(),e.rect(0,0,u,d),e.clip(),e.fillStyle=b;for(let f=0;f<h.length;f++){let p=f*(o+n);if(p>u)break;let y=h[f]*d*.9,c=d-y;C(e,p,c,o,y,v)}e.restore()}function lt(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,n=r.barSpacing*a,l=Math.floor(t.width/(o+n)),h=L(i,l),d=t.height,u=d/2,v=s*t.width,g=Y(r,a),b=[g,g,0,0],f=[0,0,g,g],p=E(e,r.color,t,r),y=E(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=p;for(let c=0;c<h.length;c++){let w=c*(o+n);if(w+o>t.width)break;let k=h[c]*d*.45;C(e,w,u-k,o,k,b),C(e,w,u,o,k,f)}e.save(),e.beginPath(),e.rect(0,0,v,d),e.clip(),e.fillStyle=y;for(let c=0;c<h.length;c++){let w=c*(o+n);if(w>v)break;let k=h[c]*d*.45;C(e,w,u-k,o,k,b),C(e,w,u,o,k,f)}e.restore()}function ht(e,t,i,s,r){let a=t.width,o=t.height,n=o/2,l=o*.35;e.clearRect(0,0,a,o);let h=(d,u,v=1,g=!1)=>{let b=E(e,d,t,r),f=Array.isArray(d)?d[d.length-1]:d;g&&(e.shadowBlur=12,e.shadowColor=f),e.strokeStyle=b,e.lineWidth=u,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,n);let p=[],y=Math.floor(i.length*v);for(let c=0;c<y;c++){let w=c/(i.length-1)*a,k=i[c],P=Math.sin(c*.1)*k,A=n+P*l;p.push({x:w,y:A})}for(let c=0;c<p.length-1;c++){let w=p[c].x+(p[c+1].x-p[c].x)*.5,k=p[c].y,P=p[c+1].x-(p[c+1].x-p[c].x)*.5,A=p[c+1].y;e.bezierCurveTo(w,k,P,A,p[c+1].x,p[c+1].y)}e.stroke(),g&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,n),e.lineTo(a,n),e.stroke();for(let d=0;d<=10;d++){let u=a/10*d;e.beginPath(),e.moveTo(u,0),e.lineTo(u,o),e.stroke()}h(r.color,2,1,!1),s>0&&h(r.progressColor,3,s,!0)}function J(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||3)*a,n=(r.barSpacing||1)*a,l=Math.floor(t.width/(o+n)),h=L(i,l),d=t.height,u=4*a,v=2*a,g=s*t.width,b=d/2,f=E(e,r.color,t,r),p=E(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height);for(let y=0;y<h.length;y++){let c=y*(o+n);if(c+o>t.width)break;let w=h[y]*d*.9,k=Math.floor(w/(u+v));e.fillStyle=c<g?p:f;for(let P=0;P<k;P++){let A=P*(u+v);e.fillRect(c,b-A-u,o,u),P>0&&e.fillRect(c,b+A,o,u)}}}function K(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||2)*a,n=(r.barSpacing||3)*a,l=Math.floor(t.width/(o+n)),h=L(i,l),d=t.height,u=Math.max(1.5*a,o/2),v=s*t.width,g=d/2,b=E(e,r.color,t,r),f=E(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height);for(let p=0;p<h.length;p++){let y=p*(o+n)+o/2;if(y>t.width)break;let c=h[p]*d*.9;e.fillStyle=y<v?f:b,e.beginPath(),e.arc(y,g-c/2,u,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(y,g+c/2,u,0,Math.PI*2),e.fill()}}function dt(e,t,i,s,r){let a=t.width,o=t.height,n=o/2,l=4,h=l/2,d=!!r.seekActive;if(e.clearRect(0,0,a,o),e.fillStyle=E(e,r.color,t,r)||"rgba(255, 255, 255, 0.2)",G(e,h,a,n,l),e.fill(),s>0){let u=Math.max(h*2,s*a);e.save(),e.globalAlpha=r.seekHandle&&!d?.7:1,e.fillStyle=E(e,r.progressColor,t,r)||"rgba(255, 255, 255, 0.9)",G(e,h,u,n,l),e.fill(),e.restore()}}var ct={bars:I,bar:I,mirror:lt,line:ht,blocks:J,block:J,dots:K,dot:K,seekbar:dt};function X(e,t,i,s,r){(ct[r.waveformStyle]||I)(e,t,i,s,r)}function Q(e){try{let t=e.getChannelData(0),i=e.sampleRate,s=ut(t,i);if(s.length<2)return 120;let r=[];for(let l=1;l<s.length;l++)r.push((s[l]-s[l-1])/i);let a={};r.forEach(l=>{let h=60/l,d=Math.round(h/3)*3;d>60&&d<200&&(a[d]=(a[d]||0)+1)});let o=0,n=120;for(let[l,h]of Object.entries(a))h>o&&(o=h,n=parseInt(l));return n<70&&a[n*2]?n*=2:n>160&&a[Math.round(n/2)]&&(n=Math.round(n/2)),n-1}catch(t){return console.warn("[WaveformPlayer] BPM detection failed:",t),null}}function ut(e,t){let r=[],a=0;for(let o=0;o<e.length-2048;o+=1024){let n=0;for(let d=o;d<o+2048;d++)n+=e[d]*e[d];n=n/2048;let l=n-a,h=a*1.8+.01;if(l>h&&n>.01){let d=r[r.length-1]||0,u=t*.15;o-d>u&&r.push(o)}a=n*.8+a*.2}return r}function pt(e,t=1800){let i=e.length/t,s=e.numberOfChannels,r=[];for(let o=0;o<s;o++){let n=e.getChannelData(o);for(let l=0;l<t;l++){let h=~~(l*i),d=~~(h+i),u=0,v=0;for(let b=h;b<d;b++){let f=n[b];f>v&&(v=f),f<u&&(u=f)}let g=Math.max(Math.abs(v),Math.abs(u));(o===0||g>r[l])&&(r[l]=g)}}let a=W(r);return a>0?r.map(o=>o/a):r}async function z(e,t=1800,i=!1){let s;try{let r=window.AudioContext||window.webkitAudioContext;s=new r;let o=await(await fetch(e)).arrayBuffer(),n=await s.decodeAudioData(o),l=pt(n,t);l=ft(l);let h=null;return i&&(h=Q(n)),{peaks:l,bpm:h}}finally{s&&s.close()}}function Z(e=1800){let t=[];for(let i=0;i<e;i++){let s=Math.random()*.5+.3,r=Math.sin(i/e*Math.PI*4)*.2;t.push(m(s+r,.1,1))}return t}function ft(e,t=.95){let i=W(e);if(i===0||i>t)return e;let s=t/i;return e.map(r=>r*s)}function tt(e){let t=document.documentElement,i=document.body;return t.classList.contains(e)||t.classList.contains(`${e}-mode`)||t.classList.contains(`theme-${e}`)||t.getAttribute("data-theme")===e||t.getAttribute("data-color-scheme")===e||i.classList.contains(e)||i.classList.contains(`${e}-mode`)||i.getAttribute("data-theme")===e}function R(){if(tt("dark"))return"dark";if(tt("light"))return"light";try{let e=getComputedStyle(document.body).backgroundColor,t=V(e);if(t!==null){if(t>128)return"light";if(t<128)return"dark"}}catch{}if(window.matchMedia){if(window.matchMedia("(prefers-color-scheme: dark)").matches)return"dark";if(window.matchMedia("(prefers-color-scheme: light)").matches)return"light"}return"dark"}var _={dark:{waveformColor:"rgba(255, 255, 255, 0.3)",progressColor:"rgba(255, 255, 255, 0.9)"},light:{waveformColor:"rgba(0, 0, 0, 0.2)",progressColor:"rgba(0, 0, 0, 0.8)"}};function F(e){if(e&&_[e])return _[e];let t=R();return _[t]}var et={url:"",height:64,samples:1800,preload:"metadata",audioMode:"self",playbackRate:1,showPlaybackSpeed:!1,playbackRates:[.5,.75,1,1.25,1.5,1.75,2],buttonAlign:"auto",layout:"default",buttonStyle:"circle",buttonSize:null,waveformStyle:"mirror",barWidth:2,barSpacing:0,barRadius:1,waveformGradient:"vertical",colorPreset:null,waveformColor:null,progressColor:null,autoplay:!1,showControls:!0,showInfo:!0,showTime:!0,showHoverTime:!1,seekHandle:!1,showBPM:!1,bpm:null,singlePlay:!0,playOnSeek:!0,enableMediaSession:!0,markers:[],showMarkers:!0,accessibleSeek:!0,seekLabel:null,title:null,artist:null,artwork:null,album:"",errorText:"Unable to load audio",playIcon:'<svg viewBox="0 0 24 24" width="16" height="16"><path d="M8 5v14l11-7z"/></svg>',pauseIcon:'<svg viewBox="0 0 24 24" width="16" height="16"><path d="M6 4h4v16H6zM14 4h4v16h-4z"/></svg>',onLoad:null,onPlay:null,onPause:null,onEnd:null,onError:null,onTimeUpdate:null,onNextTrack:null,onPreviousTrack:null},it={bars:{barWidth:3,barSpacing:1},mirror:{barWidth:2,barSpacing:2},line:{barWidth:2,barSpacing:0},blocks:{barWidth:4,barSpacing:2},dots:{barWidth:3,barSpacing:3},seekbar:{barWidth:1,barSpacing:0}};var mt="data:image/svg+xml,"+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="#71717a" fill-opacity="0.15"/><g fill="none" stroke="#a1a1aa" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="17" r="2.2"/><circle cx="17" cy="15" r="2.2"/><path d="M10.2 17V7l9-1.6v9"/></g></svg>'),st=5,rt=10,gt='button, a[href], input, [role="slider"]',T=class e{static instances=new Map;static currentlyPlaying=null;constructor(t,i={}){if(this.container=typeof t=="string"?document.querySelector(t):t,!this.container)throw new Error("[WaveformPlayer] Container element not found");let s=D(this.container),r={...i};r.style&&!r.waveformStyle&&(r.waveformStyle=r.style),r.src&&!r.url&&(r.url=r.src),this.options=B(et,s,r);let a=F(this.options.colorPreset);this._autoTheme=this.options.colorPreset==null||!_[this.options.colorPreset],this._presetKeys=[],this._scheme=this.options.colorPreset&&_[this.options.colorPreset]?this.options.colorPreset:R();for(let[n,l]of Object.entries(a))(this.options[n]===null||this.options[n]===void 0)&&(this.options[n]=l,this._presetKeys.push(n));let o=it[this.options.waveformStyle];o&&(s.barWidth===void 0&&i.barWidth===void 0&&(this.options.barWidth=o.barWidth),s.barSpacing===void 0&&i.barSpacing===void 0&&(this.options.barSpacing=o.barSpacing)),this.audio=null,this.canvas=null,this.ctx=null,this.waveformData=[],this.progress=0,this._activeMarkerIndex=-1,this._markerLabelTimer=null,this.isPlaying=!1,this.isLoading=!1,this.hasError=!1,this.updateTimer=null,this.resizeObserver=null,this._ac=new AbortController,this.id=this.container.id||N(this.options.url),e.instances.set(this.id,this),e._watchTheme(),this.init(),setTimeout(()=>{this._emit("waveformplayer:ready",{player:this,url:this.options.url})},100)}_emit(t,i,s=!1){let r=new CustomEvent(t,{bubbles:!0,cancelable:s,detail:i});return this.container.dispatchEvent(r),r}_requestSeek(t){this._emit("waveformplayer:request-seek",{...this._buildTrackDetail(),percent:t},!0).defaultPrevented||(this.progress=t,this.drawWaveform?.())}init(){this.createDOM(),this.createAudio(),this.initPlaybackSpeed(),this.initKeyboardControls(),this.initSeekControl(),this.bindEvents(),this.setupResizeObserver(),requestAnimationFrame(()=>{this.resizeCanvas(),this.options.url&&this.load(this.options.url).then(()=>{this.options.autoplay&&this.play()?.catch(()=>{})}).catch(t=>{console.error("[WaveformPlayer] Failed to load audio:",t)})})}createDOM(){this.container.innerHTML="",this.container.className="waveform-player";let t=this.options.buttonAlign;t==="auto"&&(this.options.waveformStyle==="bars"?t="bottom":t="center"),this.options.layout==="preview"&&this.container.classList.add("waveform-layout-preview"),this.container.classList.toggle("waveform-theme-light",this._scheme==="light");let s=this.options.showControls?`
|
|
2
2
|
<button class="waveform-btn${this.options.buttonStyle==="minimal"?" waveform-btn-minimal":""}" aria-label="Play/Pause"${this.options.buttonSize!=null?` style="--wfp-btn-size: ${typeof this.options.buttonSize=="number"?`${this.options.buttonSize}px`:this.options.buttonSize};"`:""}>
|
|
3
3
|
<span class="waveform-icon-play">${this.options.playIcon}</span>
|
|
4
4
|
<span class="waveform-icon-pause" style="display:none;">${this.options.pauseIcon}</span>
|
|
5
5
|
</button>
|
|
6
|
-
`:"",
|
|
6
|
+
`:"",r=this.options.showInfo?`
|
|
7
7
|
<div class="waveform-info">
|
|
8
8
|
${this.options.artwork?`
|
|
9
9
|
<img class="waveform-artwork" src="${this.options.artwork}" alt="Album artwork" style="
|
|
@@ -26,11 +26,11 @@ function W(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}fu
|
|
|
26
26
|
`:""}
|
|
27
27
|
${this.options.showPlaybackSpeed?`
|
|
28
28
|
<div class="waveform-speed">
|
|
29
|
-
<button class="speed-btn" aria-label="Playback speed" aria-haspopup="
|
|
29
|
+
<button class="speed-btn" aria-label="Playback speed" aria-haspopup="menu" aria-expanded="false">
|
|
30
30
|
<span class="speed-value">1x</span>
|
|
31
31
|
</button>
|
|
32
|
-
<div class="speed-menu" style="display: none;">
|
|
33
|
-
${this.options.playbackRates.map(a=>`<button class="speed-option" data-rate="${a}">${a}x</button>`).join("")}
|
|
32
|
+
<div class="speed-menu" role="menu" aria-label="Playback speed" style="display: none;">
|
|
33
|
+
${this.options.playbackRates.map(a=>`<button class="speed-option" role="menuitemradio" tabindex="-1" aria-checked="false" data-rate="${a}">${a}x</button>`).join("")}
|
|
34
34
|
</div>
|
|
35
35
|
</div>
|
|
36
36
|
`:""}
|
|
@@ -45,7 +45,7 @@ function W(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}fu
|
|
|
45
45
|
<div class="waveform-player-inner">
|
|
46
46
|
<div class="waveform-body">
|
|
47
47
|
<div class="waveform-track waveform-align-${t}">
|
|
48
|
-
${
|
|
48
|
+
${s}
|
|
49
49
|
|
|
50
50
|
<div class="waveform-container">
|
|
51
51
|
<canvas></canvas>
|
|
@@ -57,7 +57,7 @@ function W(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}fu
|
|
|
57
57
|
</div>
|
|
58
58
|
</div>
|
|
59
59
|
|
|
60
|
-
${
|
|
60
|
+
${r}
|
|
61
61
|
</div>
|
|
62
62
|
</div>
|
|
63
|
-
`,this.playBtn=this.container.querySelector(".waveform-btn"),this.canvas=this.container.querySelector("canvas"),this.ctx=this.canvas.getContext("2d"),this.titleEl=this.container.querySelector(".waveform-title"),this.artistEl=this.container.querySelector(".waveform-artist"),this.artworkEl=this.container.querySelector(".waveform-artwork"),this.artworkEl&&this.artworkEl.addEventListener("error",()=>{this.artworkEl.src.startsWith("data:")||(this.artworkEl.src=mt)}),this.currentTimeEl=this.container.querySelector(".time-current"),this.totalTimeEl=this.container.querySelector(".time-total"),this.bpmEl=this.container.querySelector(".waveform-bpm"),this.bpmValueEl=this.container.querySelector(".bpm-value"),this.loadingEl=this.container.querySelector(".waveform-loading"),this.errorEl=this.container.querySelector(".waveform-error"),this.markersContainer=this.container.querySelector(".waveform-markers"),this.speedBtn=this.container.querySelector(".speed-btn"),this.speedMenu=this.container.querySelector(".speed-menu"),this.resizeCanvas(),this.updateBPMDisplay()}createAudio(){if(this.options.audioMode==="external"){this.audio=null;return}this.audio=new Audio,this.audio.preload=this.options.preload||"metadata",this.audio.crossOrigin="anonymous"}initPlaybackSpeed(){this.audio&&this.options.playbackRate&&this.options.playbackRate!==1&&(this.audio.playbackRate=this.options.playbackRate),this.options.showPlaybackSpeed&&this.initSpeedControls()}initSpeedControls(){let t=this.container.querySelector(".speed-btn"),i=this.container.querySelector(".speed-menu");if(!t||!i)return;let r=s=>{i.style.display=s?"block":"none",t.setAttribute("aria-expanded",s?"true":"false")};t.addEventListener("click",s=>{s.stopPropagation(),r(i.style.display==="none")},{signal:this._ac.signal}),document.addEventListener("click",()=>r(!1),{signal:this._ac.signal}),i.addEventListener("click",s=>{s.stopPropagation(),s.target.classList.contains("speed-option")&&(this.setPlaybackRate(parseFloat(s.target.dataset.rate)),r(!1),t.focus())},{signal:this._ac.signal}),t.closest(".waveform-speed")?.addEventListener("keydown",s=>{s.key==="Escape"&&i.style.display!=="none"&&(r(!1),t.focus())},{signal:this._ac.signal}),this.updateSpeedUI()}initKeyboardControls(){this.container.setAttribute("tabindex","-1"),this.container.addEventListener("click",t=>{t.target.closest(gt)||(e.getAllInstances().forEach(i=>{i!==this&&i.container.setAttribute("tabindex","-1")}),this.container.setAttribute("tabindex","0"),this.container.focus())},{signal:this._ac.signal}),this.container.addEventListener("keydown",t=>{if(document.activeElement!==this.container)return;let i=t.key,r=!!this.audio,s=r?this.audio.currentTime:0;if(r&&i>="0"&&i<="9"){t.preventDefault(),this.seekToPercent(parseInt(i)/10);return}let a={" ":()=>this.togglePlay()};r&&(a.ArrowLeft=()=>this.seekTo(m(s-5,0,this.audio.duration)),a.ArrowRight=()=>this.seekTo(m(s+5,0,this.audio.duration)),a.ArrowUp=()=>this.setVolume(m(this.audio.volume+.1)),a.ArrowDown=()=>this.setVolume(m(this.audio.volume-.1)),a.m=a.M=()=>this.audio.muted=!this.audio.muted),a[i]&&(t.preventDefault(),a[i]())},{signal:this._ac.signal})}initSeekControl(){this.options.accessibleSeek&&(this.seekEl=this.container.querySelector(".waveform-container"),this.seekEl&&(this.seekEl.setAttribute("role","slider"),this.seekEl.setAttribute("tabindex","0"),this.seekEl.setAttribute("aria-valuemin","0"),this.applySeekLabel(),this.updateSeekAccessibility(),this.seekEl.addEventListener("keydown",t=>{if(t.key===" "||t.key==="Spacebar"){t.preventDefault(),t.stopPropagation(),this.togglePlay();return}let i=this.getSeekDuration();if(!i)return;let r=this.getSeekCurrentTime(),s;switch(t.key){case"ArrowLeft":case"ArrowDown":s=r-st;break;case"ArrowRight":case"ArrowUp":s=r+st;break;case"PageDown":s=r-rt;break;case"PageUp":s=r+rt;break;case"Home":s=0;break;case"End":s=i;break;default:return}t.preventDefault(),t.stopPropagation(),this.seekToSeconds(s)},{signal:this._ac.signal})))}getSeekDuration(){return this.options.audioMode==="external"?this._extDuration||0:this.audio&&Number.isFinite(this.audio.duration)?this.audio.duration:0}getSeekCurrentTime(){return this.options.audioMode==="external"?this.progress*(this._extDuration||0):this.audio&&Number.isFinite(this.audio.currentTime)?this.audio.currentTime:0}seekToSeconds(t){let i=this.getSeekDuration();if(!i)return;let r=m(t,0,i);if(this.options.audioMode==="external"){this._requestSeek(r/i),this.updateSeekAccessibility();return}this.seekTo(r)}applySeekLabel(t=this.options.title){if(!this.seekEl)return;let i=this.options.seekLabel||t||"Seek";this.seekEl.setAttribute("aria-label",i)}updateSeekAccessibility(){if(!this.seekEl)return;let t=this.getSeekDuration(),i=Math.min(this.getSeekCurrentTime(),t);this.seekEl.setAttribute("aria-valuemax",String(Math.round(t))),this.seekEl.setAttribute("aria-valuenow",String(Math.round(i))),this.seekEl.setAttribute("aria-valuetext",`${S(i)} of ${S(t)}`)}initMediaSession(){if(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio)return;this._applyMediaMetadata(),navigator.mediaSession.setActionHandler("play",()=>this.play()),navigator.mediaSession.setActionHandler("pause",()=>this.pause()),navigator.mediaSession.setActionHandler("seekbackward",()=>{this.seekTo(m(this.audio.currentTime-10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekforward",()=>{this.seekTo(m(this.audio.currentTime+10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekto",r=>{r.seekTime!==null&&this.seekTo(r.seekTime)});let t=this.options.onNextTrack,i=this.options.onPreviousTrack;try{navigator.mediaSession.setActionHandler("nexttrack",typeof t=="function"?()=>t(this):null)}catch{}try{navigator.mediaSession.setActionHandler("previoustrack",typeof i=="function"?()=>i(this):null)}catch{}}_applyMediaMetadata(){!("mediaSession"in navigator)||!this.options.enableMediaSession||(navigator.mediaSession.metadata=new MediaMetadata({title:this.options.title||"Unknown Track",artist:this.options.artist||"",album:this.options.album||"",artwork:this.options.artwork?[{src:this.options.artwork,sizes:"512x512",type:"image/jpeg"}]:[]}))}_updateMediaSession(t){if(!(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio))try{t==="playing"&&this._applyMediaMetadata(),navigator.mediaSession.playbackState=t;let i=this.audio.duration;navigator.mediaSession.setPositionState&&i&&isFinite(i)&&navigator.mediaSession.setPositionState({duration:i,playbackRate:this.audio.playbackRate||1,position:m(this.audio.currentTime,0,i)})}catch{}}bindEvents(){this.playBtn&&this.playBtn.addEventListener("click",()=>this.togglePlay()),this.audio&&(this.audio.addEventListener("loadstart",()=>this.setLoading(!0)),this.audio.addEventListener("loadedmetadata",()=>this.onMetadataLoaded()),this.audio.addEventListener("canplay",()=>this.setLoading(!1)),this.audio.addEventListener("play",()=>this.onPlay()),this.audio.addEventListener("pause",()=>this.onPause()),this.audio.addEventListener("ended",()=>this.onEnded()),this.audio.addEventListener("error",i=>this.onError(i))),this.canvas.addEventListener("click",i=>this.handleCanvasClick(i)),this._dragging=!1,this._seekHover=!1,this._handleNear=!1,this.canvas.addEventListener("pointerenter",()=>{this._seekHover=!0,this.drawWaveform(),this._updateSeekHandle()}),this.canvas.addEventListener("pointerleave",()=>{this._seekHover=!1,this._handleNear=!1,this._dragging||this._hideHoverTip(),this.drawWaveform(),this._updateSeekHandle()}),this.canvas.addEventListener("pointerdown",i=>{if(!(i.pointerType==="mouse"&&i.button!==0)){this._dragging=!0;try{this.canvas.setPointerCapture(i.pointerId)}catch{}this._scrubTo(i.clientX)}}),this.canvas.addEventListener("pointermove",i=>{if(this._dragging){this._scrubTo(i.clientX);return}let r=this.canvas.getBoundingClientRect();r.width&&(this._handleNear=Math.abs(i.clientX-r.left-this.progress*r.width)<=10,this._updateSeekHandle())});let t=i=>{if(this._dragging){this._dragging=!1,this._suppressClick=!0;try{this.canvas.releasePointerCapture(i.pointerId)}catch{}this._seekFromPointer(i.clientX),!this._seekHover&&!this.options.showHoverTime&&this._hideHoverTip(),this._updateSeekHandle()}};this.canvas.addEventListener("pointerup",t),this.canvas.addEventListener("pointercancel",t),this.setupHoverTime(),this.setupSeekHandle(),this.resizeHandler=j(()=>this.resizeCanvas(),100),window.addEventListener("resize",this.resizeHandler)}setupResizeObserver(){"ResizeObserver"in window&&(this.resizeObserver=new ResizeObserver(()=>{this.resizeCanvas()}),this.canvas?.parentElement&&this.resizeObserver.observe(this.canvas.parentElement))}async load(t){try{this.setLoading(!0),this.progress=0,this.hasError=!1,this.audio&&(this.audio.src=t,await new Promise((r,s)=>{let a=()=>{this.audio.removeEventListener("loadedmetadata",a),this.audio.removeEventListener("error",o),r()},o=n=>{this.audio.removeEventListener("loadedmetadata",a),this.audio.removeEventListener("error",o),s(n)};this.audio.addEventListener("loadedmetadata",a),this.audio.addEventListener("error",o)}));let i=this.options.title||H(t);if(this.titleEl&&(this.titleEl.textContent=i),this.applySeekLabel(i),this.options.waveform)this.setWaveformData(this.options.waveform);else try{let r=await z(t,this.options.samples,this.options.showBPM);this.waveformData=r.peaks,r.bpm&&(this.detectedBPM=r.bpm,this.updateBPMDisplay())}catch(r){console.warn("[WaveformPlayer] Using placeholder waveform:",r),this.waveformData=Z(this.options.samples)}this.drawWaveform(),this.renderMarkers(),this.initMediaSession(),this.options.onLoad&&this.options.onLoad(this)}catch(i){this.onError(i)}finally{this.setLoading(!1)}}async loadTrack(t,i=null,r=null,s={}){this.isPlaying&&this.pause(),this.audio&&(this.audio.src="",this.audio.load()),this.hasError=!1,this.errorEl&&(this.errorEl.style.display="none"),this.canvas&&(this.canvas.style.opacity="1"),this.playBtn&&(this.playBtn.disabled=!1),this.progress=0,this.waveformData=[],this.options=B(this.options,{url:t,title:i||this.options.title,artist:r||this.options.artist,...s}),s.preload&&this.audio&&(this.audio.preload=s.preload),this.artistEl&&(r?(this.artistEl.textContent=r,this.artistEl.style.display=""):r===""&&(this.artistEl.style.display="none")),s.artwork&&this.artworkEl&&(this.artworkEl.src=s.artwork),this.options.markers=s.markers||[],this.options.waveform=s.waveform||null,await this.load(t),s.autoplay!==!1&&this.play()?.catch(()=>{})}setWaveformData(t){if(typeof t=="string"&&t.trim().endsWith(".json")){fetch(t.trim()).then(i=>i.json()).then(i=>{this.waveformData=Array.isArray(i)?i:i.peaks||[],i.markers&&!this.options.markers?.length&&(this.options.markers=i.markers,this.renderMarkers()),this.drawWaveform()}).catch(()=>{});return}if(typeof t=="string")try{let i=JSON.parse(t);this.waveformData=Array.isArray(i)?i:[]}catch{this.waveformData=t.split(",").map(Number)}else this.waveformData=Array.isArray(t)?t:[];this.drawWaveform()}drawWaveform(){!this.ctx||this.waveformData.length===0||X(this.ctx,this.canvas,this.waveformData,this.progress,{...this.options,waveformStyle:this.options.waveformStyle||"bars",color:this.options.waveformColor,progressColor:this.options.progressColor,seekActive:this._seekHover||this._dragging})}resizeCanvas(){if(!this.canvas||this.isDestroying)return;let t=window.devicePixelRatio||1,i=this.canvas.parentElement.getBoundingClientRect();this.canvas.width=i.width*t,this.canvas.height=this.options.height*t,this.canvas.parentElement.style.height=this.options.height+"px",this.drawWaveform()}renderMarkers(){if(!this.markersContainer||(this.markersContainer.innerHTML="",this._activeMarkerIndex=-1,clearTimeout(this._markerLabelTimer),!this.options.showMarkers||!this.options.markers?.length))return;let t=this.getSeekDuration();t&&this.options.markers.forEach((i,r)=>{if(i.time>t){console.warn(`[WaveformPlayer] Marker "${i.label}" at ${i.time}s exceeds audio duration of ${t}s`);return}let s=i.time/t*100,a=document.createElement("button");a.className="waveform-marker",a.style.left=`${s}%`,a.style.backgroundColor=i.color||"rgba(255, 255, 255, 0.5)",a.setAttribute("aria-label",i.label),a.setAttribute("data-time",i.time);let o=document.createElement("span");o.className="waveform-marker-tooltip",o.textContent=i.label,a.appendChild(o),a.addEventListener("click",n=>{n.stopPropagation(),this.seekTo(i.time),this.options.playOnSeek&&!this.isPlaying&&this.play()}),this.markersContainer.appendChild(a)})}setActiveMarker(t){if(!this.markersContainer)return;this.markersContainer.querySelectorAll(".waveform-marker").forEach((r,s)=>r.classList.toggle("active",s===t))}updateActiveMarker(){if(!this.markersContainer)return;let t=this.markersContainer.querySelectorAll(".waveform-marker");if(!t.length)return;let i=this.getSeekDuration(),r=i?this.progress*i:0,s=-1,a=-1/0;t.forEach((o,n)=>{let l=parseFloat(o.getAttribute("data-time"));Number.isFinite(l)&&l<=r+.05&&l>a&&(a=l,s=n)}),s!==this._activeMarkerIndex&&(this._activeMarkerIndex=s,this.setActiveMarker(s),clearTimeout(this._markerLabelTimer),t.forEach((o,n)=>o.classList.toggle("show-label",n===s)),s>=0&&(this._markerLabelTimer=setTimeout(()=>{this.markersContainer?.querySelectorAll(".waveform-marker").forEach(o=>o.classList.remove("show-label"))},2500)))}setupHoverTime(){if(!this.seekEl)return;let t=document.createElement("div");t.className="waveform-hover-time",t.setAttribute("aria-hidden","true"),this.seekEl.appendChild(t),this.hoverTimeEl=t,this.options.showHoverTime&&(this.seekEl.addEventListener("pointermove",i=>{this._dragging||this._updateHoverTip(i.clientX)}),this.seekEl.addEventListener("pointerleave",()=>{this._dragging||this._hideHoverTip()}))}_updateHoverTip(t){let i=this.hoverTimeEl;if(!i)return;let r=this.getSeekDuration();if(!r){i.style.opacity="0";return}let s=this.canvas.getBoundingClientRect(),a=m((t-s.left)/s.width);i.textContent=S(a*r),i.style.left=a*100+"%",i.style.opacity="1"}_hideHoverTip(){this.hoverTimeEl&&(this.hoverTimeEl.style.opacity="0")}_scrubTo(t){let i=this.canvas.getBoundingClientRect();if(!i.width)return;this.progress=m((t-i.left)/i.width),this.drawWaveform(),this._updateSeekHandle(),this._updateHoverTip(t);let r=this.getSeekDuration();r&&this.currentTimeEl&&(this.currentTimeEl.textContent=S(this.progress*r))}setupSeekHandle(){if(!this.options.seekHandle||this.options.waveformStyle!=="seekbar"||!this.seekEl)return;let t=document.createElement("div");t.className="waveform-seek-handle",t.setAttribute("aria-hidden","true"),this.seekEl.appendChild(t),this.seekHandleEl=t}_updateSeekHandle(){let t=this.seekHandleEl;t&&(t.style.left=this.progress*100+"%",t.classList.toggle("is-visible",this._seekHover||this._dragging),t.classList.toggle("is-active",this._dragging||this._handleNear))}handleCanvasClick(t){if(this._suppressClick){this._suppressClick=!1;return}this._seekFromPointer(t.clientX)}_seekFromPointer(t){let i=this.canvas.getBoundingClientRect();if(!i.width)return;let r=m((t-i.left)/i.width);if(this.options.audioMode==="external"){this._requestSeek(r);return}!this.audio||!this.audio.duration||this.seekToPercent(r)}setLoading(t){this.isLoading=t,this.loadingEl&&(this.loadingEl.style.display=t?"block":"none"),this.seekEl&&this.seekEl.setAttribute("aria-busy",t?"true":"false")}onMetadataLoaded(){this.isDestroying||(this.totalTimeEl&&(this.totalTimeEl.textContent=S(this.audio.duration)),this.renderMarkers(),this.updateSeekAccessibility())}setPlayButtonState(t){if(!this.playBtn)return;this.playBtn.classList.toggle("playing",t);let i=this.playBtn.querySelector(".waveform-icon-play"),r=this.playBtn.querySelector(".waveform-icon-pause");i&&(i.style.display=t?"none":"flex"),r&&(r.style.display=t?"flex":"none")}onPlay(){this.isDestroying||(this.isPlaying=!0,this.setPlayButtonState(!0),this.startSmoothUpdate(),this._updateMediaSession("playing"),this._emit("waveformplayer:play",{player:this,url:this.options.url}),this.options.onPlay&&this.options.onPlay(this))}onPause(){this.isDestroying||(this.isPlaying=!1,this.setPlayButtonState(!1),this.stopSmoothUpdate(),this._updateMediaSession("paused"),this._emit("waveformplayer:pause",{player:this,url:this.options.url}),this.options.onPause&&this.options.onPause(this))}onEnded(){if(this.isDestroying)return;let t=this.audio.duration;this.progress=0,this.audio.currentTime=0,this.drawWaveform(),this.currentTimeEl&&(this.currentTimeEl.textContent="0:00"),this._emit("waveformplayer:ended",{player:this,url:this.options.url,currentTime:t,duration:t}),this.onPause(),this.options.onEnd&&this.options.onEnd(this)}onError(t){this.isDestroying||(console.error("[WaveformPlayer] Audio error:",t),this.hasError=!0,this.setLoading(!1),this.errorEl&&(this.errorEl.style.display="flex"),this.canvas&&(this.canvas.style.opacity="0.2"),this.playBtn&&(this.playBtn.disabled=!0),this.options.onError&&this.options.onError(t,this))}startSmoothUpdate(){this.stopSmoothUpdate();let t=()=>{this.isPlaying&&this.audio&&this.audio.duration&&(this.updateProgress(),this.updateTimer=requestAnimationFrame(t))};this.updateTimer=requestAnimationFrame(t)}stopSmoothUpdate(){this.updateTimer&&(cancelAnimationFrame(this.updateTimer),this.updateTimer=null)}updateProgress(){if(!this.audio||!this.audio.duration||this._dragging)return;let t=this.audio.currentTime/this.audio.duration;Math.abs(t-this.progress)>.001&&(this.progress=t,this.drawWaveform(),this._updateSeekHandle()),this.currentTimeEl&&(this.currentTimeEl.textContent=S(this.audio.currentTime)),this._emit("waveformplayer:timeupdate",{player:this,currentTime:this.audio.currentTime,duration:this.audio.duration,progress:this.progress,url:this.options.url}),this.options.onTimeUpdate&&this.options.onTimeUpdate(this.audio.currentTime,this.audio.duration,this),this.updateActiveMarker(),this.updateSeekAccessibility()}updateBPMDisplay(){let t=this.options.bpm||this.detectedBPM;this.bpmEl&&this.bpmValueEl&&t&&(this.bpmValueEl.textContent=Math.round(t),this.bpmEl.style.display="inline-flex")}refreshTheme(){if(!this._autoTheme)return;this._scheme=R();let t=F(this.options.colorPreset);for(let i of this._presetKeys||[])i in t&&(this.options[i]=t[i]);this._applyThemeColors()}_applyThemeColors(){this.container.classList.toggle("waveform-theme-light",this._scheme==="light"),this.canvas&&this.drawWaveform()}static _watchTheme(){if(e._themeWatch||typeof document>"u")return;let t=()=>requestAnimationFrame(()=>{e.instances.forEach(a=>{try{a.refreshTheme()}catch{}})}),i={attributes:!0,attributeFilter:["class","data-theme","data-color-scheme","style"]},r=new MutationObserver(t);r.observe(document.documentElement,i),document.body&&r.observe(document.body,i);let s=null;try{s=window.matchMedia("(prefers-color-scheme: dark)"),s.addEventListener("change",t)}catch{}e._themeWatch={obs:r,mq:s,refresh:t}}updateSpeedUI(){if(!this.audio)return;let t=this.container.querySelector(".speed-value");if(t){let i=this.audio.playbackRate;t.textContent=i===1?"1x":`${i}x`}this.container.querySelectorAll(".speed-option").forEach(i=>{i.classList.toggle("active",parseFloat(i.dataset.rate)===this.audio.playbackRate)})}play(){if(this.options.singlePlay&&e.currentlyPlaying&&e.currentlyPlaying!==this&&e.currentlyPlaying.pause(),this.options.audioMode==="external"){this._emit("waveformplayer:request-play",this._buildTrackDetail(),!0).defaultPrevented||(e.currentlyPlaying=this);return}return e.currentlyPlaying=this,this.audio.play()}pause(){if(e.currentlyPlaying===this&&(e.currentlyPlaying=null),this.options.audioMode==="external"){this._emit("waveformplayer:request-pause",this._buildTrackDetail(),!0);return}this.audio.pause()}_buildTrackDetail(){return{url:this.options.url,title:this.options.title,artist:this.options.artist,artwork:this.options.artwork,markers:this.options.markers,waveform:this.options.waveform,id:this.id,player:this}}setPlayingState(t){let i=this.isPlaying;this.isPlaying=!!t,this.setPlayButtonState(this.isPlaying),this.isPlaying&&!i?(this.startSmoothUpdate?.(),this._emit("waveformplayer:play",{player:this,url:this.options.url}),this.options.onPlay&&this.options.onPlay(this)):!this.isPlaying&&i&&(this.stopSmoothUpdate?.(),this._emit("waveformplayer:pause",{player:this,url:this.options.url}),this.options.onPause&&this.options.onPause(this))}setProgress(t,i){!i||i<=0||(this.progress=m(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=S(t)),this._extDuration=i,this.totalTimeEl&&(!this.totalTimeEl.dataset._extSet||this.totalTimeEl.dataset._extDur!==String(i))&&(this.totalTimeEl.textContent=S(i),this.totalTimeEl.dataset._extSet="1",this.totalTimeEl.dataset._extDur=String(i)),this.drawWaveform?.(),this.updateActiveMarker(),this._emit("waveformplayer:timeupdate",{player:this,currentTime:t,duration:i,progress:this.progress,url:this.options.url}),this.options.onTimeUpdate&&this.options.onTimeUpdate(t,i,this),this.progress>=1?this._extEnded||(this._extEnded=!0,this._emit("waveformplayer:ended",{player:this,url:this.options.url,currentTime:i,duration:i}),this.options.onEnd&&this.options.onEnd(this)):this._extEnded=!1,this.updateSeekAccessibility())}togglePlay(){this.isPlaying?this.pause():this.play()}seekTo(t){this.audio&&this.audio.duration&&(this.audio.currentTime=m(t,0,this.audio.duration),this.updateProgress())}seekToPercent(t){this.audio&&this.audio.duration&&(this.audio.currentTime=this.audio.duration*m(t),this.updateProgress())}setVolume(t){let i=Number(t);this.audio&&Number.isFinite(i)&&(this.audio.volume=m(i))}setPlaybackRate(t){if(!this.audio)return;let i=m(t,.5,2);this.audio.playbackRate=i,this.options.playbackRate=i,this.updateSpeedUI()}destroy(){this.isDestroying=!0,this._emit("waveformplayer:destroy",{player:this,url:this.options.url}),this.pause(),this.stopSmoothUpdate(),clearTimeout(this._markerLabelTimer),this._ac?.abort(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.resizeHandler&&(window.removeEventListener("resize",this.resizeHandler),this.resizeHandler=null),e.instances.delete(this.id),e.currentlyPlaying===this&&(e.currentlyPlaying=null),this.audio&&(this.audio.pause(),this.audio.src="",this.audio.load(),this.audio=null),this.container.innerHTML="",this.canvas=null,this.ctx=null,this.playBtn=null,this.waveformData=[]}static getInstance(t){if(typeof t=="string"){let i=this.instances.get(t);if(i)return i;let r=document.getElementById(t);if(r)return Array.from(this.instances.values()).find(s=>s.container===r)}if(t instanceof HTMLElement)return Array.from(this.instances.values()).find(i=>i.container===t)}static getAllInstances(){return Array.from(this.instances.values())}static destroyAll(){this.instances.forEach(t=>t.destroy()),this.instances.clear()}static async generateWaveformData(t,i=1800){try{return(await z(t,i)).peaks}catch(r){throw console.error("[WaveformPlayer] Failed to generate waveform:",r),r}}static getPeaksUrl(t){if(!t)return;let i=t.replace(/\.(mp3|wav|ogg|flac|m4a|aac)(\?[^#]*)?(#.*)?$/i,".json$2$3");return i===t?void 0:i}};T.utils={formatTime:S,extractTitleFromUrl:H,escapeHtml:x,isSafeHref:U,parseDataAttributes:D};var $=()=>typeof window<"u"&&typeof document<"u";function O(){if(!$())return;document.querySelectorAll("[data-waveform-player]").forEach(t=>{if(t.dataset.waveformInitialized!=="true")try{new T(t),t.dataset.waveformInitialized="true"}catch(i){console.error("[WaveformPlayer] Failed to initialize:",i,t)}})}$()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",O):O());T.init=O;$()&&(window.WaveformPlayer=T);var Ht=T;export{T as WaveformPlayer,Ht as default};
|
|
63
|
+
`,this.playBtn=this.container.querySelector(".waveform-btn"),this.canvas=this.container.querySelector("canvas"),this.ctx=this.canvas.getContext("2d"),this.titleEl=this.container.querySelector(".waveform-title"),this.artistEl=this.container.querySelector(".waveform-artist"),this.artworkEl=this.container.querySelector(".waveform-artwork"),this.artworkEl&&this.artworkEl.addEventListener("error",()=>{this.artworkEl.src.startsWith("data:")||(this.artworkEl.src=mt)}),this.currentTimeEl=this.container.querySelector(".time-current"),this.totalTimeEl=this.container.querySelector(".time-total"),this.bpmEl=this.container.querySelector(".waveform-bpm"),this.bpmValueEl=this.container.querySelector(".bpm-value"),this.loadingEl=this.container.querySelector(".waveform-loading"),this.errorEl=this.container.querySelector(".waveform-error"),this.markersContainer=this.container.querySelector(".waveform-markers"),this.speedBtn=this.container.querySelector(".speed-btn"),this.speedMenu=this.container.querySelector(".speed-menu"),this.resizeCanvas(),this.updateBPMDisplay()}createAudio(){if(this.options.audioMode==="external"){this.audio=null;return}this.audio=new Audio,this.audio.preload=this.options.preload||"metadata",this.audio.crossOrigin="anonymous"}initPlaybackSpeed(){this.audio&&this.options.playbackRate&&this.options.playbackRate!==1&&(this.audio.playbackRate=this.options.playbackRate),this.options.showPlaybackSpeed&&this.initSpeedControls()}initSpeedControls(){let t=this.container.querySelector(".speed-btn"),i=this.container.querySelector(".speed-menu");if(!t||!i)return;let s=()=>Array.from(i.querySelectorAll(".speed-option")),r=()=>i.style.display!=="none",a=l=>{if(i.style.display=l?"block":"none",t.setAttribute("aria-expanded",l?"true":"false"),l){let h=s();(h.find(d=>d.getAttribute("aria-checked")==="true")||h[0])?.focus()}},o=l=>{let h=s();h.length&&h[(l+h.length)%h.length].focus()},n=l=>{this.setPlaybackRate(parseFloat(l.dataset.rate)),a(!1),t.focus()};t.addEventListener("click",l=>{l.stopPropagation(),a(!r())},{signal:this._ac.signal}),document.addEventListener("click",()=>a(!1),{signal:this._ac.signal}),i.addEventListener("click",l=>{l.stopPropagation();let h=l.target.closest(".speed-option");h&&n(h)},{signal:this._ac.signal}),t.closest(".waveform-speed")?.addEventListener("keydown",l=>{let h=s(),d=h.indexOf(document.activeElement);if(!r()){(l.key==="ArrowDown"||l.key==="ArrowUp")&&document.activeElement===t&&(l.preventDefault(),a(!0));return}switch(l.key){case"ArrowDown":l.preventDefault(),o(d<0?0:d+1);break;case"ArrowUp":l.preventDefault(),o(d<0?h.length-1:d-1);break;case"Home":l.preventDefault(),o(0);break;case"End":l.preventDefault(),o(h.length-1);break;case"Escape":l.preventDefault(),a(!1),t.focus();break;case"Tab":a(!1);break}},{signal:this._ac.signal}),this.updateSpeedUI()}initKeyboardControls(){this.container.setAttribute("tabindex","-1"),this.container.addEventListener("click",t=>{t.target.closest(gt)||(e.getAllInstances().forEach(i=>{i!==this&&i.container.setAttribute("tabindex","-1")}),this.container.setAttribute("tabindex","0"),this.container.focus())},{signal:this._ac.signal}),this.container.addEventListener("keydown",t=>{if(document.activeElement!==this.container)return;let i=t.key,s=!!this.audio,r=s?this.audio.currentTime:0;if(s&&i>="0"&&i<="9"){t.preventDefault(),this.seekToPercent(parseInt(i)/10);return}let a={" ":()=>this.togglePlay()};s&&(a.ArrowLeft=()=>this.seekTo(m(r-5,0,this.audio.duration)),a.ArrowRight=()=>this.seekTo(m(r+5,0,this.audio.duration)),a.ArrowUp=()=>this.setVolume(m(this.audio.volume+.1)),a.ArrowDown=()=>this.setVolume(m(this.audio.volume-.1)),a.m=a.M=()=>this.audio.muted=!this.audio.muted),a[i]&&(t.preventDefault(),a[i]())},{signal:this._ac.signal})}initSeekControl(){this.options.accessibleSeek&&(this.seekEl=this.container.querySelector(".waveform-container"),this.seekEl&&(this.seekEl.setAttribute("role","slider"),this.seekEl.setAttribute("tabindex","0"),this.seekEl.setAttribute("aria-valuemin","0"),this.applySeekLabel(),this.updateSeekAccessibility(),this.seekEl.addEventListener("keydown",t=>{if(t.key===" "||t.key==="Spacebar"){t.preventDefault(),t.stopPropagation(),this.togglePlay();return}let i=this.getSeekDuration();if(!i)return;let s=this.getSeekCurrentTime(),r;switch(t.key){case"ArrowLeft":case"ArrowDown":r=s-st;break;case"ArrowRight":case"ArrowUp":r=s+st;break;case"PageDown":r=s-rt;break;case"PageUp":r=s+rt;break;case"Home":r=0;break;case"End":r=i;break;default:return}t.preventDefault(),t.stopPropagation(),this.seekToSeconds(r)},{signal:this._ac.signal})))}getSeekDuration(){return this.options.audioMode==="external"?this._extDuration||0:this.audio&&Number.isFinite(this.audio.duration)?this.audio.duration:0}getSeekCurrentTime(){return this.options.audioMode==="external"?this.progress*(this._extDuration||0):this.audio&&Number.isFinite(this.audio.currentTime)?this.audio.currentTime:0}seekToSeconds(t){let i=this.getSeekDuration();if(!i)return;let s=m(t,0,i);if(this.options.audioMode==="external"){this._requestSeek(s/i),this.updateSeekAccessibility();return}this.seekTo(s)}applySeekLabel(t=this.options.title){if(!this.seekEl)return;let i=this.options.seekLabel||t||"Seek";this.seekEl.setAttribute("aria-label",i)}updateSeekAccessibility(){if(!this.seekEl)return;let t=this.getSeekDuration(),i=Math.min(this.getSeekCurrentTime(),t);this.seekEl.setAttribute("aria-valuemax",String(Math.round(t))),this.seekEl.setAttribute("aria-valuenow",String(Math.round(i))),this.seekEl.setAttribute("aria-valuetext",`${S(i)} of ${S(t)}`)}initMediaSession(){if(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio)return;this._applyMediaMetadata(),navigator.mediaSession.setActionHandler("play",()=>this.play()),navigator.mediaSession.setActionHandler("pause",()=>this.pause()),navigator.mediaSession.setActionHandler("seekbackward",()=>{this.seekTo(m(this.audio.currentTime-10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekforward",()=>{this.seekTo(m(this.audio.currentTime+10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekto",s=>{s.seekTime!==null&&this.seekTo(s.seekTime)});let t=this.options.onNextTrack,i=this.options.onPreviousTrack;try{navigator.mediaSession.setActionHandler("nexttrack",typeof t=="function"?()=>t(this):null)}catch{}try{navigator.mediaSession.setActionHandler("previoustrack",typeof i=="function"?()=>i(this):null)}catch{}}_applyMediaMetadata(){!("mediaSession"in navigator)||!this.options.enableMediaSession||(navigator.mediaSession.metadata=new MediaMetadata({title:this.options.title||"Unknown Track",artist:this.options.artist||"",album:this.options.album||"",artwork:this.options.artwork?[{src:this.options.artwork,sizes:"512x512",type:"image/jpeg"}]:[]}))}_updateMediaSession(t){if(!(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio))try{t==="playing"&&this.initMediaSession(),navigator.mediaSession.playbackState=t;let i=this.audio.duration;navigator.mediaSession.setPositionState&&i&&isFinite(i)&&navigator.mediaSession.setPositionState({duration:i,playbackRate:this.audio.playbackRate||1,position:m(this.audio.currentTime,0,i)})}catch{}}bindEvents(){this.playBtn&&this.playBtn.addEventListener("click",()=>this.togglePlay()),this.audio&&(this.audio.addEventListener("loadstart",()=>this.setLoading(!0)),this.audio.addEventListener("loadedmetadata",()=>this.onMetadataLoaded()),this.audio.addEventListener("canplay",()=>this.setLoading(!1)),this.audio.addEventListener("play",()=>this.onPlay()),this.audio.addEventListener("pause",()=>this.onPause()),this.audio.addEventListener("ended",()=>this.onEnded()),this.audio.addEventListener("error",i=>this.onError(i))),this.canvas.addEventListener("click",i=>this.handleCanvasClick(i)),this._dragging=!1,this._seekHover=!1,this._handleNear=!1,this.canvas.addEventListener("pointerenter",()=>{this._seekHover=!0,this.drawWaveform(),this._updateSeekHandle()}),this.canvas.addEventListener("pointerleave",()=>{this._seekHover=!1,this._handleNear=!1,this._dragging||this._hideHoverTip(),this.drawWaveform(),this._updateSeekHandle()}),this.canvas.addEventListener("pointerdown",i=>{if(!(i.pointerType==="mouse"&&i.button!==0)){this._dragging=!0;try{this.canvas.setPointerCapture(i.pointerId)}catch{}this._scrubTo(i.clientX)}}),this.canvas.addEventListener("pointermove",i=>{if(this._dragging){this._scrubTo(i.clientX);return}let s=this.canvas.getBoundingClientRect();s.width&&(this._handleNear=Math.abs(i.clientX-s.left-this.progress*s.width)<=10,this._updateSeekHandle())});let t=i=>{if(this._dragging){this._dragging=!1,this._suppressClick=!0;try{this.canvas.releasePointerCapture(i.pointerId)}catch{}this._seekFromPointer(i.clientX),!this._seekHover&&!this.options.showHoverTime&&this._hideHoverTip(),this._updateSeekHandle()}};this.canvas.addEventListener("pointerup",t),this.canvas.addEventListener("pointercancel",t),this.setupHoverTime(),this.setupSeekHandle(),this.resizeHandler=j(()=>this.resizeCanvas(),100),window.addEventListener("resize",this.resizeHandler)}setupResizeObserver(){"ResizeObserver"in window&&(this.resizeObserver=new ResizeObserver(()=>{this.resizeCanvas()}),this.canvas?.parentElement&&this.resizeObserver.observe(this.canvas.parentElement))}async load(t){try{this.setLoading(!0),this.progress=0,this.hasError=!1,this.audio&&(this.audio.src=t,await new Promise((s,r)=>{let a=()=>{this.audio.removeEventListener("loadedmetadata",a),this.audio.removeEventListener("error",o),s()},o=n=>{this.audio.removeEventListener("loadedmetadata",a),this.audio.removeEventListener("error",o),r(n)};this.audio.addEventListener("loadedmetadata",a),this.audio.addEventListener("error",o)}));let i=this.options.title||H(t);if(this.titleEl&&(this.titleEl.textContent=i),this.applySeekLabel(i),this.options.waveform)this.setWaveformData(this.options.waveform);else try{let s=await z(t,this.options.samples,this.options.showBPM);this.waveformData=s.peaks,s.bpm&&(this.detectedBPM=s.bpm,this.updateBPMDisplay())}catch(s){console.warn("[WaveformPlayer] Using placeholder waveform:",s),this.waveformData=Z(this.options.samples)}this.drawWaveform(),this.renderMarkers(),this.options.onLoad&&this.options.onLoad(this)}catch(i){this.onError(i)}finally{this.setLoading(!1)}}async loadTrack(t,i=null,s=null,r={}){this.isPlaying&&this.pause(),this.audio&&(this.audio.src="",this.audio.load()),this.hasError=!1,this.errorEl&&(this.errorEl.style.display="none"),this.canvas&&(this.canvas.style.opacity="1"),this.playBtn&&(this.playBtn.disabled=!1),this.progress=0,this.waveformData=[],this.options=B(this.options,{url:t,title:i||this.options.title,artist:s||this.options.artist,...r}),r.preload&&this.audio&&(this.audio.preload=r.preload),this.artistEl&&(s?(this.artistEl.textContent=s,this.artistEl.style.display=""):s===""&&(this.artistEl.style.display="none")),r.artwork&&this.artworkEl&&(this.artworkEl.src=r.artwork),this.options.markers=r.markers||[],this.options.waveform=r.waveform||null,await this.load(t),r.autoplay!==!1&&this.play()?.catch(()=>{})}setWaveformData(t){if(typeof t=="string"&&t.trim().endsWith(".json")){fetch(t.trim()).then(i=>i.json()).then(i=>{this.waveformData=Array.isArray(i)?i:i.peaks||[],i.markers&&!this.options.markers?.length&&(this.options.markers=i.markers,this.renderMarkers()),this.drawWaveform()}).catch(()=>{});return}if(typeof t=="string")try{let i=JSON.parse(t);this.waveformData=Array.isArray(i)?i:[]}catch{this.waveformData=t.split(",").map(Number)}else this.waveformData=Array.isArray(t)?t:[];this.drawWaveform()}drawWaveform(){!this.ctx||this.waveformData.length===0||X(this.ctx,this.canvas,this.waveformData,this.progress,{...this.options,waveformStyle:this.options.waveformStyle||"bars",color:this.options.waveformColor,progressColor:this.options.progressColor,seekActive:this._seekHover||this._dragging})}resizeCanvas(){if(!this.canvas||this.isDestroying)return;let t=window.devicePixelRatio||1,i=this.canvas.parentElement.getBoundingClientRect();this.canvas.width=i.width*t,this.canvas.height=this.options.height*t,this.canvas.parentElement.style.height=this.options.height+"px",this.drawWaveform()}renderMarkers(){if(!this.markersContainer||(this.markersContainer.innerHTML="",this._activeMarkerIndex=-1,clearTimeout(this._markerLabelTimer),!this.options.showMarkers||!this.options.markers?.length))return;let t=this.getSeekDuration();t&&this.options.markers.forEach((i,s)=>{if(i.time>t){console.warn(`[WaveformPlayer] Marker "${i.label}" at ${i.time}s exceeds audio duration of ${t}s`);return}let r=i.time/t*100,a=document.createElement("button");a.className="waveform-marker",a.style.left=`${r}%`,a.style.backgroundColor=i.color||"rgba(255, 255, 255, 0.5)",a.setAttribute("aria-label",i.label),a.setAttribute("data-time",i.time);let o=document.createElement("span");o.className="waveform-marker-tooltip",o.textContent=i.label,a.appendChild(o),a.addEventListener("click",n=>{n.stopPropagation(),this.seekTo(i.time),this.options.playOnSeek&&!this.isPlaying&&this.play()}),this.markersContainer.appendChild(a)})}setActiveMarker(t){if(!this.markersContainer)return;this.markersContainer.querySelectorAll(".waveform-marker").forEach((s,r)=>s.classList.toggle("active",r===t))}updateActiveMarker(){if(!this.markersContainer)return;let t=this.markersContainer.querySelectorAll(".waveform-marker");if(!t.length)return;let i=this.getSeekDuration(),s=i?this.progress*i:0,r=-1,a=-1/0;t.forEach((o,n)=>{let l=parseFloat(o.getAttribute("data-time"));Number.isFinite(l)&&l<=s+.05&&l>a&&(a=l,r=n)}),r!==this._activeMarkerIndex&&(this._activeMarkerIndex=r,this.setActiveMarker(r),clearTimeout(this._markerLabelTimer),t.forEach((o,n)=>o.classList.toggle("show-label",n===r)),r>=0&&(this._markerLabelTimer=setTimeout(()=>{this.markersContainer?.querySelectorAll(".waveform-marker").forEach(o=>o.classList.remove("show-label"))},2500)))}setupHoverTime(){if(!this.seekEl)return;let t=document.createElement("div");t.className="waveform-hover-time",t.setAttribute("aria-hidden","true"),this.seekEl.appendChild(t),this.hoverTimeEl=t,this.options.showHoverTime&&(this.seekEl.addEventListener("pointermove",i=>{this._dragging||this._updateHoverTip(i.clientX)}),this.seekEl.addEventListener("pointerleave",()=>{this._dragging||this._hideHoverTip()}))}_updateHoverTip(t){let i=this.hoverTimeEl;if(!i)return;let s=this.getSeekDuration();if(!s){i.style.opacity="0";return}let r=this.canvas.getBoundingClientRect(),a=m((t-r.left)/r.width);i.textContent=S(a*s),i.style.left=a*100+"%",i.style.opacity="1"}_hideHoverTip(){this.hoverTimeEl&&(this.hoverTimeEl.style.opacity="0")}_scrubTo(t){let i=this.canvas.getBoundingClientRect();if(!i.width)return;this.progress=m((t-i.left)/i.width),this.drawWaveform(),this._updateSeekHandle(),this._updateHoverTip(t);let s=this.getSeekDuration();s&&this.currentTimeEl&&(this.currentTimeEl.textContent=S(this.progress*s))}setupSeekHandle(){if(!this.options.seekHandle||this.options.waveformStyle!=="seekbar"||!this.seekEl)return;let t=document.createElement("div");t.className="waveform-seek-handle",t.setAttribute("aria-hidden","true"),this.seekEl.appendChild(t),this.seekHandleEl=t}_updateSeekHandle(){let t=this.seekHandleEl;t&&(t.style.left=this.progress*100+"%",t.classList.toggle("is-visible",this._seekHover||this._dragging),t.classList.toggle("is-active",this._dragging||this._handleNear))}handleCanvasClick(t){if(this._suppressClick){this._suppressClick=!1;return}this._seekFromPointer(t.clientX)}_seekFromPointer(t){let i=this.canvas.getBoundingClientRect();if(!i.width)return;let s=m((t-i.left)/i.width);if(this.options.audioMode==="external"){this._requestSeek(s);return}!this.audio||!this.audio.duration||this.seekToPercent(s)}setLoading(t){this.isLoading=t,this.loadingEl&&(this.loadingEl.style.display=t?"block":"none"),this.seekEl&&this.seekEl.setAttribute("aria-busy",t?"true":"false")}onMetadataLoaded(){this.isDestroying||(this.totalTimeEl&&(this.totalTimeEl.textContent=S(this.audio.duration)),this.renderMarkers(),this.updateSeekAccessibility())}setPlayButtonState(t){if(!this.playBtn)return;this.playBtn.classList.toggle("playing",t);let i=this.playBtn.querySelector(".waveform-icon-play"),s=this.playBtn.querySelector(".waveform-icon-pause");i&&(i.style.display=t?"none":"flex"),s&&(s.style.display=t?"flex":"none")}onPlay(){this.isDestroying||(this.isPlaying=!0,this.setPlayButtonState(!0),this.startSmoothUpdate(),this._updateMediaSession("playing"),this._emit("waveformplayer:play",{player:this,url:this.options.url}),this.options.onPlay&&this.options.onPlay(this))}onPause(){this.isDestroying||(this.isPlaying=!1,this.setPlayButtonState(!1),this.stopSmoothUpdate(),this._updateMediaSession("paused"),this._emit("waveformplayer:pause",{player:this,url:this.options.url}),this.options.onPause&&this.options.onPause(this))}onEnded(){if(this.isDestroying)return;let t=this.audio.duration;this.progress=0,this.audio.currentTime=0,this.drawWaveform(),this.currentTimeEl&&(this.currentTimeEl.textContent="0:00"),this._emit("waveformplayer:ended",{player:this,url:this.options.url,currentTime:t,duration:t}),this.onPause(),this.options.onEnd&&this.options.onEnd(this)}onError(t){this.isDestroying||(console.error("[WaveformPlayer] Audio error:",t),this.hasError=!0,this.setLoading(!1),this.errorEl&&(this.errorEl.style.display="flex"),this.canvas&&(this.canvas.style.opacity="0.2"),this.playBtn&&(this.playBtn.disabled=!0),this.options.onError&&this.options.onError(t,this))}startSmoothUpdate(){this.stopSmoothUpdate();let t=()=>{this.isPlaying&&this.audio&&this.audio.duration&&(this.updateProgress(),this.updateTimer=requestAnimationFrame(t))};this.updateTimer=requestAnimationFrame(t)}stopSmoothUpdate(){this.updateTimer&&(cancelAnimationFrame(this.updateTimer),this.updateTimer=null)}updateProgress(){if(!this.audio||!this.audio.duration||this._dragging)return;let t=this.audio.currentTime/this.audio.duration;Math.abs(t-this.progress)>.001&&(this.progress=t,this.drawWaveform(),this._updateSeekHandle()),this.currentTimeEl&&(this.currentTimeEl.textContent=S(this.audio.currentTime)),this._emit("waveformplayer:timeupdate",{player:this,currentTime:this.audio.currentTime,duration:this.audio.duration,progress:this.progress,url:this.options.url}),this.options.onTimeUpdate&&this.options.onTimeUpdate(this.audio.currentTime,this.audio.duration,this),this.updateActiveMarker(),this.updateSeekAccessibility()}updateBPMDisplay(){let t=this.options.bpm||this.detectedBPM;this.bpmEl&&this.bpmValueEl&&t&&(this.bpmValueEl.textContent=Math.round(t),this.bpmEl.style.display="inline-flex")}refreshTheme(){if(!this._autoTheme)return;this._scheme=R();let t=F(this.options.colorPreset);for(let i of this._presetKeys||[])i in t&&(this.options[i]=t[i]);this._applyThemeColors()}_applyThemeColors(){this.container.classList.toggle("waveform-theme-light",this._scheme==="light"),this.canvas&&this.drawWaveform()}static _watchTheme(){if(e._themeWatch||typeof document>"u")return;let t=()=>requestAnimationFrame(()=>{e.instances.forEach(a=>{try{a.refreshTheme()}catch{}})}),i={attributes:!0,attributeFilter:["class","data-theme","data-color-scheme","style"]},s=new MutationObserver(t);s.observe(document.documentElement,i),document.body&&s.observe(document.body,i);let r=null;try{r=window.matchMedia("(prefers-color-scheme: dark)"),r.addEventListener("change",t)}catch{}e._themeWatch={obs:s,mq:r,refresh:t}}updateSpeedUI(){if(!this.audio)return;let t=this.container.querySelector(".speed-value");if(t){let i=this.audio.playbackRate;t.textContent=i===1?"1x":`${i}x`}this.container.querySelectorAll(".speed-option").forEach(i=>{let s=parseFloat(i.dataset.rate)===this.audio.playbackRate;i.classList.toggle("active",s),i.setAttribute("aria-checked",s?"true":"false")})}play(){if(this.options.singlePlay&&e.currentlyPlaying&&e.currentlyPlaying!==this&&e.currentlyPlaying.pause(),this.options.audioMode==="external"){this._emit("waveformplayer:request-play",this._buildTrackDetail(),!0).defaultPrevented||(e.currentlyPlaying=this);return}return e.currentlyPlaying=this,this.audio.play()}pause(){if(e.currentlyPlaying===this&&(e.currentlyPlaying=null),this.options.audioMode==="external"){this._emit("waveformplayer:request-pause",this._buildTrackDetail(),!0);return}this.audio.pause()}_buildTrackDetail(){return{url:this.options.url,title:this.options.title,artist:this.options.artist,artwork:this.options.artwork,markers:this.options.markers,waveform:this.options.waveform,id:this.id,player:this}}setPlayingState(t){let i=this.isPlaying;this.isPlaying=!!t,this.setPlayButtonState(this.isPlaying),this.isPlaying&&!i?(this.startSmoothUpdate?.(),this._emit("waveformplayer:play",{player:this,url:this.options.url}),this.options.onPlay&&this.options.onPlay(this)):!this.isPlaying&&i&&(this.stopSmoothUpdate?.(),this._emit("waveformplayer:pause",{player:this,url:this.options.url}),this.options.onPause&&this.options.onPause(this))}setProgress(t,i){!i||i<=0||(this.progress=m(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=S(t)),this._extDuration=i,this.totalTimeEl&&(!this.totalTimeEl.dataset._extSet||this.totalTimeEl.dataset._extDur!==String(i))&&(this.totalTimeEl.textContent=S(i),this.totalTimeEl.dataset._extSet="1",this.totalTimeEl.dataset._extDur=String(i)),this.drawWaveform?.(),this.updateActiveMarker(),this._emit("waveformplayer:timeupdate",{player:this,currentTime:t,duration:i,progress:this.progress,url:this.options.url}),this.options.onTimeUpdate&&this.options.onTimeUpdate(t,i,this),this.progress>=1?this._extEnded||(this._extEnded=!0,this._emit("waveformplayer:ended",{player:this,url:this.options.url,currentTime:i,duration:i}),this.options.onEnd&&this.options.onEnd(this)):this._extEnded=!1,this.updateSeekAccessibility())}togglePlay(){this.isPlaying?this.pause():this.play()}seekTo(t){this.audio&&this.audio.duration&&(this.audio.currentTime=m(t,0,this.audio.duration),this.updateProgress())}seekToPercent(t){this.audio&&this.audio.duration&&(this.audio.currentTime=this.audio.duration*m(t),this.updateProgress())}setVolume(t){let i=Number(t);this.audio&&Number.isFinite(i)&&(this.audio.volume=m(i))}setPlaybackRate(t){if(!this.audio)return;let i=m(t,.5,2);this.audio.playbackRate=i,this.options.playbackRate=i,this.updateSpeedUI()}destroy(){this.isDestroying=!0,this._emit("waveformplayer:destroy",{player:this,url:this.options.url}),this.pause(),this.stopSmoothUpdate(),clearTimeout(this._markerLabelTimer),this._ac?.abort(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.resizeHandler&&(window.removeEventListener("resize",this.resizeHandler),this.resizeHandler=null),e.instances.delete(this.id),e.currentlyPlaying===this&&(e.currentlyPlaying=null),this.audio&&(this.audio.pause(),this.audio.src="",this.audio.load(),this.audio=null),this.container.innerHTML="",this.canvas=null,this.ctx=null,this.playBtn=null,this.waveformData=[]}static getInstance(t){if(typeof t=="string"){let i=this.instances.get(t);if(i)return i;let s=document.getElementById(t);if(s)return Array.from(this.instances.values()).find(r=>r.container===s)}if(t instanceof HTMLElement)return Array.from(this.instances.values()).find(i=>i.container===t)}static getAllInstances(){return Array.from(this.instances.values())}static destroyAll(){this.instances.forEach(t=>t.destroy()),this.instances.clear()}static async generateWaveformData(t,i=1800){try{return(await z(t,i)).peaks}catch(s){throw console.error("[WaveformPlayer] Failed to generate waveform:",s),s}}static getPeaksUrl(t){if(!t)return;let i=t.replace(/\.(mp3|wav|ogg|flac|m4a|aac)(\?[^#]*)?(#.*)?$/i,".json$2$3");return i===t?void 0:i}};T.utils={formatTime:S,extractTitleFromUrl:H,escapeHtml:x,isSafeHref:U,parseDataAttributes:D};var $=()=>typeof window<"u"&&typeof document<"u";function O(){if(!$())return;document.querySelectorAll("[data-waveform-player]").forEach(t=>{if(t.dataset.waveformInitialized!=="true")try{new T(t),t.dataset.waveformInitialized="true"}catch(i){console.error("[WaveformPlayer] Failed to initialize:",i,t)}})}$()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",O):O());T.init=O;$()&&(window.WaveformPlayer=T);var Ht=T;export{T as WaveformPlayer,Ht as default};
|