Skip to content

Instantly share code, notes, and snippets.

@IkarosKappler
Created November 15, 2017 16:23
Show Gist options
  • Save IkarosKappler/e3c6b011fc08c93d2e1a80a50d9cef61 to your computer and use it in GitHub Desktop.
Save IkarosKappler/e3c6b011fc08c93d2e1a80a50d9cef61 to your computer and use it in GitHub Desktop.
WebAudio API Polyfill for Safari Browsers
/**
* Safari does handle web audio a bit different.
*
* Original found at
* https://gist.github.com/laziel/7aefabe99ee57b16081c
*
* Modified by Ikaros Kappler
* @date 2017-11-15
**/
function webaudioPolyfill( callback ) {
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) {
console.log( e );
usingWebAudio = false;
}
// context state at this time is `undefined` in iOS8 Safari
if( usingWebAudio ) {
var eventCalled = false;
if( ctx.state === 'suspended') {
console.log( 'web audio context is suspended!' );
var resume = function () {
console.log( 'resuming web audio context ...' );
ctx.resume().then( function() { if( !eventCalled ) callback(ctx); eventCalled = true; } );
setTimeout(function () {
if (ctx.state === 'running') {
document.body.removeEventListener('touchend', resume, false);
}
}, 0);
};
document.body.addEventListener('touchend', resume, false);
ctx.resume().then( function() { if( !eventCalled ) callback(ctx); eventCalled = true; } );
} else {
callback(ctx);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment