Created
April 18, 2019 10:34
-
-
Save luruke/91da5814393bb4fd919fbdac9e5f0aeb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Try to fix iOS lock on audio. | |
* | |
* By default, audio on iOS is locked until a sound is played within a user interaction, | |
* and then it plays normally the rest of the page session. | |
*/ | |
// Inspired from https://github.com/goldfire/howler.js/blob/2.0/src/howler.core.js#L212 | |
export default class IosUnlock { | |
constructor(ctx) { | |
this.ctx = ctx; | |
this.unlocked = false; | |
this.unlock = this.unlock.bind(this); | |
document.addEventListener('touchend', this.unlock, true); | |
document.addEventListener('mousedown', this.unlock, true); | |
document.addEventListener('click', this.unlock, true); | |
} | |
unlock() { | |
if (this.unlocked) { | |
if (this.ctx.state === 'suspended') { | |
this.ctx.resume(); | |
} | |
return false; | |
} | |
if (typeof this.ctx.resume === 'function') { | |
return this.ctx.resume().then(this.startFakeBuffer.bind(this)); | |
} | |
return this.startFakeBuffer(); | |
} | |
startFakeBuffer() { | |
this.buffer = this.ctx.createBuffer(1, 1, 22050); | |
this.source = this.ctx.createBufferSource(); | |
this.source.buffer = this.buffer; | |
this.source.connect(this.ctx.destination); | |
this.source.start(0); | |
this.source.onended = this.onSourceEnd.bind(this); | |
} | |
onSourceEnd() { | |
this.source.disconnect(); | |
this.unlocked = true; | |
document.removeEventListener('touchend', this.unlock, true); | |
document.removeEventListener('mousedown', this.unlock, true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment