forked from deskjet/chiptune2.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
chiptune3.min.js
1 lines (1 loc) · 2.54 KB
/
chiptune3.min.js
1
const defaultCfg={repeatCount:-1,stereoSeparation:100,interpolationFilter:0,context:!1};export class ChiptuneJsPlayer{constructor(t){if(this.config={...defaultCfg,...t},this.config.context){if(!this.config.context.destination)throw"ChiptuneJsPlayer: This is not an audio context";this.context=this.config.context,this.destination=!1}else this.context=new AudioContext,this.destination=this.context.destination;delete this.config.context,this.gain=this.context.createGain(),this.gain.gain.value=1,this.handlers=[],this.context.audioWorklet.addModule(new URL("./chiptune3.worklet.min.js",import.meta.url)).then((()=>{this.processNode=new AudioWorkletNode(this.context,"libopenmpt-processor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]}),this.processNode.port.onmessage=this.handleMessage_.bind(this),this.processNode.port.postMessage({cmd:"config",val:this.config}),this.fireEvent("onInitialized"),this.processNode.connect(this.gain),this.destination&&this.gain.connect(this.destination)})).catch((t=>console.error(t)))}handleMessage_(t){switch(t.data.cmd){case"meta":this.meta=t.data.meta,this.duration=t.data.meta.dur,this.fireEvent("onMetadata",this.meta);break;case"pos":this.currentTime=t.data.pos,this.order=t.data.order,this.pattern=t.data.pattern,this.row=t.data.row,this.fireEvent("onProgress",t.data);break;case"end":this.fireEvent("onEnded");break;case"err":this.fireEvent("onError",{type:t.data.val});break;default:console.log("Received unknown message",t.data)}}fireEvent(t,e){const s=this.handlers;s.length&&s.forEach((function(s){s.eventName===t&&s.handler(e)}))}addHandler(t,e){this.handlers.push({eventName:t,handler:e})}onInitialized(t){this.addHandler("onInitialized",t)}onEnded(t){this.addHandler("onEnded",t)}onError(t){this.addHandler("onError",t)}onMetadata(t){this.addHandler("onMetadata",t)}onProgress(t){this.addHandler("onProgress",t)}postMsg(t,e){this.processNode&&this.processNode.port.postMessage({cmd:t,val:e})}load(t){fetch(t).then((t=>t.arrayBuffer())).then((t=>this.play(t))).catch((t=>{this.fireEvent("onError",{type:"Load"})}))}play(t){this.postMsg("play",t)}stop(){this.postMsg("stop")}pause(){this.postMsg("pause")}unpause(){this.postMsg("unpause")}togglePause(){this.postMsg("togglePause")}setRepeatCount(t){this.postMsg("repeatCount",t)}setPitch(t){this.postMsg("setPitch",t)}setTempo(t){this.postMsg("setTempo",t)}setPos(t){this.postMsg("setPos",t)}setOrderRow(t,e){this.postMsg("setOrderRow",{o:t,r:e})}setVol(t){this.gain.gain.value=t}selectSubsong(t){this.postMsg("selectSubsong",t)}seek(t){this.setPos(t)}getCurrentTime(){return this.currentTime}}