web-audio-api-player
Advanced tools
Comparing version 5.1.0-beta.1 to 5.1.0-beta.2
@@ -207,5 +207,5 @@ /****************************************************************************** | ||
if (this._options.createAudioContextOnFirstUserInteraction) { | ||
document.addEventListener('touchstart', this._unlockAudio.bind(this)); | ||
document.addEventListener('touchend', this._unlockAudio.bind(this)); | ||
document.addEventListener('mousedown', this._unlockAudio.bind(this)); | ||
document.addEventListener('touchstart', this.unlockAudio.bind(this)); | ||
document.addEventListener('touchend', this.unlockAudio.bind(this)); | ||
document.addEventListener('mousedown', this.unlockAudio.bind(this)); | ||
} | ||
@@ -215,32 +215,44 @@ } | ||
if (this._options.createAudioContextOnFirstUserInteraction) { | ||
document.removeEventListener('touchstart', this._unlockAudio.bind(this)); | ||
document.removeEventListener('touchend', this._unlockAudio.bind(this)); | ||
document.removeEventListener('mousedown', this._unlockAudio.bind(this)); | ||
document.removeEventListener('touchstart', this.unlockAudio.bind(this)); | ||
document.removeEventListener('touchend', this.unlockAudio.bind(this)); | ||
document.removeEventListener('mousedown', this.unlockAudio.bind(this)); | ||
} | ||
} | ||
_unlockAudio() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
unlockAudio() { | ||
return new Promise((resolve, reject) => { | ||
if (this._isAudioUnlocked) { | ||
return; | ||
resolve(); | ||
} | ||
yield this.getAudioContext(); | ||
const placeholderBuffer = this._audioContext.createBuffer(1, 1, 22050); | ||
let bufferSource = this._audioContext.createBufferSource(); | ||
bufferSource.onended = () => { | ||
bufferSource.disconnect(0); | ||
this._isAudioUnlocked = true; | ||
this._removeFirstUserInteractionEventListeners(); | ||
bufferSource.disconnect(0); | ||
bufferSource.buffer = null; | ||
bufferSource = null; | ||
}; | ||
bufferSource.buffer = placeholderBuffer; | ||
bufferSource.connect(this._audioContext.destination); | ||
bufferSource.start(0); | ||
if (this._options.loadPlayerMode === 'player_mode_audio') { | ||
this._createAudioElement(); | ||
this._createMediaElementAudioSourceNode(); | ||
} | ||
this.getAudioContext().then(() => { | ||
const placeholderBuffer = this._audioContext.createBuffer(1, 1, 22050); | ||
let bufferSource = this._audioContext.createBufferSource(); | ||
bufferSource.onended = () => { | ||
bufferSource.disconnect(0); | ||
this._removeFirstUserInteractionEventListeners(); | ||
bufferSource.disconnect(0); | ||
bufferSource.buffer = null; | ||
bufferSource = null; | ||
if (this._options.loadPlayerMode === 'player_mode_audio') { | ||
this._createAudioElementAndSource().then(() => { | ||
this._isAudioUnlocked = true; | ||
resolve(); | ||
}).catch(reject); | ||
} | ||
else if (this._options.loadPlayerMode === 'player_mode_ajax') { | ||
this._isAudioUnlocked = true; | ||
resolve(); | ||
} | ||
}; | ||
bufferSource.buffer = placeholderBuffer; | ||
bufferSource.connect(this._audioContext.destination); | ||
bufferSource.start(0); | ||
}).catch(reject); | ||
}); | ||
} | ||
_createAudioElementAndSource() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
yield this._createAudioElement(); | ||
yield this._createMediaElementAudioSourceNode(); | ||
}); | ||
} | ||
_createAudioElement() { | ||
@@ -498,7 +510,7 @@ return __awaiter(this, void 0, void 0, function* () { | ||
xhr.onprogress = function (event) { | ||
const percentage = 100 / (event.total / event.loaded); | ||
const percentageRounded = Math.round((percentage + Number.EPSILON) * 100) / 100; | ||
requested.loadingProgress = percentageRounded; | ||
const loadingPercentageRaw = 100 / (event.total / event.loaded); | ||
const loadingPercentage = Math.round(loadingPercentageRaw); | ||
requested.loadingProgress = loadingPercentage; | ||
if (requested.onLoading !== null) { | ||
requested.onLoading(percentageRounded, event.total, event.loaded); | ||
requested.onLoading(loadingPercentage, event.total, event.loaded); | ||
} | ||
@@ -740,9 +752,10 @@ }; | ||
const buffered = sound.audioElement.buffered.end(0); | ||
const percentage = 100 / (duration / buffered); | ||
sound.loadingProgress = percentage; | ||
const loadingPercentageRaw = 100 / (duration / buffered); | ||
const loadingPercentage = Math.round(loadingPercentageRaw); | ||
sound.loadingProgress = loadingPercentage; | ||
if (sound.onLoading !== null) { | ||
sound.onLoading(percentage, duration, buffered); | ||
sound.onLoading(loadingPercentage, duration, buffered); | ||
} | ||
sound.duration = sound.audioElement.duration; | ||
if (percentage === 100) { | ||
if (loadingPercentage === 100) { | ||
sound.isBuffering = false; | ||
@@ -797,2 +810,3 @@ sound.isBuffered = true; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
yield this._playerAudio.unlockAudio(); | ||
const currentSound = this._getSoundFromQueue({ whichSound: PlayerCore.CURRENT_SOUND }); | ||
@@ -799,0 +813,0 @@ const sound = this._getSoundFromQueue({ whichSound, updateIndex: true }); |
@@ -1,2 +0,2 @@ | ||
function e(e,t,i,o){return new(i||(i=Promise))((function(n,s){function u(e){try{r(o.next(e))}catch(e){s(e)}}function d(e){try{r(o.throw(e))}catch(e){s(e)}}function r(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(u,d)}r((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class t{constructor(e){this.url=null,this.codec=null,this.loop=!1,this.sourceNode=null,this.gainNode=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.elapsedPlayTime=0,this.playTime=0,this.playedTimePercentage=0,this.state="sound_state_stopped",this.loadingProgress=0,this.duration=null,this.firstTimePlayed=!0,this.isConnectToPlayerGain=!1,Array.isArray(e.source)?this.source=e.source:this.source=[e.source],void 0!==e.id?this.id=e.id:this.id=this._generateSoundId(),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,"function"==typeof e.onSeeking?this.onSeeking=e.onSeeking:this.onSeeking=null,e.arrayBuffer instanceof ArrayBuffer&&(this.arrayBuffer=e.arrayBuffer),e.audioBuffer instanceof AudioBuffer&&(this.audioBuffer=e.audioBuffer,this.isBuffering=!1,this.isBuffered=!0,this.audioBufferDate=new Date,this.duration=this.getDuration())}getCurrentTime(){let e;null!==this.sourceNode&&(this.sourceNode instanceof AudioBufferSourceNode?e=this.sourceNode.context.currentTime-this.startTime+this.elapsedPlayTime:this.sourceNode instanceof MediaElementAudioSourceNode&&(e=this.audioElement.currentTime));return Math.round(100*(e+Number.EPSILON))/100}getDuration(){let e;null!==this.sourceNode&&(this.sourceNode instanceof AudioBufferSourceNode?e=this.audioBuffer.duration:this.sourceNode instanceof MediaElementAudioSourceNode&&(e=this.audioElement.duration));return Math.round(100*(e+Number.EPSILON))/100}_generateSoundId(){return Date.now().toString(36)+Math.random().toString(36).substring(2)}}t.SOUND_STATE_STOPPED="sound_state_stopped",t.SOUND_STATE_PAUSED="sound_state_paused",t.SOUND_STATE_PLAYING="sound_state_playing",t.SOUND_STATE_SEEKING="sound_state_seeking";class i{constructor(e){this._audioContext=null,this._volume=null,this._audioNodes={gainNode:null},this._audioElement=null,this._mediaElementAudioSourceNode=null,this._isAudioUnlocked=!1,this._options=e,this._initialize()}_initialize(){this._options.createAudioContextOnFirstUserInteraction&&this._addFirstUserInteractionEventListeners()}getAudioNodes(){return this._audioNodes}decodeAudio(t){return e(this,void 0,void 0,(function*(){const e=yield this.getAudioContext();return yield e.decodeAudioData(t)}))}_createAudioContext(){if(this._audioContext instanceof AudioContext)return;const e=window.AudioContext||window.webkitAudioContext;null!==this._options.audioContext?this._audioContext=this._options.audioContext:this._audioContext=new e}_addFirstUserInteractionEventListeners(){this._options.createAudioContextOnFirstUserInteraction&&(document.addEventListener("touchstart",this._unlockAudio.bind(this)),document.addEventListener("touchend",this._unlockAudio.bind(this)),document.addEventListener("mousedown",this._unlockAudio.bind(this)))}_removeFirstUserInteractionEventListeners(){this._options.createAudioContextOnFirstUserInteraction&&(document.removeEventListener("touchstart",this._unlockAudio.bind(this)),document.removeEventListener("touchend",this._unlockAudio.bind(this)),document.removeEventListener("mousedown",this._unlockAudio.bind(this)))}_unlockAudio(){return e(this,void 0,void 0,(function*(){if(this._isAudioUnlocked)return;yield this.getAudioContext();const e=this._audioContext.createBuffer(1,1,22050);let t=this._audioContext.createBufferSource();t.onended=()=>{t.disconnect(0),this._isAudioUnlocked=!0,this._removeFirstUserInteractionEventListeners(),t.disconnect(0),t.buffer=null,t=null},t.buffer=e,t.connect(this._audioContext.destination),t.start(0),"player_mode_audio"===this._options.loadPlayerMode&&(this._createAudioElement(),this._createMediaElementAudioSourceNode())}))}_createAudioElement(){return e(this,void 0,void 0,(function*(){if(null===this._audioElement){const e=new Audio;e.controls=!1,e.autoplay=!1,e.preload="metadata",e.volume=1,e.id="web-audio-api-player",this._audioElement=e,this._options.addAudioElementsToDom&&document.body.appendChild(e)}}))}getAudioElement(){return this._audioElement}getAudioContext(){return e(this,void 0,void 0,(function*(){return null===this._audioContext||"closed"===this._audioContext.state?yield this._createAudioContext():"suspended"===this._audioContext.state&&(yield this.unfreezeAudioContext()),this._audioContext}))}unfreezeAudioContext(){return void 0===this._audioContext.resume?Promise.resolve():this._audioContext.resume()}freezeAudioContext(){return void 0===this._audioContext.suspend?Promise.resolve():this._audioContext.suspend()}isAudioContextFrozen(){return"suspended"===this._audioContext.state}detectAudioContextSupport(){let e=!1;return(void 0!==window.webkitAudioContext||"undefined"!=typeof AudioContext)&&(e=!0),e}detectAudioElementSupport(){return!!document.createElement("audio").canPlayType}_createAudioBufferSourceNode(){return e(this,void 0,void 0,(function*(){return(yield this.getAudioContext()).createBufferSource()}))}_createMediaElementAudioSourceNode(){return e(this,void 0,void 0,(function*(){if(null===this._mediaElementAudioSourceNode){const e=yield this.getAudioContext();this._mediaElementAudioSourceNode=e.createMediaElementSource(this._audioElement)}}))}_destroyMediaElementAudioSourceNode(){null!==this._mediaElementAudioSourceNode&&(void 0!==this._mediaElementAudioSourceNode.mediaElement&&this._mediaElementAudioSourceNode.mediaElement.remove(),this._mediaElementAudioSourceNode.disconnect(),this._mediaElementAudioSourceNode=null)}_destroyAudioBufferSourceNode(){null!==this._mediaElementAudioSourceNode&&this._mediaElementAudioSourceNode.disconnect()}_destroyAudioContext(){return e(this,void 0,void 0,(function*(){null!==this._audioContext&&"closed"!==this._audioContext.state&&(yield this._audioContext.close(),this._audioContext=null)}))}shutDown(t){return e(this,void 0,void 0,(function*(){this._removeFirstUserInteractionEventListeners(),t.forEach((e=>{this.disconnectSound(e)})),this._destroyMediaElementAudioSourceNode(),this._destroyAudioBufferSourceNode(),this._disconnectPlayerGainNode(),yield this._destroyAudioContext()}))}_getPlayerGainNode(){return e(this,void 0,void 0,(function*(){let e;if(this._audioNodes.gainNode instanceof GainNode)e=this._audioNodes.gainNode;else{const t=yield this.getAudioContext();e=t.createGain(),this._initializeVolume(e),e.connect(t.destination),this._audioNodes.gainNode=e}return e}))}_disconnectPlayerGainNode(){null!==this._audioNodes.gainNode&&(this._audioNodes.gainNode.disconnect(),this._audioNodes.gainNode=null)}connectSound(t,i){return e(this,void 0,void 0,(function*(){if(t.isConnectToPlayerGain)return;if("player_mode_ajax"===this._options.loadPlayerMode){const e=yield this._createAudioBufferSourceNode();t.gainNode=e.context.createGain(),e.connect(t.gainNode),e.loop=t.loop,e.onended=i,t.sourceNode=e}else"player_mode_audio"===this._options.loadPlayerMode&&(t.gainNode=this._mediaElementAudioSourceNode.context.createGain(),this._mediaElementAudioSourceNode.connect(t.gainNode),this._mediaElementAudioSourceNode.mediaElement.loop=t.loop,this._mediaElementAudioSourceNode.mediaElement.onended=i,t.sourceNode=this._mediaElementAudioSourceNode);t.gainNode.gain.value=1;const e=yield this._getPlayerGainNode();t.gainNode.connect(e),t.isConnectToPlayerGain=!0}))}disconnectSound(t){return e(this,void 0,void 0,(function*(){t.isConnectToPlayerGain&&(null!==t.sourceNode&&(t.sourceNode.disconnect(),t.sourceNode=null),null!==t.gainNode&&(t.gainNode.disconnect(),t.gainNode=null,t.isConnectToPlayerGain=!1),null!==t.audioElement&&(t.audioElement=null))}))}_changePlayerGainValue(t){return e(this,void 0,void 0,(function*(){if(this._audioNodes.gainNode instanceof GainNode){const e=yield this.getAudioContext();this._audioNodes.gainNode.gain.setTargetAtTime(t,e.currentTime,.1)}}))}setVolume(t,i=!0){return e(this,void 0,void 0,(function*(){this._options.persistVolume&&i&&localStorage.setItem("WebAudioAPIPlayerVolume",t.toString());const e=t/100;if(this._audioNodes.gainNode instanceof GainNode){e!==Math.round(100*(this._audioNodes.gainNode.gain.value+Number.EPSILON))/100&&(yield this._changePlayerGainValue(e))}return this._volume=t,t}))}getVolume(){let e;if(null!==this._volume)e=this._volume;else{if(this._options.persistVolume){const t=parseInt(localStorage.getItem("WebAudioAPIPlayerVolume"));isNaN(t)||(e=t)}void 0===e&&(e=this._options.volume),this._volume=e}return e}_initializeVolume(e){if(this._options.persistVolume){const t=parseInt(localStorage.getItem("WebAudioAPIPlayerVolume")),i=t/100;isNaN(t)||(e.gain.value=i),this._volume=t}if(null===this._volume){const t=this._options.volume/100;e.gain.value=t,this._volume=this._options.volume}}}class o{getArrayBuffer(e){return new Promise((function(t,i){const o=new XMLHttpRequest;o.open("GET",e.url,!0),o.responseType="arraybuffer",o.onload=function(){200===o.status?t(o.response):i(new Error(o.statusText+"(status:"+o.status+")"))},o.onprogress=function(t){const i=100/(t.total/t.loaded),o=Math.round(100*(i+Number.EPSILON))/100;e.loadingProgress=o,null!==e.onLoading&&e.onLoading(o,t.total,t.loaded)},o.onerror=function(e){i(e)},o.send()}))}}class n{constructor(e={}){this._playingProgressRequestId=null,this._postMuteVolume=null,this._progressTrigger=(e,i)=>{const o=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND});if(e.id===o.id&&o.state===t.SOUND_STATE_PLAYING){if(i-this._playingProgressPreviousTimestamp>=this._options.playingProgressIntervalTime){const t=e.getCurrentTime(),o=e.getDuration();if(!isNaN(t)&&!isNaN(o)){let n=0;if(0!==t){const e=t/o*100;n=Math.round(e)}e.playedTimePercentage=n,e.playTime=t,e.onPlaying(n,o,t),this._playingProgressPreviousTimestamp=i}}this._playingProgressRequestId=window.requestAnimationFrame((t=>{this._progressTrigger(e,t)}))}};const i={volume:80,loopQueue:!1,loopSong:!1,soundsBaseUrl:"",playingProgressIntervalTime:200,playNextOnEnded:!0,stopOnReset:!0,visibilityAutoMute:!1,createAudioContextOnFirstUserInteraction:!0,persistVolume:!0,loadPlayerMode:"player_mode_audio",audioContext:null,addAudioElementsToDom:!1},o=Object.assign({},i,e);this._queue=[],this._currentIndex=0,this._options=o,this._playingProgressPreviousTimestamp=0,this._initialize()}_initialize(){const e=this._audioOptions();switch(this._playerAudio=new i(e),this._options.loadPlayerMode){case n.PLAYER_MODE_AUDIO:if(!this._playerAudio.detectAudioContextSupport())throw new Error("audio context is not supported by this device");if(!this._playerAudio.detectAudioElementSupport())throw new Error("audio element is not supported by this device");break;case n.PLAYER_MODE_AJAX:if(!this._playerAudio.detectAudioContextSupport())throw new Error("audio context is not supported by this device")}}_audioOptions(){return{audioContext:this._options.audioContext,createAudioContextOnFirstUserInteraction:this._options.createAudioContextOnFirstUserInteraction,volume:this._options.volume,persistVolume:this._options.persistVolume,loadPlayerMode:this._options.loadPlayerMode,addAudioElementsToDom:this._options.addAudioElementsToDom}}addSoundToQueue({soundAttributes:e,whereInQueue:i="append"}){const o=new t(e);switch(i){case n.WHERE_IN_QUEUE_AT_END:this._appendSoundToQueue(o);break;case n.WHERE_IN_QUEUE_AT_START:this._prependSoundToQueue(o)}return o}_appendSoundToQueue(e){this._queue.push(e)}_prependSoundToQueue(e){this._queue.unshift(e)}resetQueue(){return e(this,void 0,void 0,(function*(){this._options.stopOnReset&&(yield this.stop()),this._queue.forEach((e=>{this._playerAudio.disconnectSound(e)})),this._queue=[]}))}reset(){this.resetQueue().catch((e=>{}))}getQueue(){return this._queue}setVolume(e){this._playerAudio.setVolume(e).catch((e=>{}))}getVolume(){return this._playerAudio.getVolume()}setLoopQueue(e){this._options.loopQueue=e}getLoopQueue(){return this._options.loopQueue}mute(){const e=this.getVolume();this._playerAudio.setVolume(0,!1).catch((e=>{})),this._postMuteVolume=e}unMute(){this._playerAudio.setVolume(this._postMuteVolume,!1).catch((e=>{})),this._postMuteVolume=null}isMuted(){return null!==this._postMuteVolume}setPosition(t){return e(this,void 0,void 0,(function*(){const e=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND});if(null!==e){let i=e.getDuration();(null===i||isNaN(i))&&(yield this._loadSound(e),i=e.getDuration());const o=i/100*t;this.setPositionInSeconds(o)}}))}setPositionInSeconds(i){return e(this,void 0,void 0,(function*(){const e=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND});if(null!==e){if(null!==e.onSeeking){const t=i,o=e.getDuration(),n=t/o*100,s=Math.round(n);e.onSeeking(s,o,t)}e.state===t.SOUND_STATE_PLAYING?(e.playTime=i,this._options.loadPlayerMode===n.PLAYER_MODE_AJAX?(e.elapsedPlayTime=i,yield this._stop(e,t.SOUND_STATE_SEEKING)):this._options.loadPlayerMode===n.PLAYER_MODE_AUDIO&&(e.state=t.SOUND_STATE_SEEKING,yield this._play(e))):(e.playTime=i,e.state=t.SOUND_STATE_SEEKING)}}))}_loadSound(t){return e(this,void 0,void 0,(function*(){switch(this._options.loadPlayerMode){case n.PLAYER_MODE_AUDIO:yield this._loadSoundUsingAudioElement(t);break;case n.PLAYER_MODE_AJAX:yield this._loadSoundUsingRequest(t);case n.PLAYER_MODE_FETCH:}}))}_loadSoundUsingAudioElement(t){return new Promise(((i,o)=>{const{url:n,codec:s=null}=this._findBestSource(t.source);if(t.url=n,t.codec=s,null!==t.url){t.audioElement=this._playerAudio.getAudioElement();const o=()=>e(this,void 0,void 0,(function*(){t.audioElement.removeEventListener("canplaythrough",o),t.isReadyToPLay=!0,isNaN(t.audioElement.duration)||(t.duration=t.audioElement.duration),i()}));t.audioElement.addEventListener("canplaythrough",o),t.audioElement.onprogress=()=>{if(t.audioElement.buffered.length){const e=t.getDuration(),i=t.audioElement.buffered.end(0),o=100/(e/i);t.loadingProgress=o,null!==t.onLoading&&t.onLoading(o,e,i),t.duration=t.audioElement.duration,100===o&&(t.isBuffering=!1,t.isBuffered=!0,t.audioBufferDate=new Date)}},t.audioElement.crossOrigin="anonymous",t.audioElement.src=t.url,t.audioElement.load()}else o(new Error("sound has no url"))}))}_loadSoundUsingRequest(t){return e(this,void 0,void 0,(function*(){if(null!==t.arrayBuffer)return yield this._decodeSound({sound:t});const{url:e,codec:i=null}=this._findBestSource(t.source);if(t.url=e,t.codec=i,null===t.url)throw new Error("sound has no url");{const e=new o;t.isBuffering=!0;const i=yield e.getArrayBuffer(t);t.arrayBuffer=i,yield this._decodeSound({sound:t})}}))}_decodeSound({sound:t}){return e(this,void 0,void 0,(function*(){const e=t.arrayBuffer.slice(0),i=yield this._playerAudio.decodeAudio(e);t.audioBuffer=i,t.isBuffering=!1,t.isBuffered=!0,t.audioBufferDate=new Date,t.duration=i.duration,t.isReadyToPLay=!0}))}play({whichSound:i,playTimeOffset:o}={}){return e(this,void 0,void 0,(function*(){const e=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND}),s=this._getSoundFromQueue({whichSound:i,updateIndex:!0});return null===s?s:null!==e&&e.state===t.SOUND_STATE_PLAYING&&e.id===s.id?(isNaN(o)||this.setPositionInSeconds(o),s):(null===e||e.state!==t.SOUND_STATE_PLAYING&&e.state!==t.SOUND_STATE_PAUSED||e.id===s.id||(yield this._stop(e,t.SOUND_STATE_STOPPED)),isNaN(o)?s.playTimeOffset=0:s.playTimeOffset=o,null===s.sourceNode&&(yield this._playerAudio.connectSound(s,(()=>{this._onEnded()}))),s.isReadyToPLay||(yield this._loadSound(s)),yield this._play(s),s)}))}_play(i){return e(this,void 0,void 0,(function*(){this._playerAudio.isAudioContextFrozen()&&(yield this._playerAudio.unfreezeAudioContext()),i.playTimeOffset>0&&(i.playTime=i.playTimeOffset),this._options.loadPlayerMode===n.PLAYER_MODE_AJAX?yield this._playAudioBuffer(i):this._options.loadPlayerMode===n.PLAYER_MODE_AUDIO&&(yield this._playMediaElementAudio(i)),i.state=t.SOUND_STATE_PLAYING,this._triggerSoundCallbacks(i)}))}_playAudioBuffer(i){return e(this,void 0,void 0,(function*(){if(i.sourceNode instanceof AudioBufferSourceNode){i.startTime=i.sourceNode.context.currentTime,i.sourceNode.buffer=i.audioBuffer;try{i.state===t.SOUND_STATE_SEEKING||i.state===t.SOUND_STATE_PAUSED&&0===i.playTimeOffset?i.sourceNode.start(0,i.playTime):i.playTimeOffset>0?(i.elapsedPlayTime=i.playTimeOffset,i.sourceNode.start(0,i.playTimeOffset)):i.sourceNode.start()}catch(e){throw new Error(e)}}}))}_playMediaElementAudio(i){return e(this,void 0,void 0,(function*(){i.sourceNode instanceof MediaElementAudioSourceNode&&(i.state===t.SOUND_STATE_SEEKING||i.state===t.SOUND_STATE_PAUSED&&0===i.playTimeOffset?i.audioElement.currentTime=i.playTime:i.playTimeOffset>0?i.audioElement.currentTime=i.playTimeOffset:i.audioElement.currentTime=0,yield i.audioElement.play())}))}_triggerSoundCallbacks(e){null===e.onResumed||e.firstTimePlayed||e.onResumed(e.playTime),null!==e.onStarted&&e.firstTimePlayed&&(e.firstTimePlayed=!1,e.onStarted(e.playTimeOffset)),null!==e.onPlaying?(this._playingProgressPreviousTimestamp=0,this._progressTrigger(e,0)):this._playingProgressRequestId=null}_onEnded(){return e(this,void 0,void 0,(function*(){if(this._options.playNextOnEnded){const e=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND});if(null!==e){if(this._options.loadPlayerMode===n.PLAYER_MODE_AUDIO||this._options.loadPlayerMode===n.PLAYER_MODE_AJAX&&e.state===t.SOUND_STATE_PLAYING){let t=!1;null!==this._getSoundFromQueue({whichSound:n.PLAY_SOUND_NEXT})&&(t=!0),t||(yield this._playerAudio.freezeAudioContext()),null!==e.onEnded&&e.onEnded(t);try{yield this.next()}catch(e){}}if(this._options.loadPlayerMode===n.PLAYER_MODE_AJAX&&e.state===t.SOUND_STATE_SEEKING)try{yield this.play(e)}catch(e){}}}}))}_getSoundFromQueue({whichSound:e,updateIndex:t=!1}={}){let i=null,o=null;if(0===this._queue.length)return i;switch(void 0===e&&(e=n.CURRENT_SOUND),e){case n.CURRENT_SOUND:o=this._currentIndex,i=this._queue[o];break;case n.PLAY_SOUND_NEXT:void 0!==this._queue[this._currentIndex+1]?(o=this._currentIndex+1,i=this._queue[o]):this._options.loopQueue&&(o=0,i=this._queue[o]);break;case n.PLAY_SOUND_PREVIOUS:void 0!==this._queue[this._currentIndex-1]?(o=this._currentIndex-1,i=this._queue[o]):this._options.loopQueue&&(o=this._queue.length-1,i=this._queue[o]);break;case n.PLAY_SOUND_FIRST:this._queue.length>0&&(o=0,i=this._queue[o]);break;case n.PLAY_SOUND_LAST:this._queue.length>0&&(o=this._queue.length-1,i=this._queue[o]);break;default:[i,o]=this._findSoundById({soundId:e})}return null!==o&&t&&(this._currentIndex=o),i}_findSoundById({soundId:e}){let t=null,i=0;return this._queue.some(((o,n)=>{if(o.id===e)return t=o,i=n,!0})),[t,i]}_findBestSource(e){const t={url:null,codec:null};let i;i=Array.isArray(e)?e:[e];let o=0;for(;o<i.length;){const e=i[o];let n="";""!==this._options.soundsBaseUrl&&(n=this._options.soundsBaseUrl),n+=e.url;let s=!0;if(null!==e.codec&&(s=this._checkCodecSupport(e.codec)),s){if(e.isPreferred){t.url=n,t.codec=e.codec;break}t.url=n,t.codec=e.codec}o++}return t}_checkCodecSupport(e){let t,i="";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:i="unrecognised codec"}if(i)throw new Error(i);return this._checkMimeTypesSupport(t)}_checkMimeTypesSupport(e){const t=new Audio;let i=!1;return e.forEach((e=>{t.canPlayType(e).replace(/^no$/,"")&&(i=!0)})),i}pause(){return e(this,void 0,void 0,(function*(){const e=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND});if(null===e)return;if(e.state===t.SOUND_STATE_PAUSED)return;const i=e.getCurrentTime();return e.playTime=i,this._options.loadPlayerMode===n.PLAYER_MODE_AJAX&&(e.elapsedPlayTime=i),null!==e.onPaused&&e.onPaused(e.playTime),yield this._stop(e,t.SOUND_STATE_PAUSED),e}))}stop(){return e(this,void 0,void 0,(function*(){const e=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND});if(null!==e&&e.state!==t.SOUND_STATE_STOPPED)return yield this._playerAudio.freezeAudioContext(),null!==e.onStopped&&e.onStopped(e.playTime),yield this._stop(e,t.SOUND_STATE_STOPPED),e}))}_stop(i,o){return e(this,void 0,void 0,(function*(){null!==this._playingProgressRequestId&&(cancelAnimationFrame(this._playingProgressRequestId),this._playingProgressRequestId=null),i.state=o,null!==i.sourceNode&&(i.sourceNode instanceof AudioBufferSourceNode&&(i.sourceNode.stop(0),yield this._playerAudio.disconnectSound(i)),i.sourceNode instanceof MediaElementAudioSourceNode&&i.audioElement.pause()),o===t.SOUND_STATE_STOPPED&&(i.isReadyToPLay=!1,i.firstTimePlayed=!0,i.startTime=0,i.elapsedPlayTime=0,i.playTime=0,i.playedTimePercentage=0,yield this._playerAudio.disconnectSound(i))}))}next(){return e(this,void 0,void 0,(function*(){return yield this.play({whichSound:n.PLAY_SOUND_NEXT})}))}previous(){return e(this,void 0,void 0,(function*(){return yield this.play({whichSound:n.PLAY_SOUND_PREVIOUS})}))}first(){return e(this,void 0,void 0,(function*(){return yield this.play({whichSound:n.PLAY_SOUND_FIRST})}))}last(){return e(this,void 0,void 0,(function*(){return yield this.play({whichSound:n.PLAY_SOUND_LAST})}))}setVisibilityAutoMute(e){this._options.visibilityAutoMute=e,e?document.addEventListener("visibilitychange",this._handleVisibilityChange.bind(this),!1):document.removeEventListener("visibilitychange",this._handleVisibilityChange.bind(this),!1)}getVisibilityAutoMute(){return this._options.visibilityAutoMute}_handleVisibilityChange(){let 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()}disconnect(){return e(this,void 0,void 0,(function*(){null!==this._playingProgressRequestId&&(cancelAnimationFrame(this._playingProgressRequestId),this._playingProgressRequestId=null),yield this._playerAudio.shutDown(this._queue)}))}getAudioContext(){return e(this,void 0,void 0,(function*(){return yield this._playerAudio.getAudioContext()}))}}n.WHERE_IN_QUEUE_AT_END="append",n.WHERE_IN_QUEUE_AT_START="prepend",n.PLAY_SOUND_NEXT="next",n.PLAY_SOUND_PREVIOUS="previous",n.PLAY_SOUND_FIRST="first",n.PLAY_SOUND_LAST="last",n.CURRENT_SOUND="current",n.PLAYER_MODE_AUDIO="player_mode_audio",n.PLAYER_MODE_AJAX="player_mode_ajax",n.PLAYER_MODE_FETCH="player_mode_fetch";export{n as PlayerCore,t as PlayerSound}; | ||
function e(e,t,o,i){return new(o||(o=Promise))((function(n,s){function u(e){try{r(i.next(e))}catch(e){s(e)}}function d(e){try{r(i.throw(e))}catch(e){s(e)}}function r(e){var t;e.done?n(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(u,d)}r((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class t{constructor(e){this.url=null,this.codec=null,this.loop=!1,this.sourceNode=null,this.gainNode=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.elapsedPlayTime=0,this.playTime=0,this.playedTimePercentage=0,this.state="sound_state_stopped",this.loadingProgress=0,this.duration=null,this.firstTimePlayed=!0,this.isConnectToPlayerGain=!1,Array.isArray(e.source)?this.source=e.source:this.source=[e.source],void 0!==e.id?this.id=e.id:this.id=this._generateSoundId(),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,"function"==typeof e.onSeeking?this.onSeeking=e.onSeeking:this.onSeeking=null,e.arrayBuffer instanceof ArrayBuffer&&(this.arrayBuffer=e.arrayBuffer),e.audioBuffer instanceof AudioBuffer&&(this.audioBuffer=e.audioBuffer,this.isBuffering=!1,this.isBuffered=!0,this.audioBufferDate=new Date,this.duration=this.getDuration())}getCurrentTime(){let e;null!==this.sourceNode&&(this.sourceNode instanceof AudioBufferSourceNode?e=this.sourceNode.context.currentTime-this.startTime+this.elapsedPlayTime:this.sourceNode instanceof MediaElementAudioSourceNode&&(e=this.audioElement.currentTime));return Math.round(100*(e+Number.EPSILON))/100}getDuration(){let e;null!==this.sourceNode&&(this.sourceNode instanceof AudioBufferSourceNode?e=this.audioBuffer.duration:this.sourceNode instanceof MediaElementAudioSourceNode&&(e=this.audioElement.duration));return Math.round(100*(e+Number.EPSILON))/100}_generateSoundId(){return Date.now().toString(36)+Math.random().toString(36).substring(2)}}t.SOUND_STATE_STOPPED="sound_state_stopped",t.SOUND_STATE_PAUSED="sound_state_paused",t.SOUND_STATE_PLAYING="sound_state_playing",t.SOUND_STATE_SEEKING="sound_state_seeking";class o{constructor(e){this._audioContext=null,this._volume=null,this._audioNodes={gainNode:null},this._audioElement=null,this._mediaElementAudioSourceNode=null,this._isAudioUnlocked=!1,this._options=e,this._initialize()}_initialize(){this._options.createAudioContextOnFirstUserInteraction&&this._addFirstUserInteractionEventListeners()}getAudioNodes(){return this._audioNodes}decodeAudio(t){return e(this,void 0,void 0,(function*(){const e=yield this.getAudioContext();return yield e.decodeAudioData(t)}))}_createAudioContext(){if(this._audioContext instanceof AudioContext)return;const e=window.AudioContext||window.webkitAudioContext;null!==this._options.audioContext?this._audioContext=this._options.audioContext:this._audioContext=new e}_addFirstUserInteractionEventListeners(){this._options.createAudioContextOnFirstUserInteraction&&(document.addEventListener("touchstart",this.unlockAudio.bind(this)),document.addEventListener("touchend",this.unlockAudio.bind(this)),document.addEventListener("mousedown",this.unlockAudio.bind(this)))}_removeFirstUserInteractionEventListeners(){this._options.createAudioContextOnFirstUserInteraction&&(document.removeEventListener("touchstart",this.unlockAudio.bind(this)),document.removeEventListener("touchend",this.unlockAudio.bind(this)),document.removeEventListener("mousedown",this.unlockAudio.bind(this)))}unlockAudio(){return new Promise(((e,t)=>{this._isAudioUnlocked&&e(),this.getAudioContext().then((()=>{const o=this._audioContext.createBuffer(1,1,22050);let i=this._audioContext.createBufferSource();i.onended=()=>{i.disconnect(0),this._removeFirstUserInteractionEventListeners(),i.disconnect(0),i.buffer=null,i=null,"player_mode_audio"===this._options.loadPlayerMode?this._createAudioElementAndSource().then((()=>{this._isAudioUnlocked=!0,e()})).catch(t):"player_mode_ajax"===this._options.loadPlayerMode&&(this._isAudioUnlocked=!0,e())},i.buffer=o,i.connect(this._audioContext.destination),i.start(0)})).catch(t)}))}_createAudioElementAndSource(){return e(this,void 0,void 0,(function*(){yield this._createAudioElement(),yield this._createMediaElementAudioSourceNode()}))}_createAudioElement(){return e(this,void 0,void 0,(function*(){if(null===this._audioElement){const e=new Audio;e.controls=!1,e.autoplay=!1,e.preload="metadata",e.volume=1,e.id="web-audio-api-player",this._audioElement=e,this._options.addAudioElementsToDom&&document.body.appendChild(e)}}))}getAudioElement(){return this._audioElement}getAudioContext(){return e(this,void 0,void 0,(function*(){return null===this._audioContext||"closed"===this._audioContext.state?yield this._createAudioContext():"suspended"===this._audioContext.state&&(yield this.unfreezeAudioContext()),this._audioContext}))}unfreezeAudioContext(){return void 0===this._audioContext.resume?Promise.resolve():this._audioContext.resume()}freezeAudioContext(){return void 0===this._audioContext.suspend?Promise.resolve():this._audioContext.suspend()}isAudioContextFrozen(){return"suspended"===this._audioContext.state}detectAudioContextSupport(){let e=!1;return(void 0!==window.webkitAudioContext||"undefined"!=typeof AudioContext)&&(e=!0),e}detectAudioElementSupport(){return!!document.createElement("audio").canPlayType}_createAudioBufferSourceNode(){return e(this,void 0,void 0,(function*(){return(yield this.getAudioContext()).createBufferSource()}))}_createMediaElementAudioSourceNode(){return e(this,void 0,void 0,(function*(){if(null===this._mediaElementAudioSourceNode){const e=yield this.getAudioContext();this._mediaElementAudioSourceNode=e.createMediaElementSource(this._audioElement)}}))}_destroyMediaElementAudioSourceNode(){null!==this._mediaElementAudioSourceNode&&(void 0!==this._mediaElementAudioSourceNode.mediaElement&&this._mediaElementAudioSourceNode.mediaElement.remove(),this._mediaElementAudioSourceNode.disconnect(),this._mediaElementAudioSourceNode=null)}_destroyAudioBufferSourceNode(){null!==this._mediaElementAudioSourceNode&&this._mediaElementAudioSourceNode.disconnect()}_destroyAudioContext(){return e(this,void 0,void 0,(function*(){null!==this._audioContext&&"closed"!==this._audioContext.state&&(yield this._audioContext.close(),this._audioContext=null)}))}shutDown(t){return e(this,void 0,void 0,(function*(){this._removeFirstUserInteractionEventListeners(),t.forEach((e=>{this.disconnectSound(e)})),this._destroyMediaElementAudioSourceNode(),this._destroyAudioBufferSourceNode(),this._disconnectPlayerGainNode(),yield this._destroyAudioContext()}))}_getPlayerGainNode(){return e(this,void 0,void 0,(function*(){let e;if(this._audioNodes.gainNode instanceof GainNode)e=this._audioNodes.gainNode;else{const t=yield this.getAudioContext();e=t.createGain(),this._initializeVolume(e),e.connect(t.destination),this._audioNodes.gainNode=e}return e}))}_disconnectPlayerGainNode(){null!==this._audioNodes.gainNode&&(this._audioNodes.gainNode.disconnect(),this._audioNodes.gainNode=null)}connectSound(t,o){return e(this,void 0,void 0,(function*(){if(t.isConnectToPlayerGain)return;if("player_mode_ajax"===this._options.loadPlayerMode){const e=yield this._createAudioBufferSourceNode();t.gainNode=e.context.createGain(),e.connect(t.gainNode),e.loop=t.loop,e.onended=o,t.sourceNode=e}else"player_mode_audio"===this._options.loadPlayerMode&&(t.gainNode=this._mediaElementAudioSourceNode.context.createGain(),this._mediaElementAudioSourceNode.connect(t.gainNode),this._mediaElementAudioSourceNode.mediaElement.loop=t.loop,this._mediaElementAudioSourceNode.mediaElement.onended=o,t.sourceNode=this._mediaElementAudioSourceNode);t.gainNode.gain.value=1;const e=yield this._getPlayerGainNode();t.gainNode.connect(e),t.isConnectToPlayerGain=!0}))}disconnectSound(t){return e(this,void 0,void 0,(function*(){t.isConnectToPlayerGain&&(null!==t.sourceNode&&(t.sourceNode.disconnect(),t.sourceNode=null),null!==t.gainNode&&(t.gainNode.disconnect(),t.gainNode=null,t.isConnectToPlayerGain=!1),null!==t.audioElement&&(t.audioElement=null))}))}_changePlayerGainValue(t){return e(this,void 0,void 0,(function*(){if(this._audioNodes.gainNode instanceof GainNode){const e=yield this.getAudioContext();this._audioNodes.gainNode.gain.setTargetAtTime(t,e.currentTime,.1)}}))}setVolume(t,o=!0){return e(this,void 0,void 0,(function*(){this._options.persistVolume&&o&&localStorage.setItem("WebAudioAPIPlayerVolume",t.toString());const e=t/100;if(this._audioNodes.gainNode instanceof GainNode){e!==Math.round(100*(this._audioNodes.gainNode.gain.value+Number.EPSILON))/100&&(yield this._changePlayerGainValue(e))}return this._volume=t,t}))}getVolume(){let e;if(null!==this._volume)e=this._volume;else{if(this._options.persistVolume){const t=parseInt(localStorage.getItem("WebAudioAPIPlayerVolume"));isNaN(t)||(e=t)}void 0===e&&(e=this._options.volume),this._volume=e}return e}_initializeVolume(e){if(this._options.persistVolume){const t=parseInt(localStorage.getItem("WebAudioAPIPlayerVolume")),o=t/100;isNaN(t)||(e.gain.value=o),this._volume=t}if(null===this._volume){const t=this._options.volume/100;e.gain.value=t,this._volume=this._options.volume}}}class i{getArrayBuffer(e){return new Promise((function(t,o){const i=new XMLHttpRequest;i.open("GET",e.url,!0),i.responseType="arraybuffer",i.onload=function(){200===i.status?t(i.response):o(new Error(i.statusText+"(status:"+i.status+")"))},i.onprogress=function(t){const o=100/(t.total/t.loaded),i=Math.round(o);e.loadingProgress=i,null!==e.onLoading&&e.onLoading(i,t.total,t.loaded)},i.onerror=function(e){o(e)},i.send()}))}}class n{constructor(e={}){this._playingProgressRequestId=null,this._postMuteVolume=null,this._progressTrigger=(e,o)=>{const i=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND});if(e.id===i.id&&i.state===t.SOUND_STATE_PLAYING){if(o-this._playingProgressPreviousTimestamp>=this._options.playingProgressIntervalTime){const t=e.getCurrentTime(),i=e.getDuration();if(!isNaN(t)&&!isNaN(i)){let n=0;if(0!==t){const e=t/i*100;n=Math.round(e)}e.playedTimePercentage=n,e.playTime=t,e.onPlaying(n,i,t),this._playingProgressPreviousTimestamp=o}}this._playingProgressRequestId=window.requestAnimationFrame((t=>{this._progressTrigger(e,t)}))}};const o={volume:80,loopQueue:!1,loopSong:!1,soundsBaseUrl:"",playingProgressIntervalTime:200,playNextOnEnded:!0,stopOnReset:!0,visibilityAutoMute:!1,createAudioContextOnFirstUserInteraction:!0,persistVolume:!0,loadPlayerMode:"player_mode_audio",audioContext:null,addAudioElementsToDom:!1},i=Object.assign({},o,e);this._queue=[],this._currentIndex=0,this._options=i,this._playingProgressPreviousTimestamp=0,this._initialize()}_initialize(){const e=this._audioOptions();switch(this._playerAudio=new o(e),this._options.loadPlayerMode){case n.PLAYER_MODE_AUDIO:if(!this._playerAudio.detectAudioContextSupport())throw new Error("audio context is not supported by this device");if(!this._playerAudio.detectAudioElementSupport())throw new Error("audio element is not supported by this device");break;case n.PLAYER_MODE_AJAX:if(!this._playerAudio.detectAudioContextSupport())throw new Error("audio context is not supported by this device")}}_audioOptions(){return{audioContext:this._options.audioContext,createAudioContextOnFirstUserInteraction:this._options.createAudioContextOnFirstUserInteraction,volume:this._options.volume,persistVolume:this._options.persistVolume,loadPlayerMode:this._options.loadPlayerMode,addAudioElementsToDom:this._options.addAudioElementsToDom}}addSoundToQueue({soundAttributes:e,whereInQueue:o="append"}){const i=new t(e);switch(o){case n.WHERE_IN_QUEUE_AT_END:this._appendSoundToQueue(i);break;case n.WHERE_IN_QUEUE_AT_START:this._prependSoundToQueue(i)}return i}_appendSoundToQueue(e){this._queue.push(e)}_prependSoundToQueue(e){this._queue.unshift(e)}resetQueue(){return e(this,void 0,void 0,(function*(){this._options.stopOnReset&&(yield this.stop()),this._queue.forEach((e=>{this._playerAudio.disconnectSound(e)})),this._queue=[]}))}reset(){this.resetQueue().catch((e=>{}))}getQueue(){return this._queue}setVolume(e){this._playerAudio.setVolume(e).catch((e=>{}))}getVolume(){return this._playerAudio.getVolume()}setLoopQueue(e){this._options.loopQueue=e}getLoopQueue(){return this._options.loopQueue}mute(){const e=this.getVolume();this._playerAudio.setVolume(0,!1).catch((e=>{})),this._postMuteVolume=e}unMute(){this._playerAudio.setVolume(this._postMuteVolume,!1).catch((e=>{})),this._postMuteVolume=null}isMuted(){return null!==this._postMuteVolume}setPosition(t){return e(this,void 0,void 0,(function*(){const e=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND});if(null!==e){let o=e.getDuration();(null===o||isNaN(o))&&(yield this._loadSound(e),o=e.getDuration());const i=o/100*t;this.setPositionInSeconds(i)}}))}setPositionInSeconds(o){return e(this,void 0,void 0,(function*(){const e=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND});if(null!==e){if(null!==e.onSeeking){const t=o,i=e.getDuration(),n=t/i*100,s=Math.round(n);e.onSeeking(s,i,t)}e.state===t.SOUND_STATE_PLAYING?(e.playTime=o,this._options.loadPlayerMode===n.PLAYER_MODE_AJAX?(e.elapsedPlayTime=o,yield this._stop(e,t.SOUND_STATE_SEEKING)):this._options.loadPlayerMode===n.PLAYER_MODE_AUDIO&&(e.state=t.SOUND_STATE_SEEKING,yield this._play(e))):(e.playTime=o,e.state=t.SOUND_STATE_SEEKING)}}))}_loadSound(t){return e(this,void 0,void 0,(function*(){switch(this._options.loadPlayerMode){case n.PLAYER_MODE_AUDIO:yield this._loadSoundUsingAudioElement(t);break;case n.PLAYER_MODE_AJAX:yield this._loadSoundUsingRequest(t);case n.PLAYER_MODE_FETCH:}}))}_loadSoundUsingAudioElement(t){return new Promise(((o,i)=>{const{url:n,codec:s=null}=this._findBestSource(t.source);if(t.url=n,t.codec=s,null!==t.url){t.audioElement=this._playerAudio.getAudioElement();const i=()=>e(this,void 0,void 0,(function*(){t.audioElement.removeEventListener("canplaythrough",i),t.isReadyToPLay=!0,isNaN(t.audioElement.duration)||(t.duration=t.audioElement.duration),o()}));t.audioElement.addEventListener("canplaythrough",i),t.audioElement.onprogress=()=>{if(t.audioElement.buffered.length){const e=t.getDuration(),o=t.audioElement.buffered.end(0),i=100/(e/o),n=Math.round(i);t.loadingProgress=n,null!==t.onLoading&&t.onLoading(n,e,o),t.duration=t.audioElement.duration,100===n&&(t.isBuffering=!1,t.isBuffered=!0,t.audioBufferDate=new Date)}},t.audioElement.crossOrigin="anonymous",t.audioElement.src=t.url,t.audioElement.load()}else i(new Error("sound has no url"))}))}_loadSoundUsingRequest(t){return e(this,void 0,void 0,(function*(){if(null!==t.arrayBuffer)return yield this._decodeSound({sound:t});const{url:e,codec:o=null}=this._findBestSource(t.source);if(t.url=e,t.codec=o,null===t.url)throw new Error("sound has no url");{const e=new i;t.isBuffering=!0;const o=yield e.getArrayBuffer(t);t.arrayBuffer=o,yield this._decodeSound({sound:t})}}))}_decodeSound({sound:t}){return e(this,void 0,void 0,(function*(){const e=t.arrayBuffer.slice(0),o=yield this._playerAudio.decodeAudio(e);t.audioBuffer=o,t.isBuffering=!1,t.isBuffered=!0,t.audioBufferDate=new Date,t.duration=o.duration,t.isReadyToPLay=!0}))}play({whichSound:o,playTimeOffset:i}={}){return e(this,void 0,void 0,(function*(){yield this._playerAudio.unlockAudio();const e=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND}),s=this._getSoundFromQueue({whichSound:o,updateIndex:!0});return null===s?s:null!==e&&e.state===t.SOUND_STATE_PLAYING&&e.id===s.id?(isNaN(i)||this.setPositionInSeconds(i),s):(null===e||e.state!==t.SOUND_STATE_PLAYING&&e.state!==t.SOUND_STATE_PAUSED||e.id===s.id||(yield this._stop(e,t.SOUND_STATE_STOPPED)),isNaN(i)?s.playTimeOffset=0:s.playTimeOffset=i,null===s.sourceNode&&(yield this._playerAudio.connectSound(s,(()=>{this._onEnded()}))),s.isReadyToPLay||(yield this._loadSound(s)),yield this._play(s),s)}))}_play(o){return e(this,void 0,void 0,(function*(){this._playerAudio.isAudioContextFrozen()&&(yield this._playerAudio.unfreezeAudioContext()),o.playTimeOffset>0&&(o.playTime=o.playTimeOffset),this._options.loadPlayerMode===n.PLAYER_MODE_AJAX?yield this._playAudioBuffer(o):this._options.loadPlayerMode===n.PLAYER_MODE_AUDIO&&(yield this._playMediaElementAudio(o)),o.state=t.SOUND_STATE_PLAYING,this._triggerSoundCallbacks(o)}))}_playAudioBuffer(o){return e(this,void 0,void 0,(function*(){if(o.sourceNode instanceof AudioBufferSourceNode){o.startTime=o.sourceNode.context.currentTime,o.sourceNode.buffer=o.audioBuffer;try{o.state===t.SOUND_STATE_SEEKING||o.state===t.SOUND_STATE_PAUSED&&0===o.playTimeOffset?o.sourceNode.start(0,o.playTime):o.playTimeOffset>0?(o.elapsedPlayTime=o.playTimeOffset,o.sourceNode.start(0,o.playTimeOffset)):o.sourceNode.start()}catch(e){throw new Error(e)}}}))}_playMediaElementAudio(o){return e(this,void 0,void 0,(function*(){o.sourceNode instanceof MediaElementAudioSourceNode&&(o.state===t.SOUND_STATE_SEEKING||o.state===t.SOUND_STATE_PAUSED&&0===o.playTimeOffset?o.audioElement.currentTime=o.playTime:o.playTimeOffset>0?o.audioElement.currentTime=o.playTimeOffset:o.audioElement.currentTime=0,yield o.audioElement.play())}))}_triggerSoundCallbacks(e){null===e.onResumed||e.firstTimePlayed||e.onResumed(e.playTime),null!==e.onStarted&&e.firstTimePlayed&&(e.firstTimePlayed=!1,e.onStarted(e.playTimeOffset)),null!==e.onPlaying?(this._playingProgressPreviousTimestamp=0,this._progressTrigger(e,0)):this._playingProgressRequestId=null}_onEnded(){return e(this,void 0,void 0,(function*(){if(this._options.playNextOnEnded){const e=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND});if(null!==e){if(this._options.loadPlayerMode===n.PLAYER_MODE_AUDIO||this._options.loadPlayerMode===n.PLAYER_MODE_AJAX&&e.state===t.SOUND_STATE_PLAYING){let t=!1;null!==this._getSoundFromQueue({whichSound:n.PLAY_SOUND_NEXT})&&(t=!0),t||(yield this._playerAudio.freezeAudioContext()),null!==e.onEnded&&e.onEnded(t);try{yield this.next()}catch(e){}}if(this._options.loadPlayerMode===n.PLAYER_MODE_AJAX&&e.state===t.SOUND_STATE_SEEKING)try{yield this.play(e)}catch(e){}}}}))}_getSoundFromQueue({whichSound:e,updateIndex:t=!1}={}){let o=null,i=null;if(0===this._queue.length)return o;switch(void 0===e&&(e=n.CURRENT_SOUND),e){case n.CURRENT_SOUND:i=this._currentIndex,o=this._queue[i];break;case n.PLAY_SOUND_NEXT:void 0!==this._queue[this._currentIndex+1]?(i=this._currentIndex+1,o=this._queue[i]):this._options.loopQueue&&(i=0,o=this._queue[i]);break;case n.PLAY_SOUND_PREVIOUS:void 0!==this._queue[this._currentIndex-1]?(i=this._currentIndex-1,o=this._queue[i]):this._options.loopQueue&&(i=this._queue.length-1,o=this._queue[i]);break;case n.PLAY_SOUND_FIRST:this._queue.length>0&&(i=0,o=this._queue[i]);break;case n.PLAY_SOUND_LAST:this._queue.length>0&&(i=this._queue.length-1,o=this._queue[i]);break;default:[o,i]=this._findSoundById({soundId:e})}return null!==i&&t&&(this._currentIndex=i),o}_findSoundById({soundId:e}){let t=null,o=0;return this._queue.some(((i,n)=>{if(i.id===e)return t=i,o=n,!0})),[t,o]}_findBestSource(e){const t={url:null,codec:null};let o;o=Array.isArray(e)?e:[e];let i=0;for(;i<o.length;){const e=o[i];let n="";""!==this._options.soundsBaseUrl&&(n=this._options.soundsBaseUrl),n+=e.url;let s=!0;if(null!==e.codec&&(s=this._checkCodecSupport(e.codec)),s){if(e.isPreferred){t.url=n,t.codec=e.codec;break}t.url=n,t.codec=e.codec}i++}return t}_checkCodecSupport(e){let 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 Error(o);return this._checkMimeTypesSupport(t)}_checkMimeTypesSupport(e){const t=new Audio;let o=!1;return e.forEach((e=>{t.canPlayType(e).replace(/^no$/,"")&&(o=!0)})),o}pause(){return e(this,void 0,void 0,(function*(){const e=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND});if(null===e)return;if(e.state===t.SOUND_STATE_PAUSED)return;const o=e.getCurrentTime();return e.playTime=o,this._options.loadPlayerMode===n.PLAYER_MODE_AJAX&&(e.elapsedPlayTime=o),null!==e.onPaused&&e.onPaused(e.playTime),yield this._stop(e,t.SOUND_STATE_PAUSED),e}))}stop(){return e(this,void 0,void 0,(function*(){const e=this._getSoundFromQueue({whichSound:n.CURRENT_SOUND});if(null!==e&&e.state!==t.SOUND_STATE_STOPPED)return yield this._playerAudio.freezeAudioContext(),null!==e.onStopped&&e.onStopped(e.playTime),yield this._stop(e,t.SOUND_STATE_STOPPED),e}))}_stop(o,i){return e(this,void 0,void 0,(function*(){null!==this._playingProgressRequestId&&(cancelAnimationFrame(this._playingProgressRequestId),this._playingProgressRequestId=null),o.state=i,null!==o.sourceNode&&(o.sourceNode instanceof AudioBufferSourceNode&&(o.sourceNode.stop(0),yield this._playerAudio.disconnectSound(o)),o.sourceNode instanceof MediaElementAudioSourceNode&&o.audioElement.pause()),i===t.SOUND_STATE_STOPPED&&(o.isReadyToPLay=!1,o.firstTimePlayed=!0,o.startTime=0,o.elapsedPlayTime=0,o.playTime=0,o.playedTimePercentage=0,yield this._playerAudio.disconnectSound(o))}))}next(){return e(this,void 0,void 0,(function*(){return yield this.play({whichSound:n.PLAY_SOUND_NEXT})}))}previous(){return e(this,void 0,void 0,(function*(){return yield this.play({whichSound:n.PLAY_SOUND_PREVIOUS})}))}first(){return e(this,void 0,void 0,(function*(){return yield this.play({whichSound:n.PLAY_SOUND_FIRST})}))}last(){return e(this,void 0,void 0,(function*(){return yield this.play({whichSound:n.PLAY_SOUND_LAST})}))}setVisibilityAutoMute(e){this._options.visibilityAutoMute=e,e?document.addEventListener("visibilitychange",this._handleVisibilityChange.bind(this),!1):document.removeEventListener("visibilitychange",this._handleVisibilityChange.bind(this),!1)}getVisibilityAutoMute(){return this._options.visibilityAutoMute}_handleVisibilityChange(){let 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()}disconnect(){return e(this,void 0,void 0,(function*(){null!==this._playingProgressRequestId&&(cancelAnimationFrame(this._playingProgressRequestId),this._playingProgressRequestId=null),yield this._playerAudio.shutDown(this._queue)}))}getAudioContext(){return e(this,void 0,void 0,(function*(){return yield this._playerAudio.getAudioContext()}))}}n.WHERE_IN_QUEUE_AT_END="append",n.WHERE_IN_QUEUE_AT_START="prepend",n.PLAY_SOUND_NEXT="next",n.PLAY_SOUND_PREVIOUS="previous",n.PLAY_SOUND_FIRST="first",n.PLAY_SOUND_LAST="last",n.CURRENT_SOUND="current",n.PLAYER_MODE_AUDIO="player_mode_audio",n.PLAYER_MODE_AJAX="player_mode_ajax",n.PLAYER_MODE_FETCH="player_mode_fetch";export{n as PlayerCore,t as PlayerSound}; | ||
//# sourceMappingURL=index.min.js.map |
@@ -41,3 +41,4 @@ import { ISound } from './sound'; | ||
protected _removeFirstUserInteractionEventListeners(): void; | ||
protected _unlockAudio(): Promise<void>; | ||
unlockAudio(): Promise<void>; | ||
protected _createAudioElementAndSource(): Promise<void>; | ||
protected _createAudioElement(): Promise<void>; | ||
@@ -44,0 +45,0 @@ getAudioElement(): HTMLAudioElement; |
{ | ||
"name": "web-audio-api-player", | ||
"version": "5.1.0-beta.1", | ||
"version": "5.1.0-beta.2", | ||
"description": "web audio api player", | ||
@@ -5,0 +5,0 @@ "keywords": [ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
335324
1658
0