Skip to content

Instantly share code, notes, and snippets.

@laziel
Created September 18, 2015 09:02
Show Gist options
  • Save laziel/7aefabe99ee57b16081c to your computer and use it in GitHub Desktop.
Save laziel/7aefabe99ee57b16081c to your computer and use it in GitHub Desktop.
Unlock Web Audio in iOS 9 Safari
var ctx = null, usingWebAudio = true;
try {
if (typeof AudioContext !== 'undefined') {
ctx = new AudioContext();
} else if (typeof webkitAudioContext !== 'undefined') {
ctx = new webkitAudioContext();
} else {
usingWebAudio = false;
}
} catch(e) {
usingWebAudio = false;
}
// context state at this time is `undefined` in iOS8 Safari
if (usingWebAudio && ctx.state === 'suspended') {
var resume = function () {
ctx.resume();
setTimeout(function () {
if (ctx.state === 'running') {
document.body.removeEventListener('touchend', resume, false);
}
}, 0);
};
document.body.addEventListener('touchend', resume, false);
}
@ffxsam
Copy link

ffxsam commented Jul 4, 2016

This totally saved my sanity. THANK YOU!

@jhmaloney
Copy link

Thank you!

@werelax
Copy link

werelax commented Mar 3, 2017

This was incredibly helpful. You, sir, are awesome.

@lmarcon
Copy link

lmarcon commented Jul 15, 2017

amazing. this solved an issue I had while trying to play some audio using webkitAudioContext on ios9 (both chrome and safari). Thanks Sir, I owe you!

@pixlpa
Copy link

pixlpa commented Nov 18, 2017

Ah, this did it. Thanks!!!

@dmaynard
Copy link

dmaynard commented Jan 9, 2018

Thank you !!

@jespertheend
Copy link

on iOS 11 it seems like the state turns into suspended every time you close safari. I had to listen for ctx.onstatechange and apply this trick again every time the state becomes suspended

@TaylorDale
Copy link

Another note: I've just had all these problems and it still didn't work.

The user cannot be in Silent mode. Even if regular music and videos play with audio, webkitAudio will not.

So annoying

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment