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);
}
@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