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. So I'd like to offer more fuel to the flaming pile of workarounds on the Internet.

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)();


Leave a Reply