Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

web-audio-api-player

Package Overview
Dependencies
Maintainers
1
Versions
31
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

web-audio-api-player - npm Package Compare versions

Comparing version 4.1.0 to 4.2.0

2

dist/index.min.js

@@ -1,2 +0,2 @@

var e=function(t,o){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])},e(t,o)};function t(e,t,o,n){return new(o||(o=Promise))((function(i,u){function r(e){try{a(n.next(e))}catch(e){u(e)}}function s(e){try{a(n.throw(e))}catch(e){u(e)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(r,s)}a((n=n.apply(e,t||[])).next())}))}function o(e,t){var o,n,i,u,r={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return u={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function s(s){return function(a){return function(s){if(o)throw new TypeError("Generator is already executing.");for(;u&&(u=0,s[0]&&(r=0)),r;)try{if(o=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return r.label++,{value:s[1],done:!1};case 5:r.label++,n=s[1],s=[0];continue;case 7:s=r.ops.pop(),r.trys.pop();continue;default:if(!(i=r.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){r=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){r.label=s[1];break}if(6===s[0]&&r.label<i[1]){r.label=i[1],i=s;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(s);break}i[2]&&r.ops.pop(),r.trys.pop();continue}s=t.call(e,r)}catch(e){s=[6,e],n=0}finally{o=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}}var n=function(){function e(e){this.url=null,this.codec=null,this.audioBufferSourceNode=null,this.mediaElementAudioSourceNode=null,this.isReadyToPLay=!1,this.isBuffered=!1,this.isBuffering=!1,this.audioElement=null,this.audioBuffer=null,this.arrayBuffer=null,this.audioBufferDate=null,this.playTimeOffset=0,this.startTime=0,this.playTime=0,this.playedTimePercentage=0,this.state="sound_state_stopped",this.loadingProgress=0,this.duration=null,this.firstTimePlayed=!0,Array.isArray(e.source)?this.source=e.source:this.source=[e.source],this.id=e.id,this.loop=e.loop||!1,this.duration=e.duration||null,"function"==typeof e.onLoading?this.onLoading=e.onLoading:this.onLoading=null,"function"==typeof e.onPlaying?this.onPlaying=e.onPlaying:this.onPlaying=null,"function"==typeof e.onStarted?this.onStarted=e.onStarted:this.onStarted=null,"function"==typeof e.onEnded?this.onEnded=e.onEnded:this.onEnded=null,"function"==typeof e.onStopped?this.onStopped=e.onStopped:this.onStopped=null,"function"==typeof e.onPaused?this.onPaused=e.onPaused:this.onPaused=null,"function"==typeof e.onResumed?this.onResumed=e.onResumed:this.onResumed=null,"ArrayBuffer"===typeof e.arrayBuffer&&(this.arrayBuffer=e.arrayBuffer),"AudioBuffer"===typeof e.audioBuffer&&(this.audioBuffer=e.audioBuffer,this.isBuffering=!1,this.isBuffered=!0,this.audioBufferDate=new Date,this.duration=this.getDuration())}return e.prototype.getCurrentTime=function(){var e;return null!==this.audioBufferSourceNode?e=this.audioBufferSourceNode.context.currentTime:null!==this.mediaElementAudioSourceNode&&(e=this.audioElement.currentTime),e},e.prototype.getDuration=function(){var e;return null!==this.audioBufferSourceNode?e=this.audioBufferSourceNode.buffer.duration:null!==this.mediaElementAudioSourceNode&&(e=this.audioElement.duration),e},e.SOUND_STATE_STOPPED="sound_state_stopped",e.SOUND_STATE_PAUSED="sound_state_paused",e.SOUND_STATE_PLAYING="sound_state_playing",e}(),i=function(t){function o(e,n){var i=t.call(this,e)||this;return i.code=n||null,Object.setPrototypeOf(i,o.prototype),i}return function(t,o){if("function"!=typeof o&&null!==o)throw new TypeError("Class extends value "+String(o)+" is not a constructor or null");function n(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}(o,t),o}(Error),u=function(){function e(e){this._audioContext=null,this._audioGraph=null,this.setPersistVolume(e.persistVolume),this._setAutoCreateContextOnFirstTouch(e.createAudioContextOnFirstUserInteraction),this.setLoadPlayerMode(e.loadPlayerMode),this.setAudioContext(e.customAudioContext),null===e.customAudioContext&&this._autoCreateAudioContextOnFirstUserInteraction(),this._createAudioContextOnFirstUserInteraction||this.getAudioContext().catch((function(){throw new i("audio context setup failed")})),this.setAudioGraph(e.customAudioGraph)}return e.prototype.decodeAudio=function(e){return t(this,void 0,void 0,(function(){var t,n;return o(this,(function(o){switch(o.label){case 0:return[4,this.getAudioContext()];case 1:return t=o.sent(),n=t.decodeAudioData(e),[2,Promise.resolve(n)]}}))}))},e.prototype._createAudioContext=function(){var e=this;return new Promise((function(t,o){var n=window.AudioContext||window.webkitAudioContext;try{e._audioContext=new n,t()}catch(e){o(e)}}))},e.prototype._autoCreateAudioContextRemoveListener=function(){document.removeEventListener("touchstart",this._autoCreateAudioContextRemoveListener.bind(this),!1),document.removeEventListener("touchend",this._autoCreateAudioContextRemoveListener.bind(this),!1),document.removeEventListener("mousedown",this._autoCreateAudioContextRemoveListener.bind(this),!1),this.getAudioContext().catch((function(){throw new i("audio context setup failed")}))},e.prototype._autoCreateAudioContextOnFirstUserInteraction=function(){this._createAudioContextOnFirstUserInteraction&&(document.addEventListener("touchstart",this._autoCreateAudioContextRemoveListener.bind(this),!1),document.addEventListener("touchend",this._autoCreateAudioContextRemoveListener.bind(this),!1),document.addEventListener("mousedown",this._autoCreateAudioContextRemoveListener.bind(this),!1))},e.prototype.getAudioContext=function(){var e=this;return new Promise((function(t,o){null===e._audioContext?e._createAudioContext().then((function(){t(e._audioContext)})).catch(o):"suspended"===e._audioContext.state?e._unfreezeAudioContext().then((function(){t(e._audioContext)})):"running"===e._audioContext.state&&t(e._audioContext)}))},e.prototype.setAudioContext=function(e){var t=this;null!==this._audioContext?this._destroyAudioContext().then((function(){t._setAudioContext(e)})):this._setAudioContext(e)},e.prototype._setAudioContext=function(e){this._audioContext=e},e.prototype._destroyAudioContext=function(){return t(this,void 0,void 0,(function(){return o(this,(function(e){switch(e.label){case 0:return[4,this._audioContext.close()];case 1:return e.sent(),this._audioContext=null,[2]}}))}))},e.prototype._unfreezeAudioContext=function(){return void 0===this._audioContext.suspend?Promise.resolve():this._audioContext.resume()},e.prototype._freezeAudioContext=function(){return void 0===this._audioContext.suspend?Promise.resolve():this._audioContext.suspend()},e.prototype.setAudioGraph=function(e){var t=this;null!==this._audioGraph&&this._destroyAudioGraph(),null===e||"gainNode"in e&&null!==e.gainNode&&void 0!==e.gainNode?this._audioGraph=e:this.getAudioContext().then((function(o){e.gainNode=o.createGain(),t._audioGraph=e}))},e.prototype.getAudioGraph=function(){var e=this;return new Promise((function(t,o){null!==e._audioGraph?t(e._audioGraph):e._createAudioGraph().then((function(o){e._audioGraph=o,t(o)})).catch(o)}))},e.prototype._createAudioGraph=function(){var e=this;return new Promise((function(t,o){e.getAudioContext().then((function(o){e._audioGraph||(e._audioGraph={gainNode:o.createGain()}),e._audioGraph.gainNode.connect(o.destination);var n=e._volume/100;e._changeGainValue(n),t(e._audioGraph)})).catch(o)}))},e.prototype._destroyAudioGraph=function(){null!==this._audioGraph&&this._audioGraph.gainNode.disconnect(),this._audioGraph=null},e.prototype.createAudioBufferSourceNode=function(e,n){return t(this,void 0,void 0,(function(){var t,i,u=this;return o(this,(function(o){switch(o.label){case 0:return[4,this.getAudioContext()];case 1:return t=o.sent(),i=t.createBufferSource(),n.audioBufferSourceNode=i,i.loop=e.loop,i.onended=function(t){e.onEnded(t),u.destroySourceNode(n)},[2]}}))}))},e.prototype.createMediaElementSourceNode=function(e,n){return t(this,void 0,void 0,(function(){var t,u,r=this;return o(this,(function(o){switch(o.label){case 0:return[4,this.getAudioContext()];case 1:t=o.sent();try{u=t.createMediaElementSource(e.mediaElement)}catch(e){throw new i(e)}return n.mediaElementAudioSourceNode=u,u.mediaElement.loop=e.loop,u.mediaElement.onended=function(){e.onEnded(),r.destroySourceNode(n)},[2]}}))}))},e.prototype.connectSourceNodeToGraphNodes=function(e){this.getAudioGraph().then((function(t){e.connect(t.gainNode),"analyserNode"in t&&null!==t.analyserNode&&void 0!==t.analyserNode&&e.connect(t.analyserNode),"delayNode"in t&&null!==t.delayNode&&void 0!==t.delayNode&&e.connect(t.delayNode),"pannerNode"in t&&null!==t.pannerNode&&void 0!==t.pannerNode&&e.connect(t.pannerNode)}))},e.prototype.destroySourceNode=function(e){if(null!==e.audioBufferSourceNode)e.audioBufferSourceNode.disconnect();else{if(null===e.mediaElementAudioSourceNode)throw new i("can't destroy as no source node in sound");e.mediaElementAudioSourceNode.disconnect()}e.audioBufferSourceNode=null},e.prototype.changeVolume=function(e){var t=e.volume,o=e.sound,n=void 0===o?null:o,i=e.forceUpdateUserVolume,u=void 0===i||i;if(this._persistVolume){var r=parseInt(localStorage.getItem("WebAudioAPIPlayerVolume"));isNaN(r)||u?u&&localStorage.setItem("WebAudioAPIPlayerVolume",t.toString()):t=r}var s=t/100;return null!==n?n.audioElement.volume=s:this._changeGainValue(s),this._volume=t,t},e.prototype._changeGainValue=function(e){this.getAudioGraph().then((function(t){t.gainNode.gain.value=e}))},e.prototype._setAutoCreateContextOnFirstTouch=function(e){this._createAudioContextOnFirstUserInteraction=e},e.prototype.setPersistVolume=function(e){this._persistVolume=e},e.prototype.getPersistVolume=function(){return this._persistVolume},e.prototype.setLoadPlayerMode=function(e){this._loadPlayerMode=e},e.prototype.getLoadPlayerMode=function(){return this._loadPlayerMode},e}(),r=function(){function e(){}return e.prototype.getArrayBuffer=function(e){return new Promise((function(t,o){var n=new XMLHttpRequest;n.open("GET",e.url,!0),n.responseType="arraybuffer",n.onload=function(){200===n.status?t(n.response):o(new i(n.statusText,n.status))},n.onprogress=function(t){var o=100/(t.total/t.loaded);e.loadingProgress=o,null!==e.onLoading&&e.onLoading(o,t.total,t.loaded)},n.onerror=function(){o(new i("xhr network error"))},n.send()}))},e}(),s=function(){function e(e){void 0===e&&(e={}),this._playingTimeoutID=null,this._customAudioGraph=null,this._customAudioContext=null,this._postMuteVolume=null,this._isMuted=!1;var t={volume:80,loopQueue:!1,loopSong:!1,soundsBaseUrl:"",playingProgressIntervalTime:1e3,playNextOnEnded:!0,audioGraph:null,audioContext:null,stopOnReset:!0,visibilityAutoMute:!1,createAudioContextOnFirstUserInteraction:!0,persistVolume:!0,loadPlayerMode:"player_mode_audio"},o=Object.assign({},t,e);this._volume=o.volume,this._soundsBaseUrl=o.soundsBaseUrl,this._queue=[],this._currentIndex=0,this._playingProgressIntervalTime=o.playingProgressIntervalTime,this._playNextOnEnded=o.playNextOnEnded,this._loopQueue=o.loopQueue,this._loopSong=o.loopSong,this._stopOnReset=o.stopOnReset,this._visibilityAutoMute=o.visibilityAutoMute,this._createAudioContextOnFirstUserInteraction=o.createAudioContextOnFirstUserInteraction,this._persistVolume=o.persistVolume,this._loadPlayerMode=o.loadPlayerMode,void 0!==o.audioContext&&(this._customAudioContext=o.audioContext),void 0!==o.audioGraph&&(this._customAudioGraph=o.audioGraph),this._initialize()}return e.prototype._initialize=function(){var t;switch(this._loadPlayerMode){case e.PLAYER_MODE_AUDIO:if(!this._detectAudioContextSupport())throw new i("audio context is not supported by this device");t=this._webAudioApiOptions();break;case e.PLAYER_MODE_AJAX:if(!this._detectAudioElementSupport())throw new i("audio context is not supported by this device");t=this._webAudioElementOptions()}this._playerAudio=new u(t)},e.prototype._webAudioApiOptions=function(){return{customAudioContext:this._customAudioContext,customAudioGraph:this._customAudioGraph,createAudioContextOnFirstUserInteraction:this._createAudioContextOnFirstUserInteraction,persistVolume:this._persistVolume,loadPlayerMode:this._loadPlayerMode}},e.prototype._webAudioElementOptions=function(){return{customAudioContext:null,customAudioGraph:null,createAudioContextOnFirstUserInteraction:!1,persistVolume:this._persistVolume,loadPlayerMode:this._loadPlayerMode}},e.prototype._detectAudioContextSupport=function(){var e=!1;return(void 0!==window.webkitAudioContext||"undefined"!=typeof AudioContext)&&(e=!0),e},e.prototype._detectAudioElementSupport=function(){return!!document.createElement("audio").canPlayType},e.prototype.addSoundToQueue=function(t){var o=t.soundAttributes,i=t.whereInQueue,u=void 0===i?e.WHERE_IN_QUEUE_AT_END:i,r=new n(o);switch(u){case e.WHERE_IN_QUEUE_AT_END:this._appendSoundToQueue(r);break;case e.WHERE_IN_QUEUE_AT_START:case e.WHERE_IN_QUEUE_AFTER_CURRENT:this._prependSoundToQueue(r)}return r},e.prototype._appendSoundToQueue=function(e){this._queue.push(e)},e.prototype._prependSoundToQueue=function(e){this._queue.unshift(e)},e.prototype._addSoundToQueueAfterCurrent=function(e){if(null===this._currentIndex)this._appendSoundToQueue(e);else{var t=this._currentIndex+1;this._queue.splice(t,0,e)}},e.prototype.resetQueue=function(){this._stopOnReset&&this.stop(),this._queue=[]},e.prototype.reset=function(){this.resetQueue()},e.prototype.getQueue=function(){return this._queue},e.prototype.setVolume=function(e){this._volume=e,this._isMuted=!1;var t=this._getSoundFromQueue();null!==t&&t.state===n.SOUND_STATE_PLAYING&&this._playerAudio.changeVolume({volume:e,sound:t,forceUpdateUserVolume:!0})},e.prototype.getVolume=function(){return this._volume},e.prototype.mute=function(){var e=this.getVolume();this._postMuteVolume=e;var t=this._getSoundFromQueue();null!==t&&t.state===n.SOUND_STATE_PLAYING&&this._playerAudio.changeVolume({volume:0,sound:t,forceUpdateUserVolume:!1}),this._isMuted=!0},e.prototype.unMute=function(){var e=this._getSoundFromQueue();null!==e&&e.state===n.SOUND_STATE_PLAYING&&this._playerAudio.changeVolume({volume:this._postMuteVolume,sound:e,forceUpdateUserVolume:!1}),this._isMuted=!1},e.prototype.isMuted=function(){return this._isMuted},e.prototype.setPosition=function(e){var t=this,o=this._getSoundFromQueue();if(null===o)throw new i("position change called, but no current sound found");if(null===o.duration||isNaN(o.duration))this._loadSound(o).then((function(o){var n=o.duration/100*e;t.setPositionInSeconds(n)})).catch((function(e){throw e}));else{var n=o.duration/100*e;this.setPositionInSeconds(n)}},e.prototype.setPositionInSeconds=function(e){var t=this._getSoundFromQueue();if(null===t)throw new i("position change called, but no current sound found");t.state===n.SOUND_STATE_PLAYING?(this.pause(),this.play({whichSound:t.id,playTimeOffset:e})):t.playTimeOffset=e},e.prototype._loadSound=function(t){var o,n;switch(this._loadPlayerMode){case e.PLAYER_MODE_AUDIO:o=this._loadSoundUsingAudioElement(t);break;case e.PLAYER_MODE_AJAX:o=this._loadSoundUsingRequest(t);break;case e.PLAYER_MODE_FETCH:n=new i(e.PLAYER_MODE_FETCH+" is not implemented yet",1),o=Promise.reject(n)}return o},e.prototype._loadSoundUsingAudioElement=function(e){var t=this;return new Promise((function(o,n){var u,r,s=(u=t._findBestSource(e.source)).url,a=void 0===(r=u.codec)?null:r;if(e.url=s,e.codec=a,e.arrayBuffer=null,null!==e.url){var d=new Audio;d.crossOrigin="anonymous",d.src=e.url,d.controls=!1,d.autoplay=!1,document.body.appendChild(d),e.audioElement=d,e.duration=d.duration,e.isReadyToPLay=!0,t._initializeAudioElementListeners(e),e.audioElement.addEventListener("canplaythrough",(function(){o(e)})),e.audioElement.addEventListener("error",(function(){var e=new i("loading sound failed");n(e)}))}else{var l=new i("sound has no url",1);n(l)}}))},e.prototype._loadSoundUsingRequest=function(e){var t=this;return new Promise((function(o,n){var u,s;if(null!==e.audioBuffer&&o(e),null!==e.arrayBuffer&&null===e.audioBuffer&&t._decodeSound({sound:e}).then((function(e){o(e)})).catch(n),null===e.arrayBuffer&&null===e.audioBuffer){var a=(u=t._findBestSource(e.source)).url,d=void 0===(s=u.codec)?null:s;if(e.url=a,e.codec=d,null!==e.url){var l=new r;e.isBuffering=!0,l.getArrayBuffer(e).then((function(i){e.arrayBuffer=i,t._decodeSound({sound:e}).then((function(e){o(e)})).catch(n)})).catch((function(e){n(e)}))}else{var c=new i("sound has no url",1);n(c)}}}))},e.prototype._initializeAudioElementListeners=function(e){e.audioElement.addEventListener("progress",(function(){e.loadingProgress=e.audioElement.duration})),e.audioElement.addEventListener("timeupdate",(function(){e.duration=e.audioElement.duration}))},e.prototype._decodeSound=function(e){var t=e.sound,o=t.arrayBuffer;return this._playerAudio.decodeAudio(o).then((function(e){return t.audioBuffer=e,t.isBuffering=!1,t.isBuffered=!0,t.audioBufferDate=new Date,t.duration=t.audioBuffer.duration,t.isReadyToPLay=!0,t})).catch((function(e){throw e}))},e.prototype.play=function(e){var t=this,o=void 0===e?{}:e,i=o.whichSound,u=o.playTimeOffset;return new Promise((function(e,o){var r=t._getSoundFromQueue();null!==r&&r.state===n.SOUND_STATE_PLAYING&&t.stop();var s=t._getSoundFromQueue({whichSound:i});if(null===s)throw new Error("no more sounds in array");void 0!==u&&(s.playTimeOffset=u),s.isReadyToPLay?t._play(s).then(e).catch(o):t._loadSound(s).then((function(){t._play(s).then(e).catch(o)})).catch(o)}))},e.prototype._play=function(e){return t(this,void 0,void 0,(function(){var t;return o(this,(function(o){switch(o.label){case 0:return t=this._volume,this._isMuted&&(t=0),this._volume=this._playerAudio.changeVolume({volume:t,sound:e,forceUpdateUserVolume:!1}),null===e.audioBuffer?[3,2]:[4,this._playAudioBuffer(e)];case 1:return o.sent(),[3,4];case 2:return[4,this._playMediaElementAudio(e)];case 3:o.sent(),o.label=4;case 4:return e.state=n.SOUND_STATE_PLAYING,e.startTime=e.getCurrentTime(),e=this._setupSoundEvents(e),[2]}}))}))},e.prototype._playAudioBuffer=function(e){return t(this,void 0,void 0,(function(){var t,n,u,r=this;return o(this,(function(o){switch(o.label){case 0:if(null!==e.audioBufferSourceNode)return[3,4];t={loop:e.loop,onEnded:function(e){r._onEnded()}},o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this._playerAudio.createAudioBufferSourceNode(t,e)];case 2:return o.sent(),[3,4];case 3:throw n=o.sent(),new i(n);case 4:(u=e.audioBufferSourceNode).buffer=e.audioBuffer,this._playerAudio.connectSourceNodeToGraphNodes(u);try{void 0!==e.playTimeOffset?u.start(0,e.playTimeOffset):u.start()}catch(e){throw new i(e)}return[2]}}))}))},e.prototype._playMediaElementAudio=function(e){return t(this,void 0,void 0,(function(){var t,n,u,r=this;return o(this,(function(o){switch(o.label){case 0:if(null!==e.mediaElementAudioSourceNode)return[3,4];t={loop:e.loop,onEnded:function(e){r._onEnded()},mediaElement:e.audioElement},o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this._playerAudio.createMediaElementSourceNode(t,e)];case 2:return o.sent(),[3,4];case 3:throw n=o.sent(),new i(n);case 4:u=e.mediaElementAudioSourceNode,this._playerAudio.connectSourceNodeToGraphNodes(u),void 0===e.playTimeOffset||isNaN(e.playTimeOffset)||(e.audioElement.currentTime=e.playTimeOffset);try{u.mediaElement.play()}catch(e){throw new i(e)}return[2]}}))}))},e.prototype._setupSoundEvents=function(e){var t=this;return null===e.onResumed||e.firstTimePlayed||e.onResumed(e.playTimeOffset),null!==e.onStarted&&e.firstTimePlayed&&(e.onStarted(e.playTimeOffset),e.firstTimePlayed=!1),null!==e.onPlaying?this._playingTimeoutID=window.setInterval((function(){t._playingProgress(e)}),this._playingProgressIntervalTime):this._playingTimeoutID=null,e},e.prototype._onEnded=function(){var e=this._getSoundFromQueue();if(null!==e&&e.state===n.SOUND_STATE_PLAYING){var t=this._getSoundFromQueue({whichSound:"next",updateIndex:!1});if(null!==e.onEnded){var o=!1;null!==t&&this._playNextOnEnded&&(o=!0),e.onEnded(o)}e.firstTimePlayed=!0,e.playTimeOffset=0,this._stop(e,n.SOUND_STATE_STOPPED),null!==t?this._playNextOnEnded&&this.play({whichSound:"next"}):(this._currentIndex=0,this._loopQueue&&this.play())}},e.prototype._getSoundFromQueue=function(t){var o=void 0===t?{}:t,n=o.whichSound,i=o.updateIndex,u=void 0===i||i,r=null;if(0===this._queue.length)return r;if(void 0===n&&void 0!==this._queue[this._currentIndex])r=this._queue[this._currentIndex];else if("number"==typeof n)r=this._findSoundById({soundId:n,updateIndex:u});else{var s=null;switch(n){case e.PLAY_SOUND_NEXT:void 0!==this._queue[this._currentIndex+1]&&(s=this._currentIndex+1,r=this._queue[s]);break;case e.PLAY_SOUND_PREVIOUS:void 0!==this._queue[this._currentIndex-1]&&(s=this._currentIndex-1,r=this._queue[s]);break;case e.PLAY_SOUND_FIRST:this._queue.length>0&&(s=0,r=this._queue[s]);break;case e.PLAY_SOUND_LAST:this._queue.length>0&&(s=this._queue.length-2,r=this._queue[s]);break;default:r=this._findSoundById({soundId:n,updateIndex:u})}null!==s&&u&&(this._currentIndex=s)}return r},e.prototype._findSoundById=function(e){var t=this,o=e.soundId,n=e.updateIndex,i=null;return this._queue.some((function(e,u){if(e.id===o)return i=e,n&&(t._currentIndex=u),!0})),i},e.prototype._findBestSource=function(e){var t=this,o={url:null,codec:null};return(Array.isArray(e)?e:[e]).forEach((function(e){var n="";""!==t._soundsBaseUrl&&(n=t._soundsBaseUrl),n+=e.url;var i=!0;null!==e.codec&&(i=t._checkCodecSupport(e.codec)),i&&(null!==o.url&&e.isPreferred,o.url=n,o.codec=e.codec)})),o},e.prototype._checkCodecSupport=function(e){var t,o="";switch(e){case"ogg":case"oga":t=['audio/ogg; codecs="vorbis"'];break;case"mp3":t=['audio/mpeg; codecs="mp3"'];break;case"opus":t=['audio/ogg; codecs="opus"','audio/webm; codecs="opus"'];break;case"wav":t=['audio/wav; codecs="1"'];break;case"m4a":t=["audio/m4a;","audio/x-m4a;"];break;case"m4p":t=["audio/m4p;","audio/x-m4p;"];break;case"caf":t=["audio/x-caf;"];break;case"aac":t=["audio/aac;"];break;case"weba":case"webm":t=['audio/webm; codecs="vorbis"'];break;case"flac":t=["audio/flac;","audio/x-flac;"];break;default:o="unrecognised codec"}if(o)throw new i(o);return this._checkMimeTypesSupport(t)},e.prototype._checkMimeTypesSupport=function(e){var t=new Audio,o=!1;return e.forEach((function(e){t.canPlayType(e).replace(/^no$/,"")&&(o=!0)})),o},e.prototype.pause=function(){var e=this._getSoundFromQueue();if(null!==e&&e.state!==n.SOUND_STATE_PAUSED){var t=e.getCurrentTime();e.playTimeOffset+=t-e.startTime,null!==e.onPaused&&e.onPaused(e.playTimeOffset),this._stop(e,n.SOUND_STATE_PAUSED)}},e.prototype.stop=function(){var e=this._getSoundFromQueue();null!==e&&e.state!==n.SOUND_STATE_STOPPED&&(e.firstTimePlayed=!0,null!==e.onStopped&&e.onStopped(e.playTimeOffset),e.playTimeOffset=0,this._stop(e,n.SOUND_STATE_STOPPED))},e.prototype._stop=function(e,t){if(null!==e.audioBufferSourceNode)e.audioBufferSourceNode.stop(0);else{if(null===e.mediaElementAudioSourceNode)throw new i("can't stop as no source node in sound");e.mediaElementAudioSourceNode.mediaElement.pause()}this._playerAudio.destroySourceNode(e),e.state=t,null!==this._playingTimeoutID&&clearInterval(this._playingTimeoutID)},e.prototype.next=function(){this.play({whichSound:"next"})},e.prototype.previous=function(){this.play({whichSound:"previous"})},e.prototype.first=function(){this.play({whichSound:"first"})},e.prototype.last=function(){this.play({whichSound:"last"})},e.prototype._playingProgress=function(e){var t=e.getCurrentTime();e.playTime=t-e.startTime+e.playTimeOffset;var o=e.getDuration(),n=e.playTime/o*100;e.playedTimePercentage=n,e.onPlaying(n,o,e.playTime)},e.prototype.setAudioGraph=function(e){this._playerAudio.setAudioGraph(e),this._customAudioGraph=e},e.prototype.getAudioGraph=function(){var e=this;return new Promise((function(t,o){e._playerAudio.getAudioGraph().then((function(o){e._customAudioGraph=o,t(o)})).catch(o)}))},e.prototype.setAudioContext=function(e){this._playerAudio.setAudioContext(e),this._customAudioContext=e},e.prototype.getAudioContext=function(){var e=this;return new Promise((function(t,o){e._playerAudio.getAudioContext().then((function(o){e._customAudioContext=o,t(o)})).catch(o)}))},e.prototype.setVisibilityAutoMute=function(e){this._visibilityAutoMute=e,e?document.addEventListener("visibilitychange",this._handleVisibilityChange.bind(this),!1):document.removeEventListener("visibilitychange",this._handleVisibilityChange.bind(this),!1)},e.prototype.getVisibilityAutoMute=function(){return this._visibilityAutoMute},e.prototype._handleVisibilityChange=function(){var e;void 0!==document.hidden?e="hidden":void 0!==document.msHidden?e="msHidden":void 0!==document.webkitHidden&&(e="webkitHidden"),document[e]?this.mute():this.unMute()},e.WHERE_IN_QUEUE_AT_END="append",e.WHERE_IN_QUEUE_AT_START="prepend",e.WHERE_IN_QUEUE_AFTER_CURRENT="afterCurrent",e.PLAY_SOUND_NEXT="next",e.PLAY_SOUND_PREVIOUS="previous",e.PLAY_SOUND_FIRST="first",e.PLAY_SOUND_LAST="last",e.PLAYER_MODE_AUDIO="player_mode_audio",e.PLAYER_MODE_AJAX="player_mode_ajax",e.PLAYER_MODE_FETCH="player_mode_fetch",e}();export{s as PlayerCore,n as PlayerSound};
var e=function(t,o){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])},e(t,o)};function t(e,t,o,n){return new(o||(o=Promise))((function(i,u){function r(e){try{a(n.next(e))}catch(e){u(e)}}function s(e){try{a(n.throw(e))}catch(e){u(e)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(r,s)}a((n=n.apply(e,t||[])).next())}))}function o(e,t){var o,n,i,u,r={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return u={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function s(s){return function(a){return function(s){if(o)throw new TypeError("Generator is already executing.");for(;u&&(u=0,s[0]&&(r=0)),r;)try{if(o=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return r.label++,{value:s[1],done:!1};case 5:r.label++,n=s[1],s=[0];continue;case 7:s=r.ops.pop(),r.trys.pop();continue;default:if(!(i=r.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){r=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){r.label=s[1];break}if(6===s[0]&&r.label<i[1]){r.label=i[1],i=s;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(s);break}i[2]&&r.ops.pop(),r.trys.pop();continue}s=t.call(e,r)}catch(e){s=[6,e],n=0}finally{o=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}}var n=function(){function e(e){this.url=null,this.codec=null,this.audioBufferSourceNode=null,this.mediaElementAudioSourceNode=null,this.isReadyToPLay=!1,this.isBuffered=!1,this.isBuffering=!1,this.audioElement=null,this.audioBuffer=null,this.arrayBuffer=null,this.audioBufferDate=null,this.playTimeOffset=0,this.startTime=0,this.playTime=0,this.playedTimePercentage=0,this.state="sound_state_stopped",this.loadingProgress=0,this.duration=null,this.firstTimePlayed=!0,Array.isArray(e.source)?this.source=e.source:this.source=[e.source],this.id=e.id,this.loop=e.loop||!1,this.duration=e.duration||null,"function"==typeof e.onLoading?this.onLoading=e.onLoading:this.onLoading=null,"function"==typeof e.onPlaying?this.onPlaying=e.onPlaying:this.onPlaying=null,"function"==typeof e.onStarted?this.onStarted=e.onStarted:this.onStarted=null,"function"==typeof e.onEnded?this.onEnded=e.onEnded:this.onEnded=null,"function"==typeof e.onStopped?this.onStopped=e.onStopped:this.onStopped=null,"function"==typeof e.onPaused?this.onPaused=e.onPaused:this.onPaused=null,"function"==typeof e.onResumed?this.onResumed=e.onResumed:this.onResumed=null,"ArrayBuffer"===typeof e.arrayBuffer&&(this.arrayBuffer=e.arrayBuffer),"AudioBuffer"===typeof e.audioBuffer&&(this.audioBuffer=e.audioBuffer,this.isBuffering=!1,this.isBuffered=!0,this.audioBufferDate=new Date,this.duration=this.getDuration())}return e.prototype.getCurrentTime=function(){var e;return null!==this.audioBufferSourceNode?e=this.audioBufferSourceNode.context.currentTime:null!==this.mediaElementAudioSourceNode&&(e=this.audioElement.currentTime),e},e.prototype.getDuration=function(){var e;return null!==this.audioBufferSourceNode?e=this.audioBufferSourceNode.buffer.duration:null!==this.mediaElementAudioSourceNode&&(e=this.audioElement.duration),e},e.SOUND_STATE_STOPPED="sound_state_stopped",e.SOUND_STATE_PAUSED="sound_state_paused",e.SOUND_STATE_PLAYING="sound_state_playing",e}(),i=function(t){function o(e,n){var i=t.call(this,e)||this;return i.code=n||null,Object.setPrototypeOf(i,o.prototype),i}return function(t,o){if("function"!=typeof o&&null!==o)throw new TypeError("Class extends value "+String(o)+" is not a constructor or null");function n(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}(o,t),o}(Error),u=function(){function e(e){this._audioContext=null,this._audioGraph=null,this.setPersistVolume(e.persistVolume),this._setAutoCreateContextOnFirstTouch(e.createAudioContextOnFirstUserInteraction),this.setLoadPlayerMode(e.loadPlayerMode),this.setAudioContext(e.customAudioContext),null===e.customAudioContext&&this._autoCreateAudioContextOnFirstUserInteraction(),this._createAudioContextOnFirstUserInteraction||this.getAudioContext().catch((function(){throw new i("audio context setup failed")})),this.setAudioGraph(e.customAudioGraph)}return e.prototype.decodeAudio=function(e){return t(this,void 0,void 0,(function(){var t,n;return o(this,(function(o){switch(o.label){case 0:return[4,this.getAudioContext()];case 1:return t=o.sent(),n=t.decodeAudioData(e),[2,Promise.resolve(n)]}}))}))},e.prototype._createAudioContext=function(){var e=this;return new Promise((function(t,o){var n=window.AudioContext||window.webkitAudioContext;try{e._audioContext=new n,t()}catch(e){o(e)}}))},e.prototype._autoCreateAudioContextRemoveListener=function(){document.removeEventListener("touchstart",this._autoCreateAudioContextRemoveListener.bind(this),!1),document.removeEventListener("touchend",this._autoCreateAudioContextRemoveListener.bind(this),!1),document.removeEventListener("mousedown",this._autoCreateAudioContextRemoveListener.bind(this),!1),this.getAudioContext().catch((function(){throw new i("audio context setup failed")}))},e.prototype._autoCreateAudioContextOnFirstUserInteraction=function(){this._createAudioContextOnFirstUserInteraction&&(document.addEventListener("touchstart",this._autoCreateAudioContextRemoveListener.bind(this),!1),document.addEventListener("touchend",this._autoCreateAudioContextRemoveListener.bind(this),!1),document.addEventListener("mousedown",this._autoCreateAudioContextRemoveListener.bind(this),!1))},e.prototype.getAudioContext=function(){var e=this;return new Promise((function(t,o){null===e._audioContext?e._createAudioContext().then((function(){t(e._audioContext)})).catch(o):"suspended"===e._audioContext.state?e._unfreezeAudioContext().then((function(){t(e._audioContext)})):"running"===e._audioContext.state&&t(e._audioContext)}))},e.prototype.setAudioContext=function(e){var t=this;null!==this._audioContext?this._destroyAudioContext().then((function(){t._setAudioContext(e)})):this._setAudioContext(e)},e.prototype._setAudioContext=function(e){this._audioContext=e},e.prototype._destroyAudioContext=function(){return t(this,void 0,void 0,(function(){return o(this,(function(e){switch(e.label){case 0:return[4,this._audioContext.close()];case 1:return e.sent(),this._audioContext=null,[2]}}))}))},e.prototype._unfreezeAudioContext=function(){return void 0===this._audioContext.suspend?Promise.resolve():this._audioContext.resume()},e.prototype._freezeAudioContext=function(){return void 0===this._audioContext.suspend?Promise.resolve():this._audioContext.suspend()},e.prototype.setAudioGraph=function(e){var t=this;null!==this._audioGraph&&this._destroyAudioGraph(),null===e||"gainNode"in e&&null!==e.gainNode&&void 0!==e.gainNode?this._audioGraph=e:this.getAudioContext().then((function(o){e.gainNode=o.createGain(),t._audioGraph=e}))},e.prototype.getAudioGraph=function(){var e=this;return new Promise((function(t,o){null!==e._audioGraph?t(e._audioGraph):e._createAudioGraph().then((function(o){e._audioGraph=o,t(o)})).catch(o)}))},e.prototype._createAudioGraph=function(){var e=this;return new Promise((function(t,o){e.getAudioContext().then((function(o){e._audioGraph||(e._audioGraph={gainNode:o.createGain()}),e._audioGraph.gainNode.connect(o.destination);var n=e._volume/100;e._changeGainValue(n),t(e._audioGraph)})).catch(o)}))},e.prototype._destroyAudioGraph=function(){null!==this._audioGraph&&this._audioGraph.gainNode.disconnect(),this._audioGraph=null},e.prototype.createAudioBufferSourceNode=function(e,n){return t(this,void 0,void 0,(function(){var t,i,u=this;return o(this,(function(o){switch(o.label){case 0:return[4,this.getAudioContext()];case 1:return t=o.sent(),i=t.createBufferSource(),n.audioBufferSourceNode=i,i.loop=e.loop,i.onended=function(t){e.onEnded(t),u.destroySourceNode(n)},[2]}}))}))},e.prototype.createMediaElementSourceNode=function(e,n){return t(this,void 0,void 0,(function(){var t,u,r=this;return o(this,(function(o){switch(o.label){case 0:return[4,this.getAudioContext()];case 1:t=o.sent();try{u=t.createMediaElementSource(e.mediaElement)}catch(e){throw new i(e)}return n.mediaElementAudioSourceNode=u,u.mediaElement.loop=e.loop,u.mediaElement.onended=function(){e.onEnded(),r.destroySourceNode(n)},[2]}}))}))},e.prototype.connectSourceNodeToGraphNodes=function(e){this.getAudioGraph().then((function(t){e.connect(t.gainNode),"analyserNode"in t&&null!==t.analyserNode&&void 0!==t.analyserNode&&e.connect(t.analyserNode),"delayNode"in t&&null!==t.delayNode&&void 0!==t.delayNode&&e.connect(t.delayNode),"pannerNode"in t&&null!==t.pannerNode&&void 0!==t.pannerNode&&e.connect(t.pannerNode)}))},e.prototype.destroySourceNode=function(e){if(null!==e.audioBufferSourceNode)e.audioBufferSourceNode.disconnect();else{if(null===e.mediaElementAudioSourceNode)throw new i("can't destroy as no source node in sound");e.mediaElementAudioSourceNode.disconnect()}e.audioBufferSourceNode=null},e.prototype.changeVolume=function(e){var t=e.volume,o=e.sound,n=void 0===o?null:o,i=e.forceUpdateUserVolume,u=void 0===i||i;if(this._persistVolume){var r=parseInt(localStorage.getItem("WebAudioAPIPlayerVolume"));isNaN(r)||u?u&&localStorage.setItem("WebAudioAPIPlayerVolume",t.toString()):t=r}var s=t/100;return null!==n?n.audioElement.volume=s:this._changeGainValue(s),this._volume=t,t},e.prototype._changeGainValue=function(e){this.getAudioGraph().then((function(t){t.gainNode.gain.value=e}))},e.prototype._setAutoCreateContextOnFirstTouch=function(e){this._createAudioContextOnFirstUserInteraction=e},e.prototype.setPersistVolume=function(e){this._persistVolume=e},e.prototype.getPersistVolume=function(){return this._persistVolume},e.prototype.setLoadPlayerMode=function(e){this._loadPlayerMode=e},e.prototype.getLoadPlayerMode=function(){return this._loadPlayerMode},e}(),r=function(){function e(){}return e.prototype.getArrayBuffer=function(e){return new Promise((function(t,o){var n=new XMLHttpRequest;n.open("GET",e.url,!0),n.responseType="arraybuffer",n.onload=function(){200===n.status?t(n.response):o(new i(n.statusText,n.status))},n.onprogress=function(t){var o=100/(t.total/t.loaded);e.loadingProgress=o,null!==e.onLoading&&e.onLoading(o,t.total,t.loaded)},n.onerror=function(){o(new i("xhr network error"))},n.send()}))},e}(),s=function(){function e(e){void 0===e&&(e={});var t=this;this._playingProgressRequestId=null,this._playingProgressPreviousTimestamp=0,this._customAudioGraph=null,this._customAudioContext=null,this._postMuteVolume=null,this._isMuted=!1,this._progressTrigger=function(e,o){o-t._playingProgressPreviousTimestamp>=t._playingProgressIntervalTime&&(t._playingProgress(e),t._playingProgressPreviousTimestamp=o),t._playingProgressRequestId=window.requestAnimationFrame((function(o){t._progressTrigger(e,o)}))};var o={volume:80,loopQueue:!1,loopSong:!1,soundsBaseUrl:"",playingProgressIntervalTime:200,playNextOnEnded:!0,audioGraph:null,audioContext:null,stopOnReset:!0,visibilityAutoMute:!1,createAudioContextOnFirstUserInteraction:!0,persistVolume:!0,loadPlayerMode:"player_mode_audio"},n=Object.assign({},o,e);this._volume=n.volume,this._soundsBaseUrl=n.soundsBaseUrl,this._queue=[],this._currentIndex=0,this._playingProgressIntervalTime=n.playingProgressIntervalTime,this._playNextOnEnded=n.playNextOnEnded,this._loopQueue=n.loopQueue,this._loopSong=n.loopSong,this._stopOnReset=n.stopOnReset,this._visibilityAutoMute=n.visibilityAutoMute,this._createAudioContextOnFirstUserInteraction=n.createAudioContextOnFirstUserInteraction,this._persistVolume=n.persistVolume,this._loadPlayerMode=n.loadPlayerMode,void 0!==n.audioContext&&(this._customAudioContext=n.audioContext),void 0!==n.audioGraph&&(this._customAudioGraph=n.audioGraph),this._initialize()}return e.prototype._initialize=function(){var t;switch(this._loadPlayerMode){case e.PLAYER_MODE_AUDIO:if(!this._detectAudioContextSupport())throw new i("audio context is not supported by this device");t=this._webAudioApiOptions();break;case e.PLAYER_MODE_AJAX:if(!this._detectAudioElementSupport())throw new i("audio context is not supported by this device");t=this._webAudioElementOptions()}this._playerAudio=new u(t)},e.prototype._webAudioApiOptions=function(){return{customAudioContext:this._customAudioContext,customAudioGraph:this._customAudioGraph,createAudioContextOnFirstUserInteraction:this._createAudioContextOnFirstUserInteraction,persistVolume:this._persistVolume,loadPlayerMode:this._loadPlayerMode}},e.prototype._webAudioElementOptions=function(){return{customAudioContext:null,customAudioGraph:null,createAudioContextOnFirstUserInteraction:!1,persistVolume:this._persistVolume,loadPlayerMode:this._loadPlayerMode}},e.prototype._detectAudioContextSupport=function(){var e=!1;return(void 0!==window.webkitAudioContext||"undefined"!=typeof AudioContext)&&(e=!0),e},e.prototype._detectAudioElementSupport=function(){return!!document.createElement("audio").canPlayType},e.prototype.addSoundToQueue=function(t){var o=t.soundAttributes,i=t.whereInQueue,u=void 0===i?e.WHERE_IN_QUEUE_AT_END:i,r=new n(o);switch(u){case e.WHERE_IN_QUEUE_AT_END:this._appendSoundToQueue(r);break;case e.WHERE_IN_QUEUE_AT_START:case e.WHERE_IN_QUEUE_AFTER_CURRENT:this._prependSoundToQueue(r)}return r},e.prototype._appendSoundToQueue=function(e){this._queue.push(e)},e.prototype._prependSoundToQueue=function(e){this._queue.unshift(e)},e.prototype._addSoundToQueueAfterCurrent=function(e){if(null===this._currentIndex)this._appendSoundToQueue(e);else{var t=this._currentIndex+1;this._queue.splice(t,0,e)}},e.prototype.resetQueue=function(){this._stopOnReset&&this.stop(),this._queue=[]},e.prototype.reset=function(){this.resetQueue()},e.prototype.getQueue=function(){return this._queue},e.prototype.setVolume=function(e){this._volume=e,this._isMuted=!1;var t=this._getSoundFromQueue();null!==t&&t.state===n.SOUND_STATE_PLAYING&&this._playerAudio.changeVolume({volume:e,sound:t,forceUpdateUserVolume:!0})},e.prototype.getVolume=function(){return this._volume},e.prototype.mute=function(){var e=this.getVolume();this._postMuteVolume=e;var t=this._getSoundFromQueue();null!==t&&t.state===n.SOUND_STATE_PLAYING&&this._playerAudio.changeVolume({volume:0,sound:t,forceUpdateUserVolume:!1}),this._isMuted=!0},e.prototype.unMute=function(){var e=this._getSoundFromQueue();null!==e&&e.state===n.SOUND_STATE_PLAYING&&this._playerAudio.changeVolume({volume:this._postMuteVolume,sound:e,forceUpdateUserVolume:!1}),this._isMuted=!1},e.prototype.isMuted=function(){return this._isMuted},e.prototype.setPosition=function(e){var t=this,o=this._getSoundFromQueue();if(null===o)throw new i("position change called, but no current sound found");if(null===o.duration||isNaN(o.duration))this._loadSound(o).then((function(o){var n=o.duration/100*e;t.setPositionInSeconds(n)})).catch((function(e){throw e}));else{var n=o.duration/100*e;this.setPositionInSeconds(n)}},e.prototype.setPositionInSeconds=function(e){var t=this._getSoundFromQueue();if(null===t)throw new i("position change called, but no current sound found");t.state===n.SOUND_STATE_PLAYING?(this.pause(),this.play({whichSound:t.id,playTimeOffset:e})):t.playTimeOffset=e},e.prototype._loadSound=function(t){var o,n;switch(this._loadPlayerMode){case e.PLAYER_MODE_AUDIO:o=this._loadSoundUsingAudioElement(t);break;case e.PLAYER_MODE_AJAX:o=this._loadSoundUsingRequest(t);break;case e.PLAYER_MODE_FETCH:n=new i(e.PLAYER_MODE_FETCH+" is not implemented yet",1),o=Promise.reject(n)}return o},e.prototype._loadSoundUsingAudioElement=function(e){var t=this;return new Promise((function(o,n){var u,r,s=(u=t._findBestSource(e.source)).url,a=void 0===(r=u.codec)?null:r;if(e.url=s,e.codec=a,e.arrayBuffer=null,null!==e.url){var d=new Audio;d.crossOrigin="anonymous",d.src=e.url,d.controls=!1,d.autoplay=!1,document.body.appendChild(d),e.audioElement=d,e.duration=d.duration,e.isReadyToPLay=!0,t._initializeAudioElementListeners(e),e.audioElement.addEventListener("canplaythrough",(function(){o(e)})),e.audioElement.addEventListener("error",(function(){var e=new i("loading sound failed");n(e)}))}else{var l=new i("sound has no url",1);n(l)}}))},e.prototype._loadSoundUsingRequest=function(e){var t=this;return new Promise((function(o,n){var u,s;if(null!==e.audioBuffer&&o(e),null!==e.arrayBuffer&&null===e.audioBuffer&&t._decodeSound({sound:e}).then((function(e){o(e)})).catch(n),null===e.arrayBuffer&&null===e.audioBuffer){var a=(u=t._findBestSource(e.source)).url,d=void 0===(s=u.codec)?null:s;if(e.url=a,e.codec=d,null!==e.url){var l=new r;e.isBuffering=!0,l.getArrayBuffer(e).then((function(i){e.arrayBuffer=i,t._decodeSound({sound:e}).then((function(e){o(e)})).catch(n)})).catch((function(e){n(e)}))}else{var c=new i("sound has no url",1);n(c)}}}))},e.prototype._initializeAudioElementListeners=function(e){e.audioElement.addEventListener("progress",(function(){e.loadingProgress=e.audioElement.duration})),e.audioElement.addEventListener("timeupdate",(function(){e.duration=e.audioElement.duration}))},e.prototype._decodeSound=function(e){var t=e.sound,o=t.arrayBuffer;return this._playerAudio.decodeAudio(o).then((function(e){return t.audioBuffer=e,t.isBuffering=!1,t.isBuffered=!0,t.audioBufferDate=new Date,t.duration=t.audioBuffer.duration,t.isReadyToPLay=!0,t})).catch((function(e){throw e}))},e.prototype.play=function(e){var t=this,o=void 0===e?{}:e,i=o.whichSound,u=o.playTimeOffset;return new Promise((function(e,o){var r=t._getSoundFromQueue();null!==r&&r.state===n.SOUND_STATE_PLAYING&&t.stop();var s=t._getSoundFromQueue({whichSound:i});if(null===s)throw new Error("no more sounds in array");void 0!==u&&(s.playTimeOffset=u),s.isReadyToPLay?t._play(s).then(e).catch(o):t._loadSound(s).then((function(){t._play(s).then(e).catch(o)})).catch(o)}))},e.prototype._play=function(e){return t(this,void 0,void 0,(function(){var t;return o(this,(function(o){switch(o.label){case 0:return t=this._volume,this._isMuted&&(t=0),this._volume=this._playerAudio.changeVolume({volume:t,sound:e,forceUpdateUserVolume:!1}),null===e.audioBuffer?[3,2]:[4,this._playAudioBuffer(e)];case 1:return o.sent(),[3,4];case 2:return[4,this._playMediaElementAudio(e)];case 3:o.sent(),o.label=4;case 4:return e.state=n.SOUND_STATE_PLAYING,e.startTime=e.getCurrentTime(),e=this._setupSoundEvents(e),[2]}}))}))},e.prototype._playAudioBuffer=function(e){return t(this,void 0,void 0,(function(){var t,n,u,r=this;return o(this,(function(o){switch(o.label){case 0:if(null!==e.audioBufferSourceNode)return[3,4];t={loop:e.loop,onEnded:function(){r._onEnded()}},o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this._playerAudio.createAudioBufferSourceNode(t,e)];case 2:return o.sent(),[3,4];case 3:throw n=o.sent(),new i(n);case 4:(u=e.audioBufferSourceNode).buffer=e.audioBuffer,this._playerAudio.connectSourceNodeToGraphNodes(u);try{void 0!==e.playTimeOffset?u.start(0,e.playTimeOffset):u.start()}catch(e){throw new i(e)}return[2]}}))}))},e.prototype._playMediaElementAudio=function(e){return t(this,void 0,void 0,(function(){var t,n,u,r=this;return o(this,(function(o){switch(o.label){case 0:if(null!==e.mediaElementAudioSourceNode)return[3,4];t={loop:e.loop,onEnded:function(){r._onEnded()},mediaElement:e.audioElement},o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this._playerAudio.createMediaElementSourceNode(t,e)];case 2:return o.sent(),[3,4];case 3:throw n=o.sent(),new i(n);case 4:u=e.mediaElementAudioSourceNode,this._playerAudio.connectSourceNodeToGraphNodes(u),void 0===e.playTimeOffset||isNaN(e.playTimeOffset)||(e.audioElement.currentTime=e.playTimeOffset);try{u.mediaElement.play()}catch(e){throw new i(e)}return[2]}}))}))},e.prototype._setupSoundEvents=function(e){var t=this;return null===e.onResumed||e.firstTimePlayed||e.onResumed(e.playTimeOffset),null!==e.onStarted&&e.firstTimePlayed&&(e.onStarted(e.playTimeOffset),e.firstTimePlayed=!1),null!==e.onPlaying?this._playingProgressRequestId=window.requestAnimationFrame((function(o){t._progressTrigger(e,o)})):this._playingProgressRequestId=null,e},e.prototype._onEnded=function(){var e=this._getSoundFromQueue();if(null!==e&&e.state===n.SOUND_STATE_PLAYING){var t=this._getSoundFromQueue({whichSound:"next",updateIndex:!1});if(null!==e.onEnded){var o=!1;null!==t&&this._playNextOnEnded&&(o=!0),e.onEnded(o)}e.firstTimePlayed=!0,e.playTimeOffset=0,this._stop(e,n.SOUND_STATE_STOPPED),null!==t?this._playNextOnEnded&&this.play({whichSound:"next"}):(this._currentIndex=0,this._loopQueue&&this.play())}},e.prototype._getSoundFromQueue=function(t){var o=void 0===t?{}:t,n=o.whichSound,i=o.updateIndex,u=void 0===i||i,r=null;if(0===this._queue.length)return r;if(void 0===n&&void 0!==this._queue[this._currentIndex])r=this._queue[this._currentIndex];else if("number"==typeof n)r=this._findSoundById({soundId:n,updateIndex:u});else{var s=null;switch(n){case e.PLAY_SOUND_NEXT:void 0!==this._queue[this._currentIndex+1]&&(s=this._currentIndex+1,r=this._queue[s]);break;case e.PLAY_SOUND_PREVIOUS:void 0!==this._queue[this._currentIndex-1]&&(s=this._currentIndex-1,r=this._queue[s]);break;case e.PLAY_SOUND_FIRST:this._queue.length>0&&(s=0,r=this._queue[s]);break;case e.PLAY_SOUND_LAST:this._queue.length>0&&(s=this._queue.length-2,r=this._queue[s]);break;default:r=this._findSoundById({soundId:n,updateIndex:u})}null!==s&&u&&(this._currentIndex=s)}return r},e.prototype._findSoundById=function(e){var t=this,o=e.soundId,n=e.updateIndex,i=null;return this._queue.some((function(e,u){if(e.id===o)return i=e,n&&(t._currentIndex=u),!0})),i},e.prototype._findBestSource=function(e){var t=this,o={url:null,codec:null};return(Array.isArray(e)?e:[e]).forEach((function(e){var n="";""!==t._soundsBaseUrl&&(n=t._soundsBaseUrl),n+=e.url;var i=!0;null!==e.codec&&(i=t._checkCodecSupport(e.codec)),i&&(null!==o.url&&e.isPreferred,o.url=n,o.codec=e.codec)})),o},e.prototype._checkCodecSupport=function(e){var t,o="";switch(e){case"ogg":case"oga":t=['audio/ogg; codecs="vorbis"'];break;case"mp3":t=['audio/mpeg; codecs="mp3"'];break;case"opus":t=['audio/ogg; codecs="opus"','audio/webm; codecs="opus"'];break;case"wav":t=['audio/wav; codecs="1"'];break;case"m4a":t=["audio/m4a;","audio/x-m4a;"];break;case"m4p":t=["audio/m4p;","audio/x-m4p;"];break;case"caf":t=["audio/x-caf;"];break;case"aac":t=["audio/aac;"];break;case"weba":case"webm":t=['audio/webm; codecs="vorbis"'];break;case"flac":t=["audio/flac;","audio/x-flac;"];break;default:o="unrecognised codec"}if(o)throw new i(o);return this._checkMimeTypesSupport(t)},e.prototype._checkMimeTypesSupport=function(e){var t=new Audio,o=!1;return e.forEach((function(e){t.canPlayType(e).replace(/^no$/,"")&&(o=!0)})),o},e.prototype.pause=function(){var e=this._getSoundFromQueue();if(null!==e&&e.state!==n.SOUND_STATE_PAUSED){var t=e.getCurrentTime();e.playTimeOffset+=t-e.startTime,null!==e.onPaused&&e.onPaused(e.playTimeOffset),this._stop(e,n.SOUND_STATE_PAUSED)}},e.prototype.stop=function(){var e=this._getSoundFromQueue();null!==e&&e.state!==n.SOUND_STATE_STOPPED&&(e.firstTimePlayed=!0,null!==e.onStopped&&e.onStopped(e.playTimeOffset),e.playTimeOffset=0,this._stop(e,n.SOUND_STATE_STOPPED))},e.prototype._stop=function(e,t){if(null!==e.audioBufferSourceNode)e.audioBufferSourceNode.stop(0);else{if(null===e.mediaElementAudioSourceNode)throw new i("can't stop as no source node in sound");e.mediaElementAudioSourceNode.mediaElement.pause()}this._playerAudio.destroySourceNode(e),e.state=t,null!==this._playingProgressRequestId&&(cancelAnimationFrame(this._playingProgressRequestId),this._playingProgressPreviousTimestamp=0)},e.prototype.next=function(){this.play({whichSound:"next"})},e.prototype.previous=function(){this.play({whichSound:"previous"})},e.prototype.first=function(){this.play({whichSound:"first"})},e.prototype.last=function(){this.play({whichSound:"last"})},e.prototype._playingProgress=function(e){var t=e.getCurrentTime();e.playTime=t-e.startTime+e.playTimeOffset;var o=e.getDuration(),n=e.playTime/o*100;e.playedTimePercentage=n,e.onPlaying(n,o,e.playTime)},e.prototype.setAudioGraph=function(e){this._playerAudio.setAudioGraph(e),this._customAudioGraph=e},e.prototype.getAudioGraph=function(){var e=this;return new Promise((function(t,o){e._playerAudio.getAudioGraph().then((function(o){e._customAudioGraph=o,t(o)})).catch(o)}))},e.prototype.setAudioContext=function(e){this._playerAudio.setAudioContext(e),this._customAudioContext=e},e.prototype.getAudioContext=function(){var e=this;return new Promise((function(t,o){e._playerAudio.getAudioContext().then((function(o){e._customAudioContext=o,t(o)})).catch(o)}))},e.prototype.setVisibilityAutoMute=function(e){this._visibilityAutoMute=e,e?document.addEventListener("visibilitychange",this._handleVisibilityChange.bind(this),!1):document.removeEventListener("visibilitychange",this._handleVisibilityChange.bind(this),!1)},e.prototype.getVisibilityAutoMute=function(){return this._visibilityAutoMute},e.prototype._handleVisibilityChange=function(){var e;void 0!==document.hidden?e="hidden":void 0!==document.msHidden?e="msHidden":void 0!==document.webkitHidden&&(e="webkitHidden"),document[e]?this.mute():this.unMute()},e.WHERE_IN_QUEUE_AT_END="append",e.WHERE_IN_QUEUE_AT_START="prepend",e.WHERE_IN_QUEUE_AFTER_CURRENT="afterCurrent",e.PLAY_SOUND_NEXT="next",e.PLAY_SOUND_PREVIOUS="previous",e.PLAY_SOUND_FIRST="first",e.PLAY_SOUND_LAST="last",e.PLAYER_MODE_AUDIO="player_mode_audio",e.PLAYER_MODE_AJAX="player_mode_ajax",e.PLAYER_MODE_FETCH="player_mode_fetch",e}();export{s as PlayerCore,n as PlayerSound};
//# sourceMappingURL=index.min.js.map

@@ -53,3 +53,4 @@ import { ISound, ISoundAttributes, ISoundSource, typeSoundStates } from './sound';

protected _playingProgressIntervalTime: number;
protected _playingTimeoutID: number | null;
protected _playingProgressRequestId: number | null;
protected _playingProgressPreviousTimestamp: DOMHighResTimeStamp;
protected _playNextOnEnded: boolean;

@@ -107,2 +108,3 @@ protected _loopQueue: boolean;

protected _setupSoundEvents(sound: ISound): ISound;
protected _progressTrigger: (sound: ISound, timestamp: DOMHighResTimeStamp) => void;
protected _onEnded(): void;

@@ -109,0 +111,0 @@ /**

{
"name": "web-audio-api-player",
"version": "4.1.0",
"version": "4.2.0",
"description": "web audio api player",

@@ -5,0 +5,0 @@ "keywords": [

@@ -15,3 +15,3 @@ [![npm version](https://img.shields.io/npm/v/web-audio-api-player.svg?style=flat)](https://www.npmjs.com/package/web-audio-api-player)

TODO: add screenshot here showing the "simple example" UI, explain that this is just an example of an UI, you can bind your own custom UI to this player and use all or just some of it's features
TODO: add screenshot here showing the "simple example" UI, explain that this is just an example of an UI, you can bind your own custom UI to this player and use all or just some of its features

@@ -34,5 +34,9 @@ 😔 there is almost no documentation yet (there is some, see next section below), to learn how to use this library I recommend you check out the source code of the [simple player example](examples/simple-player) to get started

## examples
the best way to get started is to check out the examples folder, start with [simple player example](examples/simple-player)
## documentation
This player has two modes, PLAYER_MODE_AUDIO which uses the audio element to load sounds via the audio element and PLAYER_MODE_AJAX to load sounds via the web audio API. Here are some of the differences between the two:
This player has two modes, [PLAYER_MODE_AUDIO](#the-audio-element-player_mode_audio) which uses the audio element to load sounds via the audio element and [PLAYER_MODE_AJAX](#the-web-audio-api-player_mode_ajax) to load sounds via the web audio API. Here are some of the differences between the two:

@@ -65,3 +69,3 @@ ### the web audio API (PLAYER_MODE_AJAX)

If you build a game where you have a lot (of small sounds) that get (pre-)loaded and maybe cached but played later at some time after they finished loading, use PLAYER_MODE_AJAX. It's progress is easier to understand, because when the loading progress of the sound has reached 100% you know it can be played. To display the loading progress a simple [HTML progress element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress) is enough.
If you build a game where you have a lot (of small sounds) that get (pre-)loaded and maybe cached but played later at some time after they finished loading, use PLAYER_MODE_AJAX. Its progress is easier to understand, because when the loading progress of the sound has reached 100% you know it can be played. To display the loading progress a simple [HTML progress element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress) is enough.

@@ -86,12 +90,10 @@ If you build a music player, use the PLAYER_MODE_AUDIO as you might to want to start playing the sound (song) as quickly as possible and don't care if it has fully loaded yet as long as the part that has been loaded is enough to play the song until the end (while the rest of it is being streamed from the server in the background). To display the time range(s) that have been loaded you could for example use a [2D canvas element](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D).

## W3C web audio API
## read more: W3C sources and MDN documetation
[W3C Candidate Recommendation, 18 September 2018](https://www.w3.org/TR/webaudio/)
* [W3C Recommendation, 17 June 2021](https://www.w3.org/TR/webaudio/)
* [Web Audio API: Editor’s Draft, 18 July 2023](https://webaudio.github.io/web-audio-api/)
* [MDN "Web Audio API" page](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API)
* [MDN "The Embed Audio element" page](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio)
* Support tables for audio features, [caniuse: web audio API / audio element / formats ...](https://caniuse.com/#search=audio)
[Editor’s Draft, 8 August 2019](https://webaudio.github.io/web-audio-api/)
[MDN Web Audio API section](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API)
Support tables for audio features, [caniuse: web audio API / audio element / formats ...](https://caniuse.com/#search=audio)
## development: build

@@ -149,18 +151,2 @@

## examples
the best way to get started is to check out the examples folder, start with [simple player example](examples/simple-player)
## note to self: publish package on npmjs.com
login to npmjs.com
`npm login`
!!! before using the next the command ensure the version of your package in the package.json has been updated
publish a new version on npmjs
`npm publish`
## notes about problems I encountered during development

@@ -187,5 +173,3 @@

* 4.0.2 eslint-plugin-import dependency update, to fix JSON5 related [CVE-2022-46175](https://github.com/advisories/GHSA-9c47-m6qq-7p4h)
* 4.0.1 merged pull request #19 to fix audiocontext types
* 4.0.0 removed UMD support, this and future versions will be ESM only
check out the [releases page](https://github.com/chrisweb/web-audio-api-player/releases) on github

@@ -198,3 +182,3 @@ ## TODOs (help / PRs appreciated)

* create a vue.js example
* create an example using the fileReader
* create an example using the (browser) fileReader, something like:

@@ -212,65 +196,47 @@ ```javascript

* add improve UI style of the "simple" example(s) (or any new example) and then add a screenshot of it to the readme to show what can be achieved
* completely rewrite the sources system, where you can define multiple variants of a sound but with different codecs, app needs to check which codecs are supported by the device and choose one, use should be able to define which codec is preferred if playback support for multiple codecs is available
* implement audiocontext to close to release memory?
* destroy the audiocontext at some point, to release memory?
* feature to use the browser notification system to alert which song is being played
* instead of the ArrayBuffer use the MediaElementAudioSourceNode, make it optional to still use the ArrayBuffer
* preload AudioBuffers in indexeddb (first song, next song, current song if loop or previous is triggered ...), let the developer set the amount of preloaded AudioBuffers, remove from "cache" by least used and by date when "cache" is full
* cache songs for offline mode? indexeddb is not very big (filesystem?), check if doable because saving a playlist of songs might exhaust the free space
* some methods return a promise others don't, use promises for all to make it more consistent?
* write a documentation
* make a list of all possible errors (set a distinct code for each error)
* add a contribution guide
* write tests!!! (goal 100% coverage), add [tests coverage badge](https://coveralls.io)
* preload AudioBuffers into indexeddb (first song, next song, current song if loop or previous is triggered ...), let the developer set the amount of preloaded AudioBuffers, remove from "cache" by least used and by date when "cache" is full, maybe do such work using this browser feature [requestidlecallback](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback) (when available)
* cache songs for offline mode? indexeddb is not very big (filesystem?), check if doable because saving a playlist of songs might exhaust the free space (depending on the playlist size)
* some methods return a promise others don't, use promises for all to make it more consistent
* write more documentation
* make a list of all possible errors (set a distinct code for each error), handle all error cases that are still unhandled
* [abort](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort) the loading of the sound if the user clicks play and then pause (or stop / next / previous) before the end of the buffering process
* replace XMLHttpRequest with fetch?
* allow cross fading songs "on end" if it's the next song in a playlist (or just fade out / fade in)
* add feature to crossfade two songs "on end" (if there is a the next song in a playlist) or just fade out (current song) / fade in (next song)
* currently the "find song in queue" can't retrieve songs by queue index, is this useful anyway?
* use suspend and resume if for some time no sound was played? ... to free device resources. As suspend returns a promise, does this mean suspending and resuming takes time? if so how much time does it take, based on that information we can decide after how much time it makes sense to suspend the ctx to save device resources
* use the [requestAnimation](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) frame or the [requestidlecallback](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback) instead of setInterval for playing progress callback?
* use web workers, especially for the decoding of the ArrayBuffer into an AudioBuffer, to not block the main thread while decoding?
* add shuffle mode
* add a loop song and loop queue mode (<https://webaudio.github.io/web-audio-api/#looping-AudioBufferSourceNode>)
* handle all error cases that are still unhandled
* add a shuffle songs mode
* add a loop song (<https://webaudio.github.io/web-audio-api/#looping-AudioBufferSourceNode>) feature (actually maybe this already works today, need to verify)
* add support for more codecs (flac, wav, ogg vorbis, opus, aac): also check the available codecs and defined sources, play the first one that has matches and available codec, let user define order of preferred codecs for playback
* add saucelabs browser testing and their badge [browser compatibility table badge](https://saucelabs.com/blog/new-open-sauce-ui-and-refreshed-build-status-badges) in readme
* write code tests!!! (goal ofc 100% coverage), add [tests coverage badge](https://coveralls.io)
* add saucelabs (or similar) browser testing (and their badge [browser compatibility table badge](https://saucelabs.com/blog/new-open-sauce-ui-and-refreshed-build-status-badges) in readme) to add a test suite for all player features
* add [travis](https://travis-ci.org) continuous integration and badge
* add improve UI style and then add a screenshot to readme of example
* add live demo (via github pages)
* add live demo (via github pages?) for people to see how the player works
* for position and volume, allow to use a percentage or a value
* feature that let's the dev set a volume (via a modifier value / coefficient) per song, useful if some songs are louder than others and you want to normalize the volume of all songs in a playlist to be similar
* add hooks to the sound object for all the native source node events [AudioBufferSourceNode](https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode)
* add (stereo) panning
## DONE
## note to self: publish package on npmjs.com
* use gulp [gulp](https://gulpjs.com/) and some gulp plugins to create a clean build
* create an XMLHttpRequest library class to fetch the ArrayBuffer
* create an audio library class to create the context and decode the ArrayBuffer
* create a custom error class with message but also a numeric code
* let the user add a sound with an already fetched ArrayBuffer or even with an already decoded AudioBuffer
* create a simple example with a vanilla JS UI
* add a sounds queue manager
* add "play" sound
* add "pause" and "stop"
* add "next" and "previous"
* add set / get volume and mute
* add a loading progress callback
* add a playing progress callback
* add an onEnded callback
* play next song onEnded, add option to enable or disable automatic play next onEnded
* add change position method
* add loop queue option
* make the core player options object optional when initializing a new player
* let the user modify the audio graph, for example by adding / removíng nodes like a filter node, a panner node ...
* replace [gulp](https://gulpjs.com/) with [rollup](https://github.com/rollup/rollup) as new module bundler
* use [pkg.module](https://github.com/rollup/rollup/wiki/pkg.module) to distribute a UMD as well as an "ES6 modules" version
* rewrite the simple example with vanilla js instead of jquery
* put the web audio API player on npm and add npm version badge / license badge / ... [shields.io](http://shields.io/)
* implement suspend and resume: ctx.suspend() and resume
* add an option that uses the visibility API to automatically mute and unmute a sound when the visibility changes
* rewrite how the audiocontext is created, for browser that enforce that a user interaction has taken place before a context can be running
* add option to persist the user volume choice using the localstorage
* switch from tslint to eslint with typescript-eslint plugin / parser: TSlint will be deprecated [github ticket](https://github.com/palantir/tslint/issues/4534), read their [blog post](https://medium.com/palantir/tslint-in-2019-1a144c2317a9) and then switch to [ESLint](https://github.com/eslint/eslint)
login to npmjs.com
`npm login`
to make a publishing test (without actually publishing) use:
`npm publish --dry-run`
!!! before using the next the command ensure the version of your package in the package.json has been updated
publish a new version on npmjs
`npm publish`
## License
[MIT](LICENSE)

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc