Created
June 11, 2020 08:32
-
-
Save luruke/e12663899de1ec3cbd4634c8577cfa21 to your computer and use it in GitHub Desktop.
This file contains hidden or 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, clb) { | |
this.ctx = ctx | |
this.unlocked = false | |
this.unlockCallback = clb | |
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.state === 'interrupted') { | |
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) | |
// console.log('SOUND UNLOCKED') | |
this.unlockCallback() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment