I'm having troubles creating an AudioContext with Safari (desktop and mobile). It seems that even with creation upon user interaction, it is still suspended.
My code:
<button onclick="test()">Test</button>
const test = () => {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
audioContext = new AudioContext();
console.log(audioContext.state); // Suspended
}
This should be a minimum working example, right? What's wrong here?
I think Safari is actually behaving correctly (at least partially) in this case. The Web Audio Spec says that ...
https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-onstatechange
Unfortunately Safari doesn't do the transition to the
runningstate on its own. You have to explicitly ask it to do so.The
statechangeevent should fire almost immediately. If you execute this inside the click handler.The function above would then look like this:
Interestingly Safari only fires the
statechangeevent if you keep theconsole.logstatement before callingresume().However there is another hack that you can try to kick of the
AudioContext. Just create a simpleGainNode.You can also give standardized-audio-context a try which makes all browsers behave the same in that regard.