Unlock Web Audio in Safari for iOS and macos

I've had hours of frustration dealing with Web Audio in Safari. Especially with ScriptProcessorNode, it just doesn't want to work. Here's a solution I've arrived at. This is written in ES6 JavaScript, and will work in both iOS and macos:

function safariAudioUnlock(audioCtx) {
  if (context.state !== 'suspended') return;
  const b = document.body;
  const events = ['touchstart','touchend', 'mousedown','mouseup'];
  events.forEach(e => b.addEventListener(e, unlock, false));
  function unlock() { audioCtx.resume().then(clean); }
  function clean() { events.forEach(e => b.removeEventListener(e, unlock)); }
}

Use it like this:

const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
safariAudioUnlock(audioCtx);

 

Leave a Reply