9

So I've this warning on my console. I read the documentation : https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

I did everything as they said but I still have this warning. Here's my code :

let context;
window.onload = function() {
    context = new AudioContext();
    ...
}

// click event
document.addEventListener('click', function (e) {
    if (e.target.closest('.play1')) {
       context.resume().then(() => {
            source.start(0);
       });
    }
})

The warning text is about this line : context = new AudioContext();

Does anyone see what I'm missing ? Thank you very much

Michaël
  • 489
  • 1
  • 5
  • 21
  • onload is not a user generated UI interaction . Common to use a btn 'click' as the user-input event req'd by web-audio AND then to get the new Context and to wire it up to streams and to get permissions per the API docs – Robert Rowntree Mar 25 '21 at 14:36
  • Does it mean I can not load my audio before the click event ? Because the idea was to load my audio inside a BufferSource before the user click to play the song – Michaël Mar 25 '21 at 15:12
  • You can do whatever you want. You're only prevented from hearing any audio until you get a user gesture to resume the context or start the buffer source. – Raymond Toy Mar 29 '21 at 14:48
  • Yes but from my example, I only declare a contexte inside an onload event. So basically I'm not supposed to get this warning no ? – Michaël Mar 30 '21 at 15:02
  • Does this answer your question? [Google Chrome Javascript issue in getting user audio - The AudioContext was not allowed to start](https://stackoverflow.com/questions/55026293/google-chrome-javascript-issue-in-getting-user-audio-the-audiocontext-was-not) – ggorlen Jul 31 '21 at 17:19

1 Answers1

11

Yes, the warning is because you did not create the context in a user gesture. I find the warning quite annoying because it is not wrong to create the context without a user gesture. What is not allowed is starting/resuming the context without a user gesture.

Since you resume the context with a user click, everything is fine.

I would ignore it. Or create the context with a click or other user gesture.

I wish Chrome would fix the warning so that it only shows up when you try to resume a context without a user gesture.

Raymond Toy
  • 5,490
  • 10
  • 13
  • 1
    Does it mean I can not load my audio before the click event ? Because the idea was to load my audio inside a BufferSource before the user click to play the song – Michaël Mar 26 '21 at 08:09
  • You should be able to load audio. You are only blocked from playing audible sounds until you use a user-gesture to resume a context or to start your AudioBufferSourceNode. (If you do these without a gesture, it may look like things are working, but they're not and you won't hear anything.) – Raymond Toy Mar 31 '21 at 20:41
  • firefox does it too. – chovy Jun 01 '23 at 11:57