midi-audio-player 1.1.2 → 2.0.0
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/CHANGELOG.md +26 -0
- package/README.md +472 -86
- package/dist/index.js +1712 -209
- package/dist/index.js.map +4 -4
- package/dist/index.mjs +13 -13
- package/dist/index.mjs.map +4 -4
- package/dist/midi-audio-player.js +1711 -209
- package/dist/midi-audio-player.min.js +13 -14
- package/index.d.ts +905 -0
- package/index.js +0 -1
- package/package.json +13 -17
- package/src/libraries/audiocompressor.js +186 -0
- package/src/libraries/indexeddbstorage.js +107 -0
- package/src/midiaudioplayer.js +1379 -51
- package/bin/cli.js +0 -27
- package/dist/midi-audio-player.js.map +0 -7
- package/dist/midi-audio-player.min.js.map +0 -7
- package/src/downloader.js +0 -33
- package/src/presets/defaultpreset.json +0 -116
- package/src/webaudiofontplayer.js +0 -264
package/dist/index.mjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
/*!
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
3
|
+
███╗ ███╗██╗██████╗ ██╗ █████╗ ██╗ ██╗██████╗ ██╗ ██████╗ ██████╗ ██╗ █████╗ ██╗ ██╗███████╗██████╗
|
|
4
|
+
████╗ ████║██║██╔══██╗██║██╔══██╗██║ ██║██╔══██╗██║██╔═══██╗██╔══██╗██║ ██╔══██╗╚██╗ ██╔╝██╔════╝██╔══██╗
|
|
5
|
+
██╔████╔██║██║██║ ██║██║███████║██║ ██║██║ ██║██║██║ ██║██████╔╝██║ ███████║ ╚████╔╝ █████╗ ██████╔╝
|
|
6
|
+
██║╚██╔╝██║██║██║ ██║██║██╔══██║██║ ██║██║ ██║██║██║ ██║██╔═══╝ ██║ ██╔══██║ ╚██╔╝ ██╔══╝ ██╔══██╗
|
|
7
|
+
██║ ╚═╝ ██║██║██████╔╝██║██║ ██║╚██████╔╝██████╔╝██║╚██████╔╝██║ ███████╗██║ ██║ ██║ ███████╗██║ ██║
|
|
8
|
+
╚═╝ ╚═╝╚═╝╚═════╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝
|
|
9
|
+
|
|
10
|
+
Version: 2.0.0
|
|
11
|
+
Build: 2026-05-29 17:16:44
|
|
12
|
+
Author: Maxime Larrivée-Roy <mlarriveeroy@gmail.com>
|
|
13
|
+
Github: https://github.com/webaudiofonts/midi-audio-player/
|
|
14
|
+
Website: https://webaudiofonts.github.io/midi-audio-player/
|
|
9
15
|
|
|
10
|
-
Version: 1.1.2
|
|
11
|
-
Généré: 2026-05-10 00:19:40
|
|
12
|
-
Auteur: Maxime Larrivée-Roy <mlarriveeroy@gmail.com>
|
|
13
|
-
Github: https://github.com/ZmotriN/midi-audio-player/
|
|
14
|
-
Website: https://zmotrin.github.io/midi-audio-player/
|
|
15
|
-
|
|
16
16
|
*/
|
|
17
|
-
function k(n,t){if(!(n instanceof t))throw new TypeError("Cannot call a class as a function")}function v(n,t){for(var V=0;V<t.length;V++){var q=t[V];q.enumerable=q.enumerable||!1,q.configurable=!0,"value"in q&&(q.writable=!0),Object.defineProperty(n,q.key,q)}}function b(n,t,V){return t&&v(n.prototype,t),V&&v(n,V),Object.defineProperty(n,"prototype",{writable:!1}),n}var c={VERSION:"2.0.17",NOTES:[],HEADER_CHUNK_LENGTH:14,CIRCLE_OF_FOURTHS:["C","F","Bb","Eb","Ab","Db","Gb","Cb","Fb","Bbb","Ebb","Abb"],CIRCLE_OF_FIFTHS:["C","G","D","A","E","B","F#","C#","G#","D#","A#","E#"]},E=[["C"],["C#","Db"],["D"],["D#","Eb"],["E"],["F"],["F#","Gb"],["G"],["G#","Ab"],["A"],["A#","Bb"],["B"]],M=0,w=function(t){E.forEach(function(V){V.forEach(function(q){return c.NOTES[M]=q+t}),M++})};for(T=-1;T<=9;T++)w(T);var T,r=(function(){function n(){k(this,n)}return b(n,null,[{key:"byteToHex",value:function(V){return("0"+V.toString(16)).slice(-2)}},{key:"bytesToHex",value:function(V){var q=[];return V.forEach(function(e){return q.push(n.byteToHex(e))}),q.join("")}},{key:"hexToNumber",value:function(V){return parseInt(V,16)}},{key:"bytesToNumber",value:function(V){return n.hexToNumber(n.bytesToHex(V))}},{key:"bytesToLetters",value:function(V){var q=[];return V.forEach(function(e){return q.push(String.fromCharCode(e))}),q.join("")}},{key:"decToBinary",value:function(V){return(V>>>0).toString(2)}},{key:"getVarIntLength",value:function(V){for(var q=V[0],e=1;q>=128;)q=V[e],e++;return e}},{key:"readVarInt",value:function(V){var q=0;return V.forEach(function(e){var a=e;a&128?(q+=a&127,q<<=7):q+=a}),q}},{key:"atob",value:(function(t){function V(q){return t.apply(this,arguments)}return V.toString=function(){return t.toString()},V})(function(t){return typeof atob=="function"?atob(t):Buffer.from(t,"base64").toString("binary")})}]),n})(),U=(function(){function n(t,V){k(this,n),this.enabled=!0,this.eventIndex=0,this.pointer=0,this.lastTick=0,this.lastStatus=null,this.index=t,this.data=V,this.delta=0,this.runningDelta=0,this.events=[];var q=this.data.subarray(this.data.length-3,this.data.length);if(!(q[0]===255&&q[1]===47&&q[2]===0))throw"Invalid MIDI file; Last three bytes of track "+this.index+"must be FF 2F 00 to mark end of track"}return b(n,[{key:"reset",value:function(){return this.enabled=!0,this.eventIndex=0,this.pointer=0,this.lastTick=0,this.lastStatus=null,this.delta=0,this.runningDelta=0,this}},{key:"enable",value:function(){return this.enabled=!0,this}},{key:"disable",value:function(){return this.enabled=!1,this}},{key:"setEventIndexByTick",value:function(V){V=V||0;for(var q=0;q<this.events.length;q++)if(this.events[q].tick>=V)return this.eventIndex=q,this}},{key:"getCurrentByte",value:function(){return this.data[this.pointer]}},{key:"getDeltaByteCount",value:function(){return r.getVarIntLength(this.data.subarray(this.pointer))}},{key:"getDelta",value:function(){return r.readVarInt(this.data.subarray(this.pointer,this.pointer+this.getDeltaByteCount()))}},{key:"handleEvent",value:function(V,q){if(q=q||!1,q){var e=V-this.lastTick,a=this.getDelta(),A=e>=a;if(this.pointer<this.data.length&&(q||A)){var i=this.parseEvent();if(this.enabled)return i}}else{for(var s=[];this.events[this.eventIndex]&&this.events[this.eventIndex].tick<=V;)this.enabled&&s.push(this.events[this.eventIndex]),this.eventIndex++;if(s.length>0)return s}return null}},{key:"getStringData",value:function(V){var q=r.getVarIntLength(this.data.subarray(V+2)),e=r.readVarInt(this.data.subarray(V+2,V+2+q)),a=r.bytesToLetters(this.data.subarray(V+2+q,V+2+q+e));return a}},{key:"parseEvent",value:function(){var V=this.pointer+this.getDeltaByteCount(),q={},e=this.getDeltaByteCount();if(q.track=this.index+1,q.delta=this.getDelta(),this.lastTick=this.lastTick+q.delta,this.runningDelta+=q.delta,q.tick=this.runningDelta,q.byteIndex=this.pointer,this.data[V]==255){switch(this.data[V+1]){case 0:q.name="Sequence Number";break;case 1:q.name="Text Event",q.string=this.getStringData(V);break;case 2:q.name="Copyright Notice";break;case 3:q.name="Sequence/Track Name",q.string=this.getStringData(V);break;case 4:q.name="Instrument Name",q.string=this.getStringData(V);break;case 5:q.name="Lyric",q.string=this.getStringData(V);break;case 6:q.name="Marker",q.string=this.getStringData(V);break;case 7:q.name="Cue Point",q.string=this.getStringData(V);break;case 9:q.name="Device Name",q.string=this.getStringData(V);break;case 32:q.name="MIDI Channel Prefix";break;case 33:q.name="MIDI Port",q.data=r.bytesToNumber([this.data[V+3]]);break;case 47:q.name="End of Track";break;case 81:q.name="Set Tempo",q.data=Math.round(6e7/r.bytesToNumber(this.data.subarray(V+3,V+6))),this.tempo=q.data;break;case 84:q.name="SMTPE Offset";break;case 88:q.name="Time Signature",q.data=this.data.subarray(V+3,V+7),q.timeSignature=""+q.data[0]+"/"+Math.pow(2,q.data[1]);break;case 89:q.name="Key Signature",q.data=this.data.subarray(V+3,V+5);var a=q.data[0]>127?q.data[0]-256:q.data[0];a>=0?q.keySignature=c.CIRCLE_OF_FIFTHS[a]:q.keySignature=c.CIRCLE_OF_FOURTHS[Math.abs(a)],q.data[1]==0?q.keySignature+=" Major":q.data[1]==1&&(q.keySignature+=" Minor");break;case 127:q.name="Sequencer-Specific Meta-event";break;default:q.name="Unknown: "+this.data[V+1].toString(16);break}var A=r.getVarIntLength(this.data.subarray(V+2)),i=r.readVarInt(this.data.subarray(V+2,V+2+A));this.pointer+=e+2+A+i}else if(this.data[V]===240){q.name="Sysex";var s=r.getVarIntLength(this.data.subarray(V+1)),h=r.readVarInt(this.data.subarray(V+1,V+1+s));q.data=this.data.subarray(V+1+s,V+1+s+h),this.pointer+=e+1+s+h}else if(this.data[V]===247){q.name="Sysex (escape)";var o=r.getVarIntLength(this.data.subarray(V+1)),u=r.readVarInt(this.data.subarray(V+1,V+1+o));q.data=this.data.subarray(V+1+o,V+1+o+u),this.pointer+=e+1+o+u}else if(this.data[V]<128)if(q.running=!0,q.noteNumber=this.data[V],q.noteName=c.NOTES[this.data[V]],q.velocity=this.data[V+1],this.lastStatus<=143)q.name="Note off",q.channel=this.lastStatus-128+1,this.pointer+=e+2;else if(this.lastStatus<=159)q.name="Note on",q.channel=this.lastStatus-144+1,this.pointer+=e+2;else if(this.lastStatus<=175)q.name="Polyphonic Key Pressure",q.channel=this.lastStatus-160+1,q.note=c.NOTES[this.data[V]],q.pressure=this.data[V+1],this.pointer+=e+2;else if(this.lastStatus<=191)q.name="Controller Change",q.channel=this.lastStatus-176+1,q.number=this.data[V],q.value=this.data[V+1],this.pointer+=e+2;else if(this.lastStatus<=207)q.name="Program Change",q.channel=this.lastStatus-192+1,q.value=this.data[V+1],this.pointer+=e+1;else if(this.lastStatus<=223)q.name="Channel Key Pressure",q.channel=this.lastStatus-208+1,this.pointer+=e+1;else if(this.lastStatus<=239)q.name="Pitch Bend",q.channel=this.lastStatus-224+1,q.value=(this.data[V+1]&127)<<7|this.data[V]&127,this.pointer+=e+2;else throw"Unknown event (running): ".concat(this.lastStatus);else if(this.lastStatus=this.data[V],this.data[V]<=143)q.name="Note off",q.channel=this.lastStatus-128+1,q.noteNumber=this.data[V+1],q.noteName=c.NOTES[this.data[V+1]],q.velocity=Math.round(this.data[V+2]/127*100),this.pointer+=e+3;else if(this.data[V]<=159)q.name="Note on",q.channel=this.lastStatus-144+1,q.noteNumber=this.data[V+1],q.noteName=c.NOTES[this.data[V+1]],q.velocity=Math.round(this.data[V+2]/127*100),this.pointer+=e+3;else if(this.data[V]<=175)q.name="Polyphonic Key Pressure",q.channel=this.lastStatus-160+1,q.note=c.NOTES[this.data[V+1]],q.pressure=this.data[V+2],this.pointer+=e+3;else if(this.data[V]<=191)q.name="Controller Change",q.channel=this.lastStatus-176+1,q.number=this.data[V+1],q.value=this.data[V+2],this.pointer+=e+3;else if(this.data[V]<=207)q.name="Program Change",q.channel=this.lastStatus-192+1,q.value=this.data[V+1],this.pointer+=e+2;else if(this.data[V]<=223)q.name="Channel Key Pressure",q.channel=this.lastStatus-208+1,this.pointer+=e+2;else if(this.data[V]<=239)q.name="Pitch Bend",q.channel=this.lastStatus-224+1,q.value=(this.data[V+2]&127)<<7|this.data[V+1]&127,this.pointer+=e+3;else throw"Unknown event: ".concat(this.data[V]);return this.delta+=q.delta,this.events.push(q),q}},{key:"endOfTrack",value:function(){return this.data[this.pointer+1]==255&&this.data[this.pointer+2]==47&&this.data[this.pointer+3]==0}}]),n})();Uint8Array.prototype.forEach||Object.defineProperty(Uint8Array.prototype,"forEach",{value:Array.prototype.forEach});var B=(function(){function n(t,V){k(this,n),this.sampleRate=5,this.startTime=0,this.buffer=V||null,this.midiChunksByteLength=null,this.division,this.format,this.setTimeoutId=!1,this.scheduledTime=0,this.tracks=[],this.instruments=[],this.defaultTempo=120,this.tempo=null,this.startTick=0,this.tick=0,this.lastTick=null,this.inLoop=!1,this.totalTicks=0,this.events=[],this.totalEvents=0,this.tempoMap=[],this.eventListeners={},typeof t=="function"&&this.on("midiEvent",t)}return b(n,[{key:"loadFile",value:function(V){throw"loadFile is only supported on Node.js"}},{key:"loadArrayBuffer",value:function(V){return this.buffer=new Uint8Array(V),this.fileLoaded()}},{key:"loadDataUri",value:function(V){for(var q=r.atob(V.split(",")[1]),e=new Uint8Array(q.length),a=0;a<q.length;a++)e[a]=q.charCodeAt(a);return this.buffer=e,this.fileLoaded()}},{key:"getFilesize",value:function(){return this.buffer?this.buffer.length:0}},{key:"fileLoaded",value:function(){if(!this.validate())throw"Invalid MIDI file; should start with MThd";return this.defaultTempo=120,this.setTempo(this.defaultTempo).getDivision().getFormat().getTracks().dryRun()}},{key:"validate",value:function(){return r.bytesToLetters(this.buffer.subarray(0,4))==="MThd"}},{key:"getFormat",value:function(){return this.format=r.bytesToNumber(this.buffer.subarray(8,10)),this}},{key:"getTracks",value:function(){this.tracks=[];for(var V=0;V<this.buffer.length;){if(r.bytesToLetters(this.buffer.subarray(V,V+4))=="MTrk"){var q=r.bytesToNumber(this.buffer.subarray(V+4,V+8));this.tracks.push(new U(this.tracks.length,this.buffer.subarray(V+8,V+8+q)))}V+=r.bytesToNumber(this.buffer.subarray(V+4,V+8))+8}var e=0;return this.tracks.forEach(function(a){e+=8+a.data.length}),this.midiChunksByteLength=c.HEADER_CHUNK_LENGTH+e,this}},{key:"enableTrack",value:function(V){return this.tracks[V-1].enable(),this}},{key:"disableTrack",value:function(V){return this.tracks[V-1].disable(),this}},{key:"getDivision",value:function(){return this.division=r.bytesToNumber(this.buffer.subarray(12,c.HEADER_CHUNK_LENGTH)),this}},{key:"playLoop",value:function(V){this.inLoop||(this.inLoop=!0,this.tick=this.getCurrentTick(),this.tracks.forEach(function(q,e){if(!V&&this.endOfFile())this.stop(),this.triggerPlayerEvent("endOfFile");else{var a=q.handleEvent(this.tick,V);if(V&&a)a.hasOwnProperty("name")&&a.name==="Set Tempo"&&this.setTempo(a.data),a.hasOwnProperty("name")&&a.name==="Program Change"&&(this.instruments.includes(a.value)||this.instruments.push(a.value));else if(a){var A=Array.isArray(a)?a:[a];A.forEach(function(i){i.hasOwnProperty("name")&&i.name==="Set Tempo"&&this.setTempo(i.data),this.emitEvent(i)},this)}}},this),!V&&this.isPlaying()&&this.triggerPlayerEvent("playing",{tick:this.tick}),this.inLoop=!1)}},{key:"setTempo",value:function(V){return this.tempo=V,this}},{key:"setStartTime",value:function(V){return this.startTime=V,this}},{key:"play",value:function(){if(this.isPlaying())throw"Already playing...";return this.startTime||(this.startTime=new Date().getTime()),this.scheduledTime=Date.now(),this.schedulePlayLoop(this.sampleRate),this}},{key:"schedulePlayLoop",value:function(V){var q=this;this.setTimeoutId=setTimeout(function(){if(q.playLoop(),q.setTimeoutId!==!1){q.scheduledTime+=q.sampleRate;var e=Date.now()-q.scheduledTime;q.schedulePlayLoop(Math.max(0,q.sampleRate-e))}},V)}},{key:"pause",value:function(){return clearTimeout(this.setTimeoutId),this.setTimeoutId=!1,this.scheduledTime=0,this.startTick=this.tick,this.startTime=0,this}},{key:"stop",value:function(){return clearTimeout(this.setTimeoutId),this.setTimeoutId=!1,this.scheduledTime=0,this.startTick=0,this.startTime=0,this.resetTracks(),this}},{key:"skipToTick",value:function(V){this.stop(),this.startTick=V;for(var q=this.tempoMap.length-1;q>=0;q--)if(this.tempoMap[q].tick<=V){this.setTempo(this.tempoMap[q].tempo);break}return this.collectStateAtTick(V).forEach(function(e){this.emitEvent(e)},this),this.tracks.forEach(function(e){e.setEventIndexByTick(V)}),this}},{key:"collectStateAtTick",value:function(V){var q={};return this.events.forEach(function(e){e.forEach(function(a){if(!(a.tick>=V)){var A;a.name==="Program Change"?A="pc:"+a.channel:a.name==="Controller Change"?A="cc:"+a.channel+":"+a.number:a.name==="Pitch Bend"&&(A="pb:"+a.channel),A&&(q[A]=a)}})}),Object.keys(q).map(function(e){return q[e]})}},{key:"skipToPercent",value:function(V){if(V<0||V>100)throw"Percent must be number between 1 and 100.";return this.skipToTick(Math.round(V/100*this.totalTicks)),this}},{key:"skipToSeconds",value:function(V){var q=this.getSongTime();if(V<0||V>q)throw V+" seconds not within song time of "+q;return this.skipToTick(this.secondsToTicks(V)),this}},{key:"isPlaying",value:function(){return this.setTimeoutId!==!1}},{key:"dryRun",value:function(){for(this.resetTracks();!this.endOfFile();)this.playLoop(!0);return this.events=this.getEvents(),this.totalEvents=this.getTotalEvents(),this.totalTicks=this.getTotalTicks(),this.buildTempoMap(),this.startTick=0,this.startTime=0,this.resetTracks(),this.triggerPlayerEvent("fileLoaded",this),this}},{key:"resetTracks",value:function(){return this.tracks.forEach(function(V){return V.reset()}),this}},{key:"getEvents",value:function(){return this.tracks.map(function(V){return V.events})}},{key:"getTotalTicks",value:function(){return Math.max.apply(null,this.tracks.map(function(V){return V.delta}))}},{key:"getTotalEvents",value:function(){return this.tracks.reduce(function(V,q){return{events:{length:V.events.length+q.events.length}}},{events:{length:0}}).events.length}},{key:"buildTempoMap",value:function(){var V=[];return this.events.forEach(function(q){q.forEach(function(e){e.name==="Set Tempo"&&V.push({tick:e.tick,tempo:e.data})})}),V.sort(function(q,e){return q.tick-e.tick}),this.tempoMap=[{tick:0,tempo:this.defaultTempo}],V.forEach(function(q){var e=this.tempoMap[this.tempoMap.length-1];q.tick===e.tick?e.tempo=q.tempo:this.tempoMap.push({tick:q.tick,tempo:q.tempo})},this),this}},{key:"ticksToSeconds",value:function(V,q){for(var e=0,a=V,A=0;A<this.tempoMap.length;A++){var i=this.tempoMap[A],s=A+1<this.tempoMap.length?this.tempoMap[A+1].tick:q;if(!(s<=V)){var h=Math.max(i.tick,V),o=Math.min(s,q);if(h>=q)break;var u=o-h;e+=u/this.division/i.tempo*60,a=o}}if(a<q){var d=this.tempoMap[this.tempoMap.length-1];e+=(q-a)/this.division/d.tempo*60}return e}},{key:"secondsToTicks",value:function(V){for(var q=V,e=0,a=0;a<this.tempoMap.length;a++){var A=this.tempoMap[a],i=a+1<this.tempoMap.length?this.tempoMap[a+1].tick:1/0,s=i-A.tick,h=s/this.division/A.tempo*60;if(q<=h)return e=A.tick+Math.round(q/60*A.tempo*this.division),e;q-=h,e=i}return this.totalTicks}},{key:"getSongTime",value:function(){return this.ticksToSeconds(0,this.totalTicks)}},{key:"getSongTimeRemaining",value:function(){return Math.round(this.ticksToSeconds(this.getCurrentTick(),this.totalTicks))}},{key:"getSongPercentRemaining",value:function(){return Math.round(this.getSongTimeRemaining()/this.getSongTime()*100)}},{key:"bytesProcessed",value:function(){return c.HEADER_CHUNK_LENGTH+this.tracks.length*8+this.tracks.reduce(function(V,q){return{pointer:V.pointer+q.pointer}},{pointer:0}).pointer}},{key:"eventsPlayed",value:function(){return this.tracks.reduce(function(V,q){return{eventIndex:V.eventIndex+q.eventIndex}},{eventIndex:0}).eventIndex}},{key:"endOfFile",value:function(){return this.isPlaying()?this.totalTicks-this.tick<=0:this.bytesProcessed()>=this.midiChunksByteLength}},{key:"getCurrentTick",value:function(){if(!this.startTime)return this.startTick;var V=(new Date().getTime()-this.startTime)/1e3,q=this.ticksToSeconds(0,this.startTick);return this.secondsToTicks(q+V)}},{key:"emitEvent",value:function(V){return this.triggerPlayerEvent("midiEvent",V),this}},{key:"on",value:function(V,q){return this.eventListeners.hasOwnProperty(V)||(this.eventListeners[V]=[]),this.eventListeners[V].push(q),this}},{key:"triggerPlayerEvent",value:function(V,q){return this.eventListeners.hasOwnProperty(V)&&this.eventListeners[V].forEach(function(e){return e(q||{})}),this}}]),n})(),S={Player:B,Utils:r,Constants:c};var p=class{#V=null;#e=null;#q=[];#t=.05;#i=1e-6;constructor(t,V){this.#V=t,this.#e=V,this.#e.zones.map(q=>this.#r(q))}queueWaveTable(t,V,q,e,a){this.#V.state==="suspended"&&this.#V.resume().catch(()=>{});let A=this.#o(e),i=this.#u(V);if(!i?.buffer)return null;let s=i.originalPitch-100*i.coarseTune-i.fineTune,h=Math.pow(2,(100*V-s)/1200),o=Math.max(t,this.#V.currentTime),u=q+this.#t,d=i.loopStart>=1&&i.loopStart<i.loopEnd;d||(u=Math.min(u,i.buffer.duration/h));let f=this.#h();this.#s(f,i,A,o,u,q);let l=this.#V.createBufferSource();if(l.buffer=i.buffer,l.playbackRate.setValueAtTime(h,0),a?.length>0&&(l.playbackRate.setValueAtTime(h,o),a.forEach(m=>{let y=Math.pow(2,(100*(V+m.delta)-s)/1200);l.playbackRate.linearRampToValueAtTime(y,o+m.when)})),l.loop=d,d){let m=i.delay??0;l.loopStart=i.loopStart/i.sampleRate+m,l.loopEnd=i.loopEnd/i.sampleRate+m}return l.connect(f),l.start(o,i.delay??0),l.stop(o+u),f.audioBufferSourceNode=l,f.when=o,f.duration=u,f}queueChord(t,V,q,e,a,A){let i=this.#o(a);return q.map((s,h)=>this.queueWaveTable(this.#V,this.#V.destination,t,V,s,e,i-Math.random()*.01,A?.[h])).filter(Boolean)}async cancelQueue(){this.#q.forEach(t=>{t.gain.cancelScheduledValues(0),t.gain.setValueAtTime(this.#i,this.#V.currentTime),t.when=-1;try{t.audioBufferSourceNode?.disconnect()}catch{}})}#r(t){if(t.buffer)return Promise.resolve(t);if(t.delay=0,t.sample){let V=atob(t.sample),q=V.length,e=new Uint8Array(q);for(let s=0;s<q;s++)e[s]=V.charCodeAt(s);let a=new Int16Array(e.buffer),A=a.length;t.buffer=this.#V.createBuffer(1,A,t.sampleRate);let i=t.buffer.getChannelData(0);for(let s=0;s<A;s++)i[s]=a[s]/32768;return this.#a(t),t}else if(t.file){let V=atob(t.file),q=new Uint8Array(V.length);for(let e=0;e<V.length;e++)q[e]=V.charCodeAt(e);this.#V.decodeAudioData(q.buffer,e=>(t.buffer=e,this.#a(t),t),e=>(console.error("Audio decoding error:",e),!1))}else return this.#a(t),t}#a(t){t.loopStart=this.#A(t.loopStart,0),t.loopEnd=this.#A(t.loopEnd,0),t.coarseTune=this.#A(t.coarseTune,0),t.fineTune=this.#A(t.fineTune,0),t.originalPitch=this.#A(t.originalPitch,6e3),t.sampleRate=this.#A(t.sampleRate,44100)}#s(t,V,q,e,a,A){t.gain.setValueAtTime(this.#n(0),this.#V.currentTime);let i=Math.min(A,a-this.#t),s=V.ahdsr&&V.ahdsr.length>0?V.ahdsr:[{duration:0,volume:1},{duration:i,volume:1}];t.gain.cancelScheduledValues(e);let h=(s[0]?.volume??1)*q;t.gain.setValueAtTime(this.#n(h),e);let o=0,u=s[0]?.volume??1;for(let d of s){let{duration:f,volume:l}=d;if(f<=0)continue;let m=i-o;if(f>m){let y=m/f,C=u+y*(l-u);t.gain.linearRampToValueAtTime(this.#n(q*C),e+i);break}o+=f,u=l,t.gain.linearRampToValueAtTime(this.#n(q*u),e+o)}t.gain.linearRampToValueAtTime(this.#n(0),e+i+this.#t)}#h(){let t=this.#q.find(V=>V.target===this.#V.destination&&this.#V.currentTime>V.when+V.duration+.001);if(t){if(t.audioBufferSourceNode){try{t.audioBufferSourceNode.stop(0),t.audioBufferSourceNode.disconnect()}catch{}t.audioBufferSourceNode=null}}else t=this.#V.createGain(),t.gain.value=0,t.target=this.#V.destination,t.connect(this.#V.destination),t.cancel=()=>{t.when+t.duration>this.#V.currentTime&&(t.gain.cancelScheduledValues(0),t.gain.setTargetAtTime(this.#i,this.#V.currentTime,.1),t.when=this.#V.currentTime+1e-5,t.duration=0)},this.#q.push(t);return t}#u(t){let V=this.#e.zones.findLast(q=>t>=q.keyRangeLow&&t<=q.keyRangeHigh+1);return V&&this.#r(V),V}#o(t){let V=t?1*t:.5;return Math.min(V,.8)}#n(t){return t>this.#i?t:this.#i}#A(t,V){return typeof t=="number"?t:V}};var x={zones:[{midi:81,originalPitch:4200,keyRangeLow:0,keyRangeHigh:43,loopStart:256,loopEnd:768,coarseTune:0,fineTune:0,sampleRate:48e3,ahdsr:!1,file:"SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU3LjcyLjEwMQAAAAAAAAAAAAAA//tUwAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAAACAAAGAACgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCg//////////////////////////////////////////////////////////////////8AAAAATGF2YzU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qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq//tkxMWDzQgxS7zzACgAADSAAAAEqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq",anchor:.00266667},{midi:81,originalPitch:6600,keyRangeLow:56,keyRangeHigh:67,loopStart:64,loopEnd:192,coarseTune:0,fineTune:0,sampleRate:48e3,ahdsr:!1,file:"SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU3LjcyLjEwMQAAAAAAAAAAAAAA//tUwAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAAACAAAE4ADs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs//////////////////////////////////////////////////////////////////8AAAAATGF2YzU3Ljk2AAAAAAAAAAAAAAAAJAXAAAAAAAAABODQyktQAAAAAAAAAAAAAAAAAAAA//vkxAAABywBgbQAACYVyC6/P9AwKAASUcckkt4YWD4fLn1AhBCJz5c+oEFghy5/ghy5+cghy7+GKZd/DHLn1HIYk5d/DHL+6H5d5TOdLnbLTLKrBqyq+vlkqeD4lCzTAngBgvMYACAAGg+NZZoFwogYAGAZCwCsDgBJsJhRJLyYvYUvg4BLFAA9AKpqYxQCumE3hMhEBIkBkBLuNR5oOGzUbs0Jk7jR1yTFgpzGY2TMgWV8qtT4fmaf4xDKgxlNgzTGRZScSFbPVQxarGZb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VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",anchor:.00133333},{midi:81,originalPitch:7800,keyRangeLow:68,keyRangeHigh:79,loopStart:32,loopEnd:96,coarseTune:0,fineTune:0,sampleRate:48e3,ahdsr:!1,file:"SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU3LjcyLjEwMQAAAAAAAAAAAAAA//tUwAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAAACAAADwADm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm//////////////////////////////////////////////////////////////////8AAAAATGF2YzU3Ljk2AAAAAAAAAAAAAAAAJAZAAAAAAAAAA8CsVDBMAAAAAAAAAAAAAAAAAAAA//vExAAABmQBjaAAACGQBa9497AdtbAkWdckklxRyjhQ5BBYYqOFHRAXDHKHOGOUOcMco7nOJHawxynnOU5cMcHOXOcHOl3NXGMqsiEAqoMI8QsSUcIsgeiQgJISFCg5ABAyw+VQaiK8yY18FNiuxBUorwU0FdiC4ivimgrsQXEV4KaCuxBcTfBXAv4isTfiuBf6KxN+L4r8RUU3wXoL+JsU3wXoL+JsV3gvRSpMQU1FMy45OS41qqqqqqqqqqqqqqqqqqqqqqqq6goZoAABEOiCXDs8P3G8oicJAhZjVVVBlsStNFVVUT8StNVMQU1FMy45OS41VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//sUxOuDxEQnByYExigAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",anchor:66667e-8},{midi:81,originalPitch:9e3,keyRangeLow:80,keyRangeHigh:91,loopStart:16,loopEnd:48,coarseTune:0,fineTune:0,sampleRate:48e3,ahdsr:!1,file:"SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU3LjcyLjEwMQAAAAAAAAAAAAAA//tUwAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAAACAAADwADm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm//////////////////////////////////////////////////////////////////8AAAAATGF2YzU3Ljk2AAAAAAAAAAAAAAAAJAaAAAAAAAAAA8ChXkahAAAAAAAAAAAAAAAAAAAA//vExAAABkQDh+AAACGUhq9895iZZVlzMgFEYk0nBACCLQfD6gTB8/qBDBwMflC4f/gQMfqBMH/4OHP4Df+XBw5+UBN/6wJu1fapqZhlttyF2FyUYQ0W0QkFSJiRIro4TAYk8aQCAQCAKjiRIkSr+xQUFOBQUV/5BQU4KChv+CgoL4KCu/4QUN8KCn/8UFN8FFf/wgp/hQ3/8FBXYgoL/+FBX5BQ3/8FBfigopVMQU1FMy45OS41VVVVVVVVVVVVVVVVVVVVV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VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",anchor:16667e-8},{midi:81,originalPitch:11400,keyRangeLow:104,keyRangeHigh:115,loopStart:12,loopEnd:52,coarseTune:0,fineTune:0,sampleRate:48e3,ahdsr:!1,file:"SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU3LjcyLjEwMQAAAAAAAAAAAAAA//tUwAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAAACAAADwADm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm//////////////////////////////////////////////////////////////////8AAAAATGF2YzU3Ljk2AAAAAAAAAAAAAAAAJAaAAAAAAAAAA8CNr1v4AAAAAAAAAAAAAAAAAAAA//vExAAAB1SVheCEbeI4SC349ApomIy4jYiPtA6x5AACs4xjvkAAPmMY/wAXzGMf4AL/X+IgG4PvwQOfIQQOZcH//wQlwfBA5/1h/iB2sP/17/1GMvIAEJ8BiUYMEW0NSAKQjJWj5HCbB/EGHqQ5m2plUuYL1WvVqeGZmb/VVVf9mZr/1VVX9hYGwKgFgbB9TCwNgbB8BG6lKUreYxjfKUrfQxvylK3oYxjeUKAgICJYoCAgICUvoYxvylL9DGN9SlL9P+UrfMYxjOoYCAgIUb6lL////////qUpSzASTEFNRTMuOTkuNaqqqqpMQU1FMy45OS41qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq//sUxNoDwAAB/gAAACAAADSAAAAEqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq",anchor:8333e-8},{midi:81,originalPitch:12600,keyRangeLow:116,keyRangeHigh:127,loopStart:6,loopEnd:42,coarseTune:0,fineTune:0,sampleRate:48e3,ahdsr:!1,file:"SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU3LjcyLjEwMQAAAAAAAAAAAAAA//tUwAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAAACAAAEIADo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo//////////////////////////////////////////////////////////////////8AAAAATGF2YzU3Ljk2AAAAAAAAAAAAAAAAJAaQAAAAAAAABCDWHfeqAAAAAAAAAAAAAAAAAAAA//vUxAAACUUrfeCE1eMLSCx88a54l3jMh4t/trUApEAAAUAGYxja+WMYx/yAAH+MY/+AYx/4AAX8xjH/7/8AF//zHyAMdoIAgAAADAYWTt4IA/Kc5/////////y4Pg/v3FZropQkAAAEiDVBBhkjdBSk5JyDlHqDmWi+kJRsJiOZ69eva6x+zAQEBCm/9VVVb/9mVVL/9mZmP/6qqqn/8ZlVV/6zMzM3/VCgICanXX+5I2JRJHaana+SSNwIQEQAwAQAQEw6j5KBCASACACAKAmBGHcdr5RNR2jtJRsed/DkTU1NTra/3Oc5znf+1rWuc7/3Na1ra/9znOc7/9rWtc7/9zWta3/4c5znO/9rTU1NXOvbW4lDtDyHkPI7TqQIQAxMQU1FMy45OS41qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpMQU1FMy45OS41qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq//sUxNoDwAABpAAAACAAADSAAAAEqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq",anchor:4167e-8}]};var g=class extends S.Player{#V=null;#e=null;#q=null;#t={preset:x,volume:.012,onEndFile:null};constructor(t={}){super(V=>this.#r(V)),this.#t={...this.#t,...t},this.#q=new Map,this.#V=new(window.AudioContext||window.webkitAudioContext),this.#e=new p(this.#V,this.#t.preset),this.on("endOfFile",async()=>{await new Promise(V=>requestAnimationFrame(()=>setTimeout(V,1))),await this.#i()})}async load(t){this.isPlaying()&&this.stop(),this.#s(),await this.loadArrayBuffer(t)}async play(t=null){t&&await this.load(t),await this.#V.resume(),await super.play()}async pause(){await super.pause(),await this.#s(),await this.#e.cancelQueue()}async stop(){await super.stop(),await this.#s(),await this.#e.cancelQueue()}async#i(){typeof this.#t.onEndFile=="function"&&await this.#t.onEndFile()}async#r(t){if(t.name!=="Note on"&&t.name!=="Note off"||!this.isPlaying()||t.noteNumber===void 0)return;let V=this.#V.currentTime;switch(t.name){case"Note on":if(t.velocity>0&&t.velocity<=127){this.#a(t.noteNumber);let q=t.velocity/127*this.#t.volume,e=this.#e.queueWaveTable(0,t.noteNumber,2,q);this.#q.set(t.noteNumber,e)}else this.#a(t.noteNumber);break;case"Note off":this.#a(t.noteNumber);break}}#a(t){let V=this.#q.get(t);V&&(V.cancel(),this.#q.delete(t))}#s(){this.#q&&(this.#q.forEach((t,V)=>{t&&t.cancel&&t.cancel()}),this.#q.clear())}};typeof window<"u"&&(window.MidiAudioPlayer=g);var Q=g;export{g as MidiAudioPlayer,Q as default};
|
|
17
|
+
function B(r,s){if(!(r instanceof s))throw new TypeError("Cannot call a class as a function")}function j(r,s){for(var t=0;t<s.length;t++){var e=s[t];e.enumerable=e.enumerable||!1,e.configurable=!0,"value"in e&&(e.writable=!0),Object.defineProperty(r,e.key,e)}}function V(r,s,t){return s&&j(r.prototype,s),t&&j(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}var A={VERSION:"2.0.17",NOTES:[],HEADER_CHUNK_LENGTH:14,CIRCLE_OF_FOURTHS:["C","F","Bb","Eb","Ab","Db","Gb","Cb","Fb","Bbb","Ebb","Abb"],CIRCLE_OF_FIFTHS:["C","G","D","A","E","B","F#","C#","G#","D#","A#","E#"]},q=[["C"],["C#","Db"],["D"],["D#","Eb"],["E"],["F"],["F#","Gb"],["G"],["G#","Ab"],["A"],["A#","Bb"],["B"]],H=0,W=function(s){q.forEach(function(t){t.forEach(function(e){return A.NOTES[H]=e+s}),H++})};for(R=-1;R<=9;R++)W(R);var R,w=(function(){function r(){B(this,r)}return V(r,null,[{key:"byteToHex",value:function(t){return("0"+t.toString(16)).slice(-2)}},{key:"bytesToHex",value:function(t){var e=[];return t.forEach(function(i){return e.push(r.byteToHex(i))}),e.join("")}},{key:"hexToNumber",value:function(t){return parseInt(t,16)}},{key:"bytesToNumber",value:function(t){return r.hexToNumber(r.bytesToHex(t))}},{key:"bytesToLetters",value:function(t){var e=[];return t.forEach(function(i){return e.push(String.fromCharCode(i))}),e.join("")}},{key:"decToBinary",value:function(t){return(t>>>0).toString(2)}},{key:"getVarIntLength",value:function(t){for(var e=t[0],i=1;e>=128;)e=t[i],i++;return i}},{key:"readVarInt",value:function(t){var e=0;return t.forEach(function(i){var a=i;a&128?(e+=a&127,e<<=7):e+=a}),e}},{key:"atob",value:(function(s){function t(e){return s.apply(this,arguments)}return t.toString=function(){return s.toString()},t})(function(s){return typeof atob=="function"?atob(s):Buffer.from(s,"base64").toString("binary")})}]),r})(),G=(function(){function r(s,t){B(this,r),this.enabled=!0,this.eventIndex=0,this.pointer=0,this.lastTick=0,this.lastStatus=null,this.index=s,this.data=t,this.delta=0,this.runningDelta=0,this.events=[];var e=this.data.subarray(this.data.length-3,this.data.length);if(!(e[0]===255&&e[1]===47&&e[2]===0))throw"Invalid MIDI file; Last three bytes of track "+this.index+"must be FF 2F 00 to mark end of track"}return V(r,[{key:"reset",value:function(){return this.enabled=!0,this.eventIndex=0,this.pointer=0,this.lastTick=0,this.lastStatus=null,this.delta=0,this.runningDelta=0,this}},{key:"enable",value:function(){return this.enabled=!0,this}},{key:"disable",value:function(){return this.enabled=!1,this}},{key:"setEventIndexByTick",value:function(t){t=t||0;for(var e=0;e<this.events.length;e++)if(this.events[e].tick>=t)return this.eventIndex=e,this}},{key:"getCurrentByte",value:function(){return this.data[this.pointer]}},{key:"getDeltaByteCount",value:function(){return w.getVarIntLength(this.data.subarray(this.pointer))}},{key:"getDelta",value:function(){return w.readVarInt(this.data.subarray(this.pointer,this.pointer+this.getDeltaByteCount()))}},{key:"handleEvent",value:function(t,e){if(e=e||!1,e){var i=t-this.lastTick,a=this.getDelta(),n=i>=a;if(this.pointer<this.data.length&&(e||n)){var o=this.parseEvent();if(this.enabled)return o}}else{for(var h=[];this.events[this.eventIndex]&&this.events[this.eventIndex].tick<=t;)this.enabled&&h.push(this.events[this.eventIndex]),this.eventIndex++;if(h.length>0)return h}return null}},{key:"getStringData",value:function(t){var e=w.getVarIntLength(this.data.subarray(t+2)),i=w.readVarInt(this.data.subarray(t+2,t+2+e)),a=w.bytesToLetters(this.data.subarray(t+2+e,t+2+e+i));return a}},{key:"parseEvent",value:function(){var t=this.pointer+this.getDeltaByteCount(),e={},i=this.getDeltaByteCount();if(e.track=this.index+1,e.delta=this.getDelta(),this.lastTick=this.lastTick+e.delta,this.runningDelta+=e.delta,e.tick=this.runningDelta,e.byteIndex=this.pointer,this.data[t]==255){switch(this.data[t+1]){case 0:e.name="Sequence Number";break;case 1:e.name="Text Event",e.string=this.getStringData(t);break;case 2:e.name="Copyright Notice";break;case 3:e.name="Sequence/Track Name",e.string=this.getStringData(t);break;case 4:e.name="Instrument Name",e.string=this.getStringData(t);break;case 5:e.name="Lyric",e.string=this.getStringData(t);break;case 6:e.name="Marker",e.string=this.getStringData(t);break;case 7:e.name="Cue Point",e.string=this.getStringData(t);break;case 9:e.name="Device Name",e.string=this.getStringData(t);break;case 32:e.name="MIDI Channel Prefix";break;case 33:e.name="MIDI Port",e.data=w.bytesToNumber([this.data[t+3]]);break;case 47:e.name="End of Track";break;case 81:e.name="Set Tempo",e.data=Math.round(6e7/w.bytesToNumber(this.data.subarray(t+3,t+6))),this.tempo=e.data;break;case 84:e.name="SMTPE Offset";break;case 88:e.name="Time Signature",e.data=this.data.subarray(t+3,t+7),e.timeSignature=""+e.data[0]+"/"+Math.pow(2,e.data[1]);break;case 89:e.name="Key Signature",e.data=this.data.subarray(t+3,t+5);var a=e.data[0]>127?e.data[0]-256:e.data[0];a>=0?e.keySignature=A.CIRCLE_OF_FIFTHS[a]:e.keySignature=A.CIRCLE_OF_FOURTHS[Math.abs(a)],e.data[1]==0?e.keySignature+=" Major":e.data[1]==1&&(e.keySignature+=" Minor");break;case 127:e.name="Sequencer-Specific Meta-event";break;default:e.name="Unknown: "+this.data[t+1].toString(16);break}var n=w.getVarIntLength(this.data.subarray(t+2)),o=w.readVarInt(this.data.subarray(t+2,t+2+n));this.pointer+=i+2+n+o}else if(this.data[t]===240){e.name="Sysex";var h=w.getVarIntLength(this.data.subarray(t+1)),l=w.readVarInt(this.data.subarray(t+1,t+1+h));e.data=this.data.subarray(t+1+h,t+1+h+l),this.pointer+=i+1+h+l}else if(this.data[t]===247){e.name="Sysex (escape)";var c=w.getVarIntLength(this.data.subarray(t+1)),u=w.readVarInt(this.data.subarray(t+1,t+1+c));e.data=this.data.subarray(t+1+c,t+1+c+u),this.pointer+=i+1+c+u}else if(this.data[t]<128)if(e.running=!0,e.noteNumber=this.data[t],e.noteName=A.NOTES[this.data[t]],e.velocity=this.data[t+1],this.lastStatus<=143)e.name="Note off",e.channel=this.lastStatus-128+1,this.pointer+=i+2;else if(this.lastStatus<=159)e.name="Note on",e.channel=this.lastStatus-144+1,this.pointer+=i+2;else if(this.lastStatus<=175)e.name="Polyphonic Key Pressure",e.channel=this.lastStatus-160+1,e.note=A.NOTES[this.data[t]],e.pressure=this.data[t+1],this.pointer+=i+2;else if(this.lastStatus<=191)e.name="Controller Change",e.channel=this.lastStatus-176+1,e.number=this.data[t],e.value=this.data[t+1],this.pointer+=i+2;else if(this.lastStatus<=207)e.name="Program Change",e.channel=this.lastStatus-192+1,e.value=this.data[t+1],this.pointer+=i+1;else if(this.lastStatus<=223)e.name="Channel Key Pressure",e.channel=this.lastStatus-208+1,this.pointer+=i+1;else if(this.lastStatus<=239)e.name="Pitch Bend",e.channel=this.lastStatus-224+1,e.value=(this.data[t+1]&127)<<7|this.data[t]&127,this.pointer+=i+2;else throw"Unknown event (running): ".concat(this.lastStatus);else if(this.lastStatus=this.data[t],this.data[t]<=143)e.name="Note off",e.channel=this.lastStatus-128+1,e.noteNumber=this.data[t+1],e.noteName=A.NOTES[this.data[t+1]],e.velocity=Math.round(this.data[t+2]/127*100),this.pointer+=i+3;else if(this.data[t]<=159)e.name="Note on",e.channel=this.lastStatus-144+1,e.noteNumber=this.data[t+1],e.noteName=A.NOTES[this.data[t+1]],e.velocity=Math.round(this.data[t+2]/127*100),this.pointer+=i+3;else if(this.data[t]<=175)e.name="Polyphonic Key Pressure",e.channel=this.lastStatus-160+1,e.note=A.NOTES[this.data[t+1]],e.pressure=this.data[t+2],this.pointer+=i+3;else if(this.data[t]<=191)e.name="Controller Change",e.channel=this.lastStatus-176+1,e.number=this.data[t+1],e.value=this.data[t+2],this.pointer+=i+3;else if(this.data[t]<=207)e.name="Program Change",e.channel=this.lastStatus-192+1,e.value=this.data[t+1],this.pointer+=i+2;else if(this.data[t]<=223)e.name="Channel Key Pressure",e.channel=this.lastStatus-208+1,this.pointer+=i+2;else if(this.data[t]<=239)e.name="Pitch Bend",e.channel=this.lastStatus-224+1,e.value=(this.data[t+2]&127)<<7|this.data[t+1]&127,this.pointer+=i+3;else throw"Unknown event: ".concat(this.data[t]);return this.delta+=e.delta,this.events.push(e),e}},{key:"endOfTrack",value:function(){return this.data[this.pointer+1]==255&&this.data[this.pointer+2]==47&&this.data[this.pointer+3]==0}}]),r})();Uint8Array.prototype.forEach||Object.defineProperty(Uint8Array.prototype,"forEach",{value:Array.prototype.forEach});var Q=(function(){function r(s,t){B(this,r),this.sampleRate=5,this.startTime=0,this.buffer=t||null,this.midiChunksByteLength=null,this.division,this.format,this.setTimeoutId=!1,this.scheduledTime=0,this.tracks=[],this.instruments=[],this.defaultTempo=120,this.tempo=null,this.startTick=0,this.tick=0,this.lastTick=null,this.inLoop=!1,this.totalTicks=0,this.events=[],this.totalEvents=0,this.tempoMap=[],this.eventListeners={},typeof s=="function"&&this.on("midiEvent",s)}return V(r,[{key:"loadFile",value:function(t){throw"loadFile is only supported on Node.js"}},{key:"loadArrayBuffer",value:function(t){return this.buffer=new Uint8Array(t),this.fileLoaded()}},{key:"loadDataUri",value:function(t){for(var e=w.atob(t.split(",")[1]),i=new Uint8Array(e.length),a=0;a<e.length;a++)i[a]=e.charCodeAt(a);return this.buffer=i,this.fileLoaded()}},{key:"getFilesize",value:function(){return this.buffer?this.buffer.length:0}},{key:"fileLoaded",value:function(){if(!this.validate())throw"Invalid MIDI file; should start with MThd";return this.defaultTempo=120,this.setTempo(this.defaultTempo).getDivision().getFormat().getTracks().dryRun()}},{key:"validate",value:function(){return w.bytesToLetters(this.buffer.subarray(0,4))==="MThd"}},{key:"getFormat",value:function(){return this.format=w.bytesToNumber(this.buffer.subarray(8,10)),this}},{key:"getTracks",value:function(){this.tracks=[];for(var t=0;t<this.buffer.length;){if(w.bytesToLetters(this.buffer.subarray(t,t+4))=="MTrk"){var e=w.bytesToNumber(this.buffer.subarray(t+4,t+8));this.tracks.push(new G(this.tracks.length,this.buffer.subarray(t+8,t+8+e)))}t+=w.bytesToNumber(this.buffer.subarray(t+4,t+8))+8}var i=0;return this.tracks.forEach(function(a){i+=8+a.data.length}),this.midiChunksByteLength=A.HEADER_CHUNK_LENGTH+i,this}},{key:"enableTrack",value:function(t){return this.tracks[t-1].enable(),this}},{key:"disableTrack",value:function(t){return this.tracks[t-1].disable(),this}},{key:"getDivision",value:function(){return this.division=w.bytesToNumber(this.buffer.subarray(12,A.HEADER_CHUNK_LENGTH)),this}},{key:"playLoop",value:function(t){this.inLoop||(this.inLoop=!0,this.tick=this.getCurrentTick(),this.tracks.forEach(function(e,i){if(!t&&this.endOfFile())this.stop(),this.triggerPlayerEvent("endOfFile");else{var a=e.handleEvent(this.tick,t);if(t&&a)a.hasOwnProperty("name")&&a.name==="Set Tempo"&&this.setTempo(a.data),a.hasOwnProperty("name")&&a.name==="Program Change"&&(this.instruments.includes(a.value)||this.instruments.push(a.value));else if(a){var n=Array.isArray(a)?a:[a];n.forEach(function(o){o.hasOwnProperty("name")&&o.name==="Set Tempo"&&this.setTempo(o.data),this.emitEvent(o)},this)}}},this),!t&&this.isPlaying()&&this.triggerPlayerEvent("playing",{tick:this.tick}),this.inLoop=!1)}},{key:"setTempo",value:function(t){return this.tempo=t,this}},{key:"setStartTime",value:function(t){return this.startTime=t,this}},{key:"play",value:function(){if(this.isPlaying())throw"Already playing...";return this.startTime||(this.startTime=new Date().getTime()),this.scheduledTime=Date.now(),this.schedulePlayLoop(this.sampleRate),this}},{key:"schedulePlayLoop",value:function(t){var e=this;this.setTimeoutId=setTimeout(function(){if(e.playLoop(),e.setTimeoutId!==!1){e.scheduledTime+=e.sampleRate;var i=Date.now()-e.scheduledTime;e.schedulePlayLoop(Math.max(0,e.sampleRate-i))}},t)}},{key:"pause",value:function(){return clearTimeout(this.setTimeoutId),this.setTimeoutId=!1,this.scheduledTime=0,this.startTick=this.tick,this.startTime=0,this}},{key:"stop",value:function(){return clearTimeout(this.setTimeoutId),this.setTimeoutId=!1,this.scheduledTime=0,this.startTick=0,this.startTime=0,this.resetTracks(),this}},{key:"skipToTick",value:function(t){this.stop(),this.startTick=t;for(var e=this.tempoMap.length-1;e>=0;e--)if(this.tempoMap[e].tick<=t){this.setTempo(this.tempoMap[e].tempo);break}return this.collectStateAtTick(t).forEach(function(i){this.emitEvent(i)},this),this.tracks.forEach(function(i){i.setEventIndexByTick(t)}),this}},{key:"collectStateAtTick",value:function(t){var e={};return this.events.forEach(function(i){i.forEach(function(a){if(!(a.tick>=t)){var n;a.name==="Program Change"?n="pc:"+a.channel:a.name==="Controller Change"?n="cc:"+a.channel+":"+a.number:a.name==="Pitch Bend"&&(n="pb:"+a.channel),n&&(e[n]=a)}})}),Object.keys(e).map(function(i){return e[i]})}},{key:"skipToPercent",value:function(t){if(t<0||t>100)throw"Percent must be number between 1 and 100.";return this.skipToTick(Math.round(t/100*this.totalTicks)),this}},{key:"skipToSeconds",value:function(t){var e=this.getSongTime();if(t<0||t>e)throw t+" seconds not within song time of "+e;return this.skipToTick(this.secondsToTicks(t)),this}},{key:"isPlaying",value:function(){return this.setTimeoutId!==!1}},{key:"dryRun",value:function(){for(this.resetTracks();!this.endOfFile();)this.playLoop(!0);return this.events=this.getEvents(),this.totalEvents=this.getTotalEvents(),this.totalTicks=this.getTotalTicks(),this.buildTempoMap(),this.startTick=0,this.startTime=0,this.resetTracks(),this.triggerPlayerEvent("fileLoaded",this),this}},{key:"resetTracks",value:function(){return this.tracks.forEach(function(t){return t.reset()}),this}},{key:"getEvents",value:function(){return this.tracks.map(function(t){return t.events})}},{key:"getTotalTicks",value:function(){return Math.max.apply(null,this.tracks.map(function(t){return t.delta}))}},{key:"getTotalEvents",value:function(){return this.tracks.reduce(function(t,e){return{events:{length:t.events.length+e.events.length}}},{events:{length:0}}).events.length}},{key:"buildTempoMap",value:function(){var t=[];return this.events.forEach(function(e){e.forEach(function(i){i.name==="Set Tempo"&&t.push({tick:i.tick,tempo:i.data})})}),t.sort(function(e,i){return e.tick-i.tick}),this.tempoMap=[{tick:0,tempo:this.defaultTempo}],t.forEach(function(e){var i=this.tempoMap[this.tempoMap.length-1];e.tick===i.tick?i.tempo=e.tempo:this.tempoMap.push({tick:e.tick,tempo:e.tempo})},this),this}},{key:"ticksToSeconds",value:function(t,e){for(var i=0,a=t,n=0;n<this.tempoMap.length;n++){var o=this.tempoMap[n],h=n+1<this.tempoMap.length?this.tempoMap[n+1].tick:e;if(!(h<=t)){var l=Math.max(o.tick,t),c=Math.min(h,e);if(l>=e)break;var u=c-l;i+=u/this.division/o.tempo*60,a=c}}if(a<e){var m=this.tempoMap[this.tempoMap.length-1];i+=(e-a)/this.division/m.tempo*60}return i}},{key:"secondsToTicks",value:function(t){for(var e=t,i=0,a=0;a<this.tempoMap.length;a++){var n=this.tempoMap[a],o=a+1<this.tempoMap.length?this.tempoMap[a+1].tick:1/0,h=o-n.tick,l=h/this.division/n.tempo*60;if(e<=l)return i=n.tick+Math.round(e/60*n.tempo*this.division),i;e-=l,i=o}return this.totalTicks}},{key:"getSongTime",value:function(){return this.ticksToSeconds(0,this.totalTicks)}},{key:"getSongTimeRemaining",value:function(){return Math.round(this.ticksToSeconds(this.getCurrentTick(),this.totalTicks))}},{key:"getSongPercentRemaining",value:function(){return Math.round(this.getSongTimeRemaining()/this.getSongTime()*100)}},{key:"bytesProcessed",value:function(){return A.HEADER_CHUNK_LENGTH+this.tracks.length*8+this.tracks.reduce(function(t,e){return{pointer:t.pointer+e.pointer}},{pointer:0}).pointer}},{key:"eventsPlayed",value:function(){return this.tracks.reduce(function(t,e){return{eventIndex:t.eventIndex+e.eventIndex}},{eventIndex:0}).eventIndex}},{key:"endOfFile",value:function(){return this.isPlaying()?this.totalTicks-this.tick<=0:this.bytesProcessed()>=this.midiChunksByteLength}},{key:"getCurrentTick",value:function(){if(!this.startTime)return this.startTick;var t=(new Date().getTime()-this.startTime)/1e3,e=this.ticksToSeconds(0,this.startTick);return this.secondsToTicks(e+t)}},{key:"emitEvent",value:function(t){return this.triggerPlayerEvent("midiEvent",t),this}},{key:"on",value:function(t,e){return this.eventListeners.hasOwnProperty(t)||(this.eventListeners[t]=[]),this.eventListeners[t].push(e),this}},{key:"triggerPlayerEvent",value:function(t,e){return this.eventListeners.hasOwnProperty(t)&&this.eventListeners[t].forEach(function(i){return i(e||{})}),this}}]),r})(),U={Player:Q,Utils:w,Constants:A};var _=class{#s=null;#r=null;#t=null;#n=[];#a=.05;#h=1e-6;#o=2;#e=null;#l=.7;#u=1;#c=null;#m=!1;#d=8192;#g=new Set;constructor(r,s,t=null){this.#s=s,this.#r=t,this.#t=r,this.#e=this.#s.createGain(),this.#e.gain.setValueAtTime(this.#l,this.#s.currentTime),this.#c=this.#s.createGain(),this.#c.gain.setValueAtTime(this.#u,this.#s.currentTime),this.#e.connect(this.#c),this.#c.connect(this.#r?this.#r.input:this.#s.destination),this.#t.zones.map(e=>this.#p(e))}get preset(){return this.#t}set preset(r){this.#t=r,this.#t.zones.map(s=>this.#p(s))}close(){let r=this.#s.currentTime;this.#n.forEach(s=>{try{s.gain.cancelScheduledValues(0),s.audioBufferSourceNode&&(s.audioBufferSourceNode.stop(r),s.audioBufferSourceNode.disconnect(),s.audioBufferSourceNode=null)}catch{}try{s.disconnect()}catch{}}),this.#n=[],this.#g.clear();try{this.#e.disconnect()}catch{}try{this.#c.disconnect()}catch{}this.#e=null,this.#c=null,this.#t=null,this.#r=null,this.#s=null}queueWaveTable(r,s,t,e,i){this.#s.state==="suspended"&&this.#s.resume().catch(()=>{});let a=this.#E(e),n=this.#x(Math.round(s));if(!n?.buffer)return null;let o=n.originalPitch-100*n.coarseTune-n.fineTune,h=s*100,l=(this.#d-8192)/8192*this.#o*100,c=h-o+l,u=Math.pow(2,c/1200),m=Math.max(r,this.#s.currentTime),f=t+this.#a,d=n.loopStart>=1&&n.loopStart<n.loopEnd;d||(f=Math.min(f,n.buffer.duration/u));let p=this.#i();this.#k(p,n,a,m,f,t);let g=this.#s.createBufferSource();if(g.buffer=n.buffer,g.playbackRate.setValueAtTime(u,0),i?.length>0&&(g.playbackRate.setValueAtTime(u,m),i.forEach(y=>{let T=(s+y.delta)*100-o+l,x=Math.pow(2,T/1200);g.playbackRate.linearRampToValueAtTime(x,m+y.when)})),g.loop=d,d){let y=n.delay??0;g.loopStart=n.loopStart/n.sampleRate+y,g.loopEnd=n.loopEnd/n.sampleRate+y}return g.connect(p),g.start(m,n.delay??0),g.stop(m+f),p.audioBufferSourceNode=g,p.when=m,p.duration=f,p.pitch=s,p.baseDetune=o,p}async cancelQueue(){this.#n.forEach(r=>{r.gain.cancelScheduledValues(0),r.gain.setValueAtTime(this.#h,this.#s.currentTime),r.when=-1;try{r.audioBufferSourceNode?.disconnect()}catch{}})}isSustainActive(){return this.#m}registerSustainNote(r){this.#g.add(r)}setPitchBend(r){this.#d=r;let s=r-8192,t=s>=0?s/8191*this.#o:s/8192*this.#o,e=this.#s.currentTime;this.#n.forEach(i=>{if(i.audioBufferSourceNode&&i.when+i.duration>e){let a=i.pitch*100,n=i.baseDetune,o=t*100,h=a-n+o,l=Math.pow(2,h/1200);i.audioBufferSourceNode.playbackRate.cancelScheduledValues(e),i.audioBufferSourceNode.playbackRate.setTargetAtTime(l,e,.015)}})}setController(r,s){let t=this.#s.currentTime,e=Math.max(0,Math.min(127,s))/127;switch(r){case 7:this.#l=e,this.#e.gain.setTargetAtTime(this.#l,t,.05);break;case 11:this.#u=e,this.#c.gain.setTargetAtTime(this.#u,t,.03);break;case 64:this.#m=s>=64,this.#m||(this.#g.forEach(i=>i()),this.#g.clear());break}}#p(r){if(r.buffer)return Promise.resolve(r);if(r.delay=0,r.file){let s=atob(r.file),t=new Uint8Array(s.length);for(let e=0;e<s.length;e++)t[e]=s.charCodeAt(e);this.#s.decodeAudioData(t.buffer,e=>(r.buffer=e,this.#T(r),r),e=>(console.error("Audio decoding error:",e),console.warn(this.#t),!1))}else return this.#T(r),r}#T(r){r.loopStart=this.#y(r.loopStart,0),r.loopEnd=this.#y(r.loopEnd,0),r.coarseTune=this.#y(r.coarseTune,0),r.fineTune=this.#y(r.fineTune,0),r.originalPitch=this.#y(r.originalPitch,6e3)}#k(r,s,t,e,i,a){r.gain.setValueAtTime(this.#h,this.#s.currentTime);let n=Math.min(a,i-this.#a),o=s.ahdsr&&s.ahdsr.length>0?s.ahdsr:[{duration:0,volume:1},{duration:n,volume:1}];r.gain.cancelScheduledValues(e);let h=(o[0]?.volume??1)*t;r.gain.linearRampToValueAtTime(this.#b(h),e+.002);let l=0,c=o[0]?.volume??1;for(let u of o){let{duration:m,volume:f}=u;if(m<=0)continue;let d=n-l;if(m>d){let p=d/m,g=c+p*(f-c);r.gain.exponentialRampToValueAtTime(this.#b(t*g),e+n);break}l+=m,c=f,r.gain.exponentialRampToValueAtTime(this.#b(t*c),e+l)}r.gain.exponentialRampToValueAtTime(this.#h,e+n+this.#a)}#i(r){let s=r||this.#e,t=this.#s.currentTime,e=this.#n.find(i=>i.target===s&&t>i.when+i.duration+.05);if(!e&&this.#n.length>=64){let i=this.#n.filter(a=>a.target===s);i.length>0&&(i.sort((a,n)=>a.when-n.when),e=i[0])}if(e){if(e.audioBufferSourceNode){try{e.audioBufferSourceNode.stop(0),e.audioBufferSourceNode.disconnect()}catch{}e.audioBufferSourceNode=null}e.gain.cancelScheduledValues(0),e.gain.setValueAtTime(this.#h,t)}else e=this.#s.createGain(),e.gain.value=0,e.target=s,e.connect(s),this.#n.push(e);return e.cancel=(i=!1)=>{let a=this.#s.currentTime;if(i&&e.audioBufferSourceNode){try{e.audioBufferSourceNode.stop(0),e.audioBufferSourceNode.disconnect()}catch{}e.audioBufferSourceNode=null}e.when+e.duration>a&&(e.gain.cancelScheduledValues(0),e.gain.setTargetAtTime(this.#h,a,i?.005:.02),e.when=a+1e-5,e.duration=0)},e}#x(r){let s=this.#t.zones.findLast(t=>r>=t.keyRangeLow&&r<=t.keyRangeHigh+1);return s&&this.#p(s),s}#E(r){let s=r?1*r:.5;return Math.min(s,.8)}#b(r){return r>this.#h?r:this.#h}#y(r,s){return typeof r=="number"?r:s}};typeof window<"u"&&(window.WebAudioFontPlayer=_);var $=_;var D=class r{#s=null;#r=null;#t=null;#n=null;#a=null;#h=null;#o=null;#e=0;#l=new Map;static#u=[32,64,128,256,512,1024,2048,4096,8192,16384];static#c=new Map([[32,.7],[64,.8],[128,.9],[256,1],[512,1.1],[1024,1.2],[2048,1.4],[4096,1.6],[8192,1.8],[16384,2]]);constructor(s,t,e){this.#t=s,this.#s=this.#t.createGain();let i=this.#s;[32,64,128,256,512,1024,2048,4096,8192,16384].forEach(n=>{i=this.#m(i,n);let o=n<1e3?n:n/1024+"k";this["band".concat(o)]=i}),this.#e=e,this.#h=this.#t.createConvolver(),this.#o=this.#t.createGain(),this.#o.gain.setValueAtTime(e,this.#t.currentTime),this.#d(1.5,2),this.#n=this.#t.createDynamicsCompressor(),this.#n.threshold.setValueAtTime(-10,this.#t.currentTime),this.#n.ratio.setValueAtTime(20,this.#t.currentTime),this.#n.attack.setValueAtTime(.001,this.#t.currentTime),this.#n.release.setValueAtTime(.1,this.#t.currentTime),this.#n.knee.setValueAtTime(0,this.#t.currentTime),this.#a=this.#t.createAnalyser(),this.#a.fftSize=256,this.#a.smoothingTimeConstant=.6,this.#r=this.#t.createGain(),this.#r.gain.setValueAtTime(t,this.#t.currentTime),i.connect(this.#r),this.#r.connect(this.#n),this.#r.connect(this.#h),this.#h.connect(this.#o),this.#n.connect(this.#a),this.#o.connect(this.#a),this.#a.connect(this.#t.destination)}get eqFrequencies(){return r.#u}get analyser(){return this.#a||null}get input(){return this.#s}get reverb(){return this.#e}set reverb(s){this.#e=Math.max(0,Math.min(1,s)),this.#o.gain.setTargetAtTime(this.#e,this.#t.currentTime,.1)}get masterVolume(){return this.#r.gain.value}set masterVolume(s){let t=Math.max(0,Math.min(1,s)),e=Math.pow(t,2);this.#r.gain.setTargetAtTime(e,this.#t.currentTime,.01)}killReverbTail(){let s=this.#t.currentTime;this.#o.gain.cancelScheduledValues(s),this.#o.gain.setValueAtTime(0,s)}restoreReverb(){this.reverb=this.#e}setEQ(s,t=.04){let e=this.#t.currentTime,i=12;for(let[a,n]of Object.entries(s)){let o=Number(a),h=this.#l.get(o);if(!h)continue;let l=Math.max(-i,Math.min(i,n));h.filter.gain.setTargetAtTime(l,e,t),h.gain=l}}getEQ(){let s={};for(let[t,e]of this.#l)s[t]=e.gain;return s}resetEQ(s=.04){let t={};for(let e of r.#u)t[e]=0;this.setEQ(t,s)}setEQPreset(s){let t={flat:{32:0,64:0,128:0,256:0,512:0,1024:0,2048:0,4096:0,8192:0,16384:0},bass:{32:7,64:6,128:4,256:2,512:0,1024:-1,2048:-1,4096:0,8192:0,16384:0},treble:{32:0,64:0,128:0,256:0,512:0,1024:1,2048:3,4096:5,8192:7,16384:8},vocal:{32:-3,64:-2,128:0,256:2,512:4,1024:5,2048:4,4096:2,8192:1,16384:0},loudness:{32:6,64:4,128:1,256:0,512:-1,1024:-1,2048:0,4096:2,8192:4,16384:5},classical:{32:4,64:3,128:2,256:0,512:0,1024:0,2048:0,4096:2,8192:3,16384:4},jazz:{32:4,64:3,128:1,256:0,512:-1,1024:-1,2048:0,4096:1,8192:3,16384:4},electronic:{32:6,64:5,128:2,256:-1,512:-2,1024:-1,2048:2,4096:4,8192:5,16384:6}},e=t[s];if(!e)throw new Error('Preset EQ unkown: "'.concat(s,'". Avaiables: ').concat(Object.keys(t).join(", ")));this.setEQ(e)}#m(s,t){let e=this.#t.createBiquadFilter();e.type="peaking",e.frequency.setValueAtTime(t,this.#t.currentTime),e.gain.setValueAtTime(0,this.#t.currentTime);let i=r.#c.get(t)??1;return e.Q.setValueAtTime(i,this.#t.currentTime),this.#l.set(t,{filter:e,gain:0}),s.connect(e),e}#d(s,t){let e=this.#t.sampleRate,i=e*s,a=this.#t.createBuffer(2,i,e),o=Math.floor(.015*e);for(let h=0;h<a.numberOfChannels;h++){let l=a.getChannelData(h),c=0,u=h===1?Math.floor(.002*e):0;for(let m=0;m<i;m++){if(m<o){l[m]=0;continue}let f=(m-o)/e,d=Math.exp(-f*(t/s)),p=Math.max(.01,.2*Math.exp(-f*2.5));c=(Math.random()*2-1)*p+c*(1-p);let y=c*d;f<.04&&(m%123===0||m%234===0)&&(y+=(Math.random()*2-1)*.2*(.04-f)/.04),m+u<i?l[m+u]=y:l[m]=y}}this.#h.buffer=a}};var Z="MidiAudioPlayer",P="KeyValues";var M=null,F=1;async function O(r=F){return M&&r!==F&&(M.close(),M=null,F=r),M||new Promise((s,t)=>{let e=indexedDB.open(Z,r);e.onupgradeneeded=i=>{let a=i.target.result;a.objectStoreNames.contains(P)||a.createObjectStore(P)},e.onsuccess=i=>{M=i.target.result,s(M)},e.onerror=i=>t(i.target.error)})}var J={async setVersion(r){await O(r)},async setItem(r,s,t=!1){let e=await O(),i=s,a=!1;if(t){let o=JSON.stringify(s),l=new Blob([o]).stream().pipeThrough(new CompressionStream("gzip"));i=await new Response(l).arrayBuffer(),a=!0}let n={data:i,isCompressed:a};return new Promise((o,h)=>{let u=e.transaction(P,"readwrite").objectStore(P).put(n,r);u.onsuccess=()=>o(),u.onerror=()=>h(u.error)})},async getItem(r){let s=await O(),t=await new Promise((e,i)=>{let o=s.transaction(P,"readonly").objectStore(P).get(r);o.onsuccess=()=>e(o.result),o.onerror=()=>i(o.error)});if(!t)return null;if(t.isCompressed){let i=new Blob([t.data]).stream().pipeThrough(new DecompressionStream("gzip")),n=await new Response(i).text();return JSON.parse(n)}return t.data},async removeItem(r){let s=await O();return new Promise((t,e)=>{let n=s.transaction(P,"readwrite").objectStore(P).delete(r);n.onsuccess=()=>t(),n.onerror=()=>e(n.error)})},async clear(){let r=await O();return new Promise((s,t)=>{let a=r.transaction(P,"readwrite").objectStore(P).clear();a.onsuccess=()=>s(),a.onerror=()=>t(a.error)})}},I=J;var z=(r,s,t)=>Math.min(Math.max(r,s),t),L=class r extends U.Player{static ENDPOINT="https://webaudiofonts.com/presets/";static DEFAULT_PRESET=-1;static REFERENCE_GAIN=.15;static KARAOKE_CHANNEL=0;#s=null;#r=null;#t=null;#n=null;#a={};#h={};#o={};#e={};#l={};#u={};#c={};#m=null;#d=null;#g=null;#p=null;#T=!1;#k="";#i={endpoint:r.ENDPOINT,volume:.6,reverb:.3,onEndFile:null,localCache:!0,presetRandom:!1,karaoke:!1,karaokeDelay:0,muteExpression:!1,maxCharPerLine:48,eqPreset:"flat",preferred:[],presets:[]};constructor(s={}){super(),this.#i={...this.#i,...s},this.#g=this.#x(),this.#r=new(window.AudioContext||window.webkitAudioContext),this.#t=new D(this.#r,this.#i.volume,this.#i.reverb),this.#t.setEQPreset(this.#i.eqPreset),this.#i.karaoke&&this.#C("intro")}get catalog(){return this.getCatalog()}get channels(){return this.#e}get channelStates(){return this.#h}get volume(){return this.#i.volume}set volume(s){this.#i.volume=z(s,0,1),this.#t.masterVolume=this.#i.volume}get volumes(){return this.#u}get reverb(){return this.#t.reverb}set reverb(s){this.#t.reverb=s}get muteExpression(){return this.#i.muteExpression}set muteExpression(s){this.#i.muteExpression=!!s}get eqFrequencies(){return this.#t.eqFrequencies}get eq(){return this.#t.getEQ()}getEQ(){return this.#t.getEQ()}setEQ(s){this.#t.setEQ(s)}setEQPreset(s){this.#t.setEQPreset(s)}setChannelVolume(s,t){this.#u[s]=t,this.#E()}async#x(){await Promise.all(this.#i.presets.map(async s=>{let t=await this.findPreset(s);t&&(this.#c[t.program]=t)}))}async findPreset(s){let t=null;return(await this.getCategories()).some(i=>{if(i.instruments.some(a=>{if(t=a.presets.find(n=>n.id==s),t)return t.category=i.name,t.instrument=a.name,t.program=a.program,!0}),t)return!0}),t}async close(){Object.keys(this.#e).forEach(s=>this.#e[s].close()),await this.#r.close()}async getCatalog(){if(this.#s)return this.#s;let s=this.#i.localCache?await sessionStorage.getItem("waf_catalog"):null;if(s)this.#s=JSON.parse(s);else{this.#f("Downloading catalog...");let i=await fetch("".concat(this.#i.endpoint,"catalog.json"));if(!i.ok)throw new Error("Impossible to download catalog: ".concat(i.status));this.#s=await i.json(),this.#i.localCache&&await sessionStorage.setItem("waf_catalog",JSON.stringify(this.#s))}let t=new Date(this.#s.updatedAt).getTime();return(await I.getItem("waf_catalog_version")||1)<t&&(await I.clear(),I.setItem("waf_catalog_version",t)),this.#s}async getCategories(){return(await this.getCatalog()).categories}async getProgramInstruments(s){let t=await this.getCategories(),e=[];return await Promise.all(t.map(async i=>i.instruments.filter(a=>a.program==s).forEach(a=>{a.presets.forEach(n=>{n.instrument=i.name+" / "+a.name,e.push(n)})}))),e}async getPreset(s){try{if(typeof s=="object")return s;let t="waf_preset_".concat(s),e=this.#i.localCache?await I.getItem(t):null;if(e)return JSON.parse(e);this.#f("Downloading preset ".concat(s,"..."));let a=await(await fetch("".concat(r.ENDPOINT).concat(s,".json"))).json();if(a.zones===void 0)throw console.error("Invalid preset: ".concat($id)),new Error("Invalid preset: ".concat($id));return this.#i.localCache&&await I.setItem(t,JSON.stringify(a),!0),a}catch{throw console.error("Invalid preset: ".concat(s)),new Error("Invalid preset: ".concat(s))}}async loadPreset(s,t){let e=await this.findPreset(s);if(!e)throw new Error("Invalid preset: ".concat(s));this.#c[e.program]=e;let i=await this.getPreset(s);this.#e[t].preset=i,this.#E()}async load(s,t){typeof s=="string"&&(this.#f("Downloading song..."),s=await(await fetch(s)).arrayBuffer()),typeof t=="string"&&(this.#f("Downloading setup..."),t=await(await fetch(t)).json()),this.#m=await this.hashBuffer(s),await this.#g,this.isPlaying()&&this.stop(),this.#v(),await Promise.all(Object.values(this.#e).map(async o=>o.close())),this.#e={},this.#o={},this.#a={},this.#k="",this.#f("Loading buffer...");try{await this.loadArrayBuffer(s)}catch{await this.loadArrayBuffer(await this.#R(s))}this.#f("Loading instruments..."),this.#l=await this.#N(),this.#h=Object.keys(this.#l).reduce((o,h)=>({...o,[h]:!1}),{}),this.#u=Object.keys(this.#l).reduce((o,h)=>({...o,[h]:1}),{}),t?.volumes!==void 0&&await Promise.all(Object.keys(t.volumes).map(async o=>{this.#u[o]!==void 0&&(this.#u[o]=t.volumes[o])}));let e=new Set,i={};t?.presets!==void 0&&await Promise.all(Object.keys(t.presets).map(async o=>{let h=await this.findPreset(t.presets[o]);h&&(i[o]=await this.getPreset(h.id),e.add(h.program))}));let a=await this.#M();Object.values(this.#l).length||this.#f("Error: no instrument found");let n=Promise.all([...a].map(async o=>{if(e.has(o))return;let h=null;this.#c[o]!==void 0?h=await this.getPreset(this.#c[o].id):this.#i.presetRandom?h=await this.#I(o):h=await this.#L(o),this.#o[o]=h}));this.#i.karaoke&&(this.#f("Generating karaoke frames..."),this.#p=null,await this.#V(),this.#k&&this.#C("title",this.#k)),this.#f("Trim midi events..."),this.#B(),queueMicrotask(()=>this.triggerPlayerEvent("computed")),await n,await Promise.all(Object.keys(this.#l).map(async o=>{this.#e[o]&&this.#e[o].close(),i[o]!==void 0?this.#e[o]=await this.#A(i[o]):this.#e[o]=await this.#A(this.#o[this.#l[o]])})),this.#f("Initializing instrument states..."),await this.#y(),await this.triggerPlayerEvent("presetsLoaded",this.#o),await this.#E(),this.#f("Player ready")}async getSongSetup(){let s={hash:this.#m,presets:{},volumes:{}};return Object.keys(this.#e).map(async t=>s.presets[t]=this.#e[t].preset.id),s.volumes=this.#u,s}async getTrainingPresets(){return await Promise.all(Object.values(this.#c).map(async s=>s.id))}async play(s=null){if(this.#r.state==="suspended")try{await this.#r.resume()}catch{return!1}return s&&await this.load(s),await Promise.all(Object.keys(this.#e).map(async t=>await this.#e[t]?.cancelQueue())),this.#t.restoreReverb(),this.isPlaying()||(this.startTime||(this.startTime=new Date().getTime()),this.scheduledTime=Date.now(),this.schedulePlayLoop(this.sampleRate)),!0}async pause(){await super.pause(),this.#t.killReverbTail(),await this.#v(),await Promise.all(Object.keys(this.#e).map(async s=>await this.#e[s]?.cancelQueue()))}async stop(s=!1){return await super.stop(),this.setTimeoutId=!1,s||(this.#t.killReverbTail(),await Promise.all(Object.keys(this.#e).map(async t=>await this.#e[t]?.cancelQueue()))),await this.#v(),this.#i.karaoke&&this.#C("intro"),this}getRealTimeVolume(){let s=this.#t.analyser,t=new Uint8Array(s.frequencyBinCount);s.getByteFrequencyData(t);let e=0;for(let i=0;i<t.length;i++)e+=t[i];return e/(t.length*100)}getSongTimeRemaining(){return this.ticksToSeconds(this.getCurrentTick(),this.totalTicks)}async skipToSeconds(s){let t=this.getSongTime();if(s<0||s>t)throw s+" seconds not within song time of "+t;return await this.skipToTick(this.secondsToTicks(s)),this}async generateWaveformSVG(s=1e3){if(!this.totalTicks||!this.events)return"";let t=new Array(s).fill(0),e=this.totalTicks/s,i=this.events.flatMap((f,d)=>f.map(p=>({...p,computedChannel:p.channel!==void 0?p.channel:d}))).filter(f=>f.name==="Controller Change"||f.name==="Program Change"||f.name==="Note on"&&f.velocity>0).sort((f,d)=>f.tick-d.tick),a=new Map,n=new Map;i.forEach(f=>{let d=Math.floor(f.tick/e);if(d>=s)return;let p=f.computedChannel;if(a.has(p)||a.set(p,100),n.has(p)||n.set(p,127),f.name==="Controller Change")f.number===7?a.set(p,f.value):f.number===11&&n.set(p,f.value);else if(f.name==="Note on"){let g=a.get(p)/127,y=n.get(p)/127,k=f.velocity*g*y;t[d]+=k}});let o=t.reduce((f,d)=>isNaN(d)?f:d>f?d:f,0),h=o>0?t.map(f=>isNaN(f)?0:f/o):t.fill(0),l=s,c=l/5,u=h.map((f,d)=>{let p=d,g=Math.max(0,Math.min(c,c-f*c));return"".concat(p,",").concat(g.toFixed(2))}),m="M 0,".concat(c," L ").concat(u.join(" L ")," L ").concat(l,",").concat(c);return'<svg class="midiaudioplayer-waveform" viewBox="0 0 '.concat(l," ").concat(c,'" preserveAspectRatio="none"><path d="').concat(m,'" fill="none" stroke-linecap="round" stroke-linejoin="round" /></svg>')}async hashBuffer(s,t="SHA-256"){let e=await crypto.subtle.digest(t,s);return Array.from(new Uint8Array(e)).map(a=>a.toString(16).padStart(2,"0")).join("")}async#E(){this.#d&&clearTimeout(this.#d),this.#d=setTimeout(async()=>{let s=await this.getSongSetup();queueMicrotask(()=>this.triggerPlayerEvent("setupChange",s))},1e3)}async triggerPlayerEvent(s,t){s!="fileLoaded"&&(s=="computed"?(this.#n=await this.#F(),super.triggerPlayerEvent(s,{title:this.#k,karaoke:this.#T,vocalChannel:this.#n,tempo:this.tempo,division:this.division,duration:this.getSongTime(),sampleRate:this.sampleRate,totalTicks:this.totalTicks,totalEvents:this.totalEvents,channels:await this.#l})):s=="endOfFile"&&this.#i.karaoke?queueMicrotask(()=>super.triggerPlayerEvent(s,t)):super.triggerPlayerEvent(s,t))}async playLoop(s){if(this.inLoop)return;if(!s&&this.endOfFile()&&this.tick>0){await this.stop(!0),this.tick=0,this.triggerPlayerEvent("endOfFile");return}this.inLoop=!0,this.tick=this.getCurrentTick();let t=this.tracks.length;for(let e=0;e<t;e++){let i=this.tracks[e].handleEvent(this.tick,s);if(!i)continue;let a=i.constructor===Array,n=a?i.length:1;for(let o=0;o<n;o++){let h=a?i[o]:i,{name:l,data:c,value:u}=h;l==="Set Tempo"&&this.setTempo(c),s?l==="Program Change"&&!this.instruments.includes(u)&&this.instruments.push(u):this.emitEvent(h)}}!s&&this.isPlaying()&&this.triggerPlayerEvent("playing",{tick:this.tick}),this.inLoop=!1}schedulePlayLoop(s){this.setTimeoutId=setTimeout(()=>{if(this.setTimeoutId===!1)return;this.playLoop();let t=this.#r.currentTime;this._lastAudioTime||(this._lastAudioTime=t);let e=t-this._lastAudioTime;this._lastAudioTime=t;let i=this.sampleRate/1e3,a=e-i,n=Math.max(0,this.sampleRate-a*1e3);this.schedulePlayLoop(n)},s)}emitEvent(s){this.#D(s)}ticksToSeconds(s,t){if(t===void 0&&(t=s,s=0),s>=t)return 0;let e=0,i=this.tempoMap.length,a=60/this.division,n=0,o=i-1,h=0;for(;n<=o;){let c=n+o>>1;this.tempoMap[c].tick<=s?(h=c,n=c+1):o=c-1}let l=s;for(let c=h;c<i;c++){let u=this.tempoMap[c],m=c+1<i?this.tempoMap[c+1].tick:t;if(m<=s)continue;let f=Math.max(u.tick,s),d=Math.min(m,t);if(f>=t)break;e+=(d-f)/u.tempo*a,l=d}if(l<t){let c=this.tempoMap[i-1];e+=(t-l)/c.tempo*a}return e}secondsToTicks(s){let t=s,e=this.tempoMap.length,i=60/this.division;for(let a=0;a<e;a++){let n=this.tempoMap[a],l=((a+1<e?this.tempoMap[a+1].tick:1/0)-n.tick)/n.tempo*i;if(t<=l)return n.tick+Math.round(t*n.tempo/i);t-=l}return this.totalTicks}getTickBeforeSeconds(s,t){if(s<=0)return 0;let e=this.ticksToSeconds(0,s),i=Math.max(0,e-t);return this.secondsToTicks(i)}async skipToTick(s){let t=Math.max(0,Math.min(s,this.totalTicks||0)),e=this.isPlaying();if(this.#v(),Object.keys(this.channels).forEach(i=>this.channels[i]?.cancelQueue?.()),e&&super.pause(),this.startTick=t,this.tick=t,this.tempoMap&&this.tempoMap.length>0){for(let i=this.tempoMap.length-1;i>=0;i--)if(this.tempoMap[i].tick<=t){this.setTempo(this.tempoMap[i].tempo);break}}try{let i=[],a=[],n=[],o=[];this.#b(t).forEach(h=>{let l=h.channel;if(!((l===void 0||!this.channels[l])&&h.name!=="Karaoke Event"))switch(h.name){case"Controller Change":i[h.channel]=h;break;case"Program Change":a[h.channel]=h;break;case"Pitch Bend":n[h.channel]=h;break;case"Karaoke Event":o[h.channel]=h;break}}),i.forEach(h=>this.emitEvent(h)),a.forEach(h=>this.emitEvent(h)),n.forEach(h=>this.emitEvent(h)),o.forEach(h=>this.triggerPlayerEvent("karaoke",{type:h.type,tick:h.tick,html:h.text}))}catch(i){console.warn("Chase MIDI Error:",i),this.#f("Chase MIDI Error:",i)}return this.tracks&&this.tracks.length>0&&this.tracks.forEach((i,a)=>{let n=this.events[a];if(n&&n.length>0){let o=0,h=n.length-1,l=n.length;for(;o<=h;){let c=o+h>>1;n[c].tick>=t?(l=c,h=c-1):o=c+1}i.eventIndex=l}else typeof i.setEventIndexByTick=="function"&&i.setEventIndexByTick(t)}),e?this.play():this.triggerPlayerEvent("playing",{tick:t}),this}#b(s){let t={};if(!this.events)return[];for(let e=0;e<this.events.length;e++){let i=this.events[e];if(!i||i.length===0)continue;let a=0,n=i.length-1,o=i.length;for(;a<=n;){let h=a+n>>1;i[h].tick>=s?(o=h,n=h-1):a=h+1}for(let h=0;h<o;h++){let l=i[h],c;l.name==="Program Change"?c="pc:"+l.channel:l.name==="Controller Change"?c="cc:"+l.channel+":"+l.number:l.name==="Pitch Bend"?c="pb:"+l.channel:l.name==="Karaoke Event"&&(c="ke:"+l.channel),c&&(t[c]=l)}}return Object.keys(t).map(e=>t[e])}async#y(){this.events&&this.#b(1).forEach(s=>{let t=s.channel;if(this.#e[t])switch(s.name){case"Controller Change":this.#e[t].setController(s.number,s.value);break;case"Pitch Bend":this.#e[t].setPitchBend?.(s.value);break;case"Program Change":s.value>=0&&s.value<=127&&this.#o[s.value+1]!==void 0&&s.channel!=10&&this.#e[t].preset?.program!==s.value+1&&(this.#e[t].preset=this.#o[s.value+1]);break}})}async#N(){let s={},t=new Set;return this.events.forEach(e=>{e.forEach(i=>{if(i.name==="Program Change"&&i.value>=0&&i.value<=127){if(s[i.channel])return;i.channel==10?s[i.channel]=-1:s[i.channel]=i.value+1}else i.name==="Note on"&&i.channel==10?(s[i.channel]=-1,t.add(10)):i.name==="Note on"&&t.add(i.channel)})}),Object.keys(s).forEach(e=>{t.has(Number(e))||delete s[e]}),s}async#M(){let s=new Set;return this.events.forEach(t=>{t.forEach(e=>{e.name==="Program Change"&&e.value>=0&&e.value<=127?s.add(e.channel==10?-1:e.value+1):e.name==="Note on"&&e.channel==10&&s.add(-1)})}),s}async#I(s){let t=await this.getProgramInstruments(s);if(!t.length)return null;let e=null;return this.#i.preferred.some(i=>{let a=new RegExp("_".concat(i,"$"),"i"),n=t.filter(o=>a.test(o.id));if(n.length)return e=n[Math.floor(Math.random()*n.length)],!0}),e||(e=t[Math.floor(Math.random()*t.length)]),this.#c[s]=e,await this.getPreset(e.id)}async#L(s){let t=await this.getProgramInstruments(s);if(!t.length)return null;let e=null;return this.#i.preferred.some(i=>{let a=new RegExp("_".concat(i,"$"),"i");if(e=t.find(n=>a.test(n.id)),e)return!0}),e||(e=t[0]),this.#c[s]=e,await this.getPreset(e.id)}async#A(s){return new $(s,this.#r,this.#t)}async#D(s){if(this.isPlaying())switch(s.name){case"Note on":if(s.tick<this.tick-100||s.noteNumber===void 0||s.channel==this.#n&&this.#i.muteExpression)return;if(s.velocity>0&&s.velocity<=127){if(this.#S(s.channel,s.noteNumber),this.#u[s.channel]==0)return;let t=s.velocity/127,e=r.REFERENCE_GAIN*Math.pow(t,2)*this.#u[s.channel],i=this.#e[s.channel]?.queueWaveTable(0,s.noteNumber,2,e);i&&this.#O(s.channel,s.noteNumber,i)}else this.#S(s.channel,s.noteNumber);break;case"Note off":if(s.noteNumber===void 0)return;this.#S(s.channel,s.noteNumber);break;case"Controller Change":this.#e[s.channel]?.setController(s.number,s.value);break;case"Pitch Bend":this.#e[s.channel]?.setPitchBend?.(s.value);break;case"Program Change":return;case"Karaoke Event":if(s.tick<this.tick-this.secondsToTicks(10))return;this.triggerPlayerEvent("karaoke",{type:s.type,tick:s.tick,html:s.text});break}}#O(s,t,e){this.#a[s]||(this.#a[s]=new Map),this.#a[s].set(t,e),this.#w();let i=(e.duration||0)*1e3;e.cleanupTimer=setTimeout(()=>{this.#a[s]?.get(t)===e&&(this.#a[s].delete(t),this.#w())},i+50)}#S(s,t){let e=this.#e[s],i=this.#a[s]?.get(t);if(i){i.cleanupTimer&&clearTimeout(i.cleanupTimer);let a=()=>{this.#a[s]?.delete(t),this.#w()};e&&e.isSustainActive()?e.registerSustainNote(()=>i.cancel(!1)):i.cancel(!1),a()}}#v(){Object.keys(this.#a).forEach(s=>{this.#a[s].forEach((t,e)=>{t&&(t.cleanupTimer&&clearTimeout(t.cleanupTimer),t.cancel&&t.cancel(!0)),this.#a[s]?.delete(e)})}),this.#w()}async#w(){let s=!1,t={};Object.keys(this.#e).forEach(e=>{let i=!!(this.#a[e]?.size&&this.#a[e].size>0);t[e]=i,this.#h[e]!==i&&(s=!0)}),s&&(this.#h=t,this.triggerPlayerEvent("channelState",this.#h))}async#R(s){let t=new Uint8Array(s),e=new DataView(s);if(String.fromCharCode(...t.slice(0,4))!=="MThd")throw new Error("Invalid MIDI file (MThd missing)");let a=e.getUint32(4),n=e.getUint16(8),o=e.getUint16(10),h=e.getUint16(12),l=[255,47,0],c=[],u=8+a;for(;u<t.length&&!(u+8>t.length);){let k=String.fromCharCode(...t.slice(u,u+4)),T=e.getUint32(u+4),x=u+8,S=x+T;if(k!=="MTrk"){let C=Math.min(S,t.length);c.push({tag:k,data:t.slice(u,C),repaired:!1}),u=S;continue}let E=c.filter(C=>C.tag==="MTrk").length+1,b=Math.min(T,t.length-x),v=t.slice(x,x+b),N=v.slice(-3);if(N[0]===255&&N[1]===47&&N[2]===0&&b===T)c.push({tag:k,data:v,repaired:!1});else{let C;if(b<T){let Y=T-b,K=v.slice(-2);K[0]===255&&K[1]===47?(C=new Uint8Array(v.length+1),C.set(v),C[v.length]=0):(C=new Uint8Array(v.length+3),C.set(v),C.set(l,v.length))}else C=new Uint8Array(v.length+3),C.set(v),C.set(l,v.length);c.push({tag:k,data:C,repaired:!0})}u=S}let m=c.filter(k=>k.tag==="MTrk").length,f=14+c.reduce((k,T)=>k+8+T.data.length,0),d=new Uint8Array(f),p=new DataView(d.buffer);d.set([77,84,104,100],0),p.setUint32(4,6),p.setUint16(8,n),p.setUint16(10,m),p.setUint16(12,h);let g=14;for(let k of c){let T=k.tag.split("").map(x=>x.charCodeAt(0));d.set(T,g),p.setUint32(g+4,k.data.length),d.set(k.data,g+8),g+=8+k.data.length}let y=c.filter(k=>k.repaired).length;return d.buffer}#B(){if(!this.events||this.events.length===0)return;let s=1/0,t=0;if(this.events.forEach(o=>{o.forEach(h=>{(h.name==="Note on"||h.name==="Note off")&&(h.tick<s&&(s=h.tick),h.tick>t&&(t=h.tick))})}),s===1/0)return;let e=[];this.events.forEach((o,h)=>{o.forEach(l=>{let c=l.name==="Program Change"||l.name==="Controller Change"||l.name==="Pitch Bend"||l.name==="Set Tempo";l.tick<s&&c&&e.push({event:l,trackIdx:h})})});let i=Object.fromEntries(this.events.map((o,h)=>[h,[]])),a=new Set;for(let o=e.length-1;o>=0;o--){let{event:h,trackIdx:l}=e[o],c=h.channel!==void 0?h.channel:"track-".concat(l),u=null;if(h.name==="Program Change"?u="pc:".concat(c):h.name==="Controller Change"?u="cc:".concat(c,":").concat(h.number):h.name==="Pitch Bend"?u="pb:".concat(c):h.name==="Set Tempo"&&(u="tempo"),u&&!a.has(u)){a.add(u);let m={...h,tick:0};i[l].push(m)}}let n=this.events.map((o,h)=>{let l=[];return o.forEach(u=>{let m=u.name==="Program Change"||u.name==="Controller Change"||u.name==="Pitch Bend"||u.name==="Set Tempo",f=u.name==="Text Event"||u.name==="Lyric Event"||u.name==="Track Name"||u.name==="Karaoke Event";if(u.tick<s)!m&&(f||h===0)&&(u.tick=0,l.push(u));else{u.tick=u.tick-s;let d=t-s;u.tick>d&&(u.tick=d),l.push(u)}}),[...i[h]||[],...l].sort((u,m)=>u.tick-m.tick)});this.events=n,this.totalTicks=t-s,typeof this.computeTempoMap=="function"&&this.computeTempoMap()}async#P(){if(this.#p)return this.#p;let s={language:"",title:"",paragraphs:[]},t=null,e=0;if(this.events.forEach(l=>{let c=l.filter(m=>m.name==="Text Event"||m.name==="Lyric Event"||m.name==="Cue Point"||m.name==="Marker"||m.name==="Track Name"),u=c.filter(m=>{let f=m.string||m.text||"";return f&&!f.startsWith("@")}).length;u>e&&(e=u,t=c)}),!t||t.length===0)return s;let i=t.sort((l,c)=>l.tick-c.tick),a=[],n=[],o=[],h=0;for(i.forEach(l=>{let c=this.#K(l.string||"");if(!c||/^Track-/i.test(c.trim())||/^Piste/i.test(c.trim())||c.trim()===""||l.tick===0&&c.length>20)return;if(c.startsWith("@L")){s.language=c.substring(2).trim();return}if(c.startsWith("@T")){s.title+=(s.title?" / ":"")+c.substring(2).trim();return}if(c.startsWith("@")||c.startsWith("(")||c.startsWith("PART")||/^\d+\s+\d+/.test(c.trim()))return;if(/^(Verse|Chorus|Bridge|Break|Intro|End\.)/i.test(c.trim())){let y=c.startsWith("\\")||c.startsWith("/"),k=o.length===0||l.tick-h>500;if((y||k)&&(o.length>0&&(n.push({tick:o[0].tick,blocks:o}),o=[]),n.length>0)){for(;n.length>4;){let T=n.splice(0,4);a.push({tick:T[0].tick,lines:T})}n.length>0&&(a.push({tick:n[0].tick,lines:n}),n=[])}return}let u=!1;if(o.length>0){let k=o[o.length-1].text,T=c.trimLeft();if(T.length>0){let x=/^[A-Z]/.test(T)||/^'[A-Z]/.test(T),S=/^[A-Z]/.test(k.trim())||/^'[A-Z]/.test(k.trim());x&&!k.endsWith(" ")&&k.trim()!="o"&&!S&&l.tick>h&&(u=!0),c.startsWith('"')&&k.endsWith('"')&&(u=!0),c.startsWith('"')&&(k.endsWith(")")||k.endsWith(')"'))&&(u=!0),T.startsWith('"')&&k.trimRight().endsWith(")")&&(u=!0)}}let m=c.startsWith("\\"),f=c.startsWith("/")||u;(m||f)&&(c.startsWith("\\")||c.startsWith("/"))&&(c=c.substring(1)),c=c.replace(/[\r\n]/g,"");let d=!1;h>0&&l.tick>h&&this.ticksToSeconds(h,l.tick)>2.5&&(d=!0);let g=o.reduce((y,k)=>y+k.text.length,0)+c.length>this.#i.maxCharPerLine;if((f||m||d||g)&&(o.length>0&&(n.push({tick:o[0].tick,blocks:o}),o=[]),n.length>0)){if(m||d){for(;n.length>4;){let y=n.splice(0,4);a.push({tick:y[0].tick,lines:y})}n.length>0&&(a.push({tick:n[0].tick,lines:n}),n=[])}else if(n.length>=6){let y=n.splice(0,4);a.push({tick:y[0].tick,lines:y})}}c.length>0&&(o.push({text:c,tick:l.tick}),h=l.tick)}),o.length>0&&n.push({tick:o[0].tick,blocks:o});n.length>4;){let l=n.splice(0,4);a.push({tick:l[0].tick,lines:l})}return n.length>0&&a.push({tick:n[0].tick,lines:n}),a=a.filter(l=>!(l.lines.length==1&&l.lines[0].blocks.length==1&&["intro","outro","sfx","solo","chorus","verse","bridge","break","end"].includes(l.lines[0].blocks[0].text.toLowerCase().trim()))),a.length<=2&&(a=[]),s.paragraphs=a,this.#p=s,s}async#V(){let s=await this.#P();if(!s.paragraphs.length){this.#T=!1,this.events[r.KARAOKE_CHANNEL].push({text:'<span class="karaoke-intro"></span>',name:"Karaoke Event",type:"intro",tick:0,channel:r.KARAOKE_CHANNEL}),this.events[r.KARAOKE_CHANNEL]=this.events[r.KARAOKE_CHANNEL].sort((u,m)=>u.tick-m.tick);return}this.#T=!0,this.#k=s.title;let t=0,e=this.secondsToTicks(this.#i.karaokeDelay),i=this.secondsToTicks(3),a=this.secondsToTicks(5),n=this.secondsToTicks(7),o=this.secondsToTicks(10),h=[];s.paragraphs.forEach((u,m)=>{u.lines.forEach((f,d)=>{f.blocks.forEach(p=>{h.push({block:p,lineIdx:d,paraIdx:m,paragraph:u,fastLinesText:u.lines.map(g=>g.blocks.map(y=>y.text).join(""))})})})});let l=[];s.paragraphs.forEach((u,m)=>{let f=this.getTickBeforeSeconds(u.tick,5);f<t&&(f=t+(u.tick-t)/2),m===0&&f<20&&(f=20),l[m]=f;let p=u.lines.map(g=>g.blocks.map(y=>y.text).join("")).map(g=>'<span class="karaoke-coming">'.concat(g,"</span>")).join("<br/>");if(this.events[r.KARAOKE_CHANNEL].push({text:p,name:"Karaoke Event",type:"lyric",tick:f,channel:r.KARAOKE_CHANNEL}),u.lines.length>0){let g=u.lines[u.lines.length-1];g.blocks.length>0&&(t=g.blocks[g.blocks.length-1].tick)}}),(l[0]||0)>25&&this.events[r.KARAOKE_CHANNEL].push({text:'<span class="karaoke-clear"></span>',name:"Karaoke Event",type:"clear",tick:5,channel:r.KARAOKE_CHANNEL}),h.forEach((u,m)=>{let f=u.block,d=u.lineIdx,p=u.paraIdx,g=u.paragraph,y=u.fastLinesText,k=(x=!1)=>g.lines.map((S,E)=>{if(E<d)return'<span class="karaoke-played">'.concat(y[E],"</span>");if(E>d)return'<span class="karaoke-coming">'.concat(y[E],"</span>");let b="";return S.blocks.forEach(v=>{let N="coming";x||v.tick<f.tick?N="played":v.tick===f.tick&&(N="playing"),b+='<span class="karaoke-'.concat(N,'">').concat(v.text,"</span>")}),b}).join("<br>");this.events[r.KARAOKE_CHANNEL].push({text:k(!1),name:"Karaoke Event",type:"lyric",tick:f.tick-e,channel:r.KARAOKE_CHANNEL});let T=h[m+1];if(T){let x=T.block.tick-f.tick;if(x>i){let S=f.tick+i,E=f.tick+n,b=x>o&&p>0;if(T.paraIdx!==p){let v=l[T.paraIdx];S>=v&&(S=v-1),b&&(E>=v||v-E<i)&&(b=!1)}S>f.tick&&this.events[r.KARAOKE_CHANNEL].push({text:k(!0),name:"Karaoke Event",type:"lyric",tick:S-e,channel:r.KARAOKE_CHANNEL}),b&&E>S&&this.events[r.KARAOKE_CHANNEL].push({text:'<span class="karaoke-clear"></span>',name:"Karaoke Event",type:"clear",tick:E-e,channel:r.KARAOKE_CHANNEL})}}t=f.tick}),this.totalTicks-t>this.secondsToTicks(5)?this.events[r.KARAOKE_CHANNEL].push({text:'<span class="karaoke-clear"></span>',name:"Karaoke Event",type:"clear",tick:t+this.secondsToTicks(5),channel:r.KARAOKE_CHANNEL}):this.events[r.KARAOKE_CHANNEL].push({text:'<span class="karaoke-clear"></span>',name:"Karaoke Event",type:"clear",tick:this.totalTicks-1,channel:r.KARAOKE_CHANNEL}),this.events[r.KARAOKE_CHANNEL]=this.events[r.KARAOKE_CHANNEL].sort((u,m)=>u.tick-m.tick)}async#F(){let s=await this.#P();if(!s?.paragraphs?.length)return null;let t=s.paragraphs.flatMap(l=>l.lines.flatMap(c=>c.blocks.map(u=>u.tick)));if(t.length===0)return null;let e=this.division?this.division/2:48,i=48,a=84,n=Object.keys(this.#l).map(Number).filter(l=>l!==10),o=null,h=-1/0;for(let l of n){let c=this.events.flatMap(E=>E.filter(b=>b.name==="Note on"&&b.velocity>0&&b.channel===l));if(c.length===0)continue;let m=t.filter(E=>c.some(b=>Math.abs(b.tick-E)<=e)).length/t.length,d=c.filter(E=>E.noteNumber>=i&&E.noteNumber<=a).length/c.length;if(d<.3)continue;let p=[...c].sort((E,b)=>E.tick-b.tick),g=this.division/8||6,k=1-p.filter((E,b)=>b>0&&Math.abs(E.tick-p[b-1].tick)<g).length/Math.max(c.length-1,1),T=c.length/Math.max(t.length,1),x=T<.3?T/.3:T>5?Math.max(0,1-(T-5)/10):1,S=m*.45+d*.35+k*.15+x*.05;S>h&&(h=S,o=l)}return h>=.4?o:null}#K(s){if(!s)return"";let t=new Uint8Array(s.length);for(let a=0;a<s.length;a++)t[a]=s.charCodeAt(a)&255;let i=new TextDecoder("windows-1252").decode(t);return i=i.replace(/ÿ/g,""),i=i.replace(/’/g,"'"),i=i.replace(/`/g,"'"),i}#C(s="clear",t=""){let e='<span class="karaoke-'.concat(s,'">').concat(t.replace(/\s\/\s/g,"<br>"),"</span>");this.#i.karaoke&&(s=="title"?queueMicrotask(()=>this.triggerPlayerEvent("karaoke",{type:s,title:t,html:e})):queueMicrotask(()=>this.triggerPlayerEvent("karaoke",{type:s,html:e})))}#f(s,t=!1){queueMicrotask(()=>this.triggerPlayerEvent("logs",s))}};typeof window<"u"&&(window.MidiAudioPlayer=L);var ut=L;export{L as MidiAudioPlayer,ut as default};
|
|
18
18
|
//# sourceMappingURL=index.mjs.map
|