Joshua Comeau
Joshua Comeau

Reputation: 2753

Silencing AudioContext warning around suspended mode

I have some JS code that looks like this:

class AudioSample {
  constructor(volume = 1, playbackRate = 1) {
    this.context = new AudioContext();
  }

  load(arrayBuffer) {
    return new Promise((resolve, reject) => {
      this.context.decodeAudioData(
        arrayBuffer,
        buffer => {
          this.buffer = buffer;

          resolve(buffer);
        },
        reject
      );
    });
  }
  // Other stuff
}

// When the page loads
const sample = new AudioSample();

fetch('/some-sound.mp3')
  .then(res => res.arrayBuffer())
  .then(arrayBuffer => sample.load(arrayBuffer));

// When a button is clicked
const play = () => {
  sample.current.pause();
  sample.current.setCurrentTime(0);
  sample.current.play();
};

This code works as intended; when the page loads, it fetches and prepares the sounds. When the button is clicked, the sound plays (even on the very first time).

My problem is that the following warning is logged in the Chrome console:

The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio

This warning is a bit of a problem because I want to package up this little utility, but I don't want my NPM package to be throwing red-herring warnings!

Is there any way to tell the browser "I know, don't worry, I won't play the sound until a user interacts with the page"?

Upvotes: 3

Views: 1313

Answers (2)

jameshfisher
jameshfisher

Reputation: 36519

I worked around this Chrome bug by using a separate OfflineAudioContext for decoding. The OfflineAudioContext does not log a warning on initialization.

Upvotes: 2

Raymond Toy
Raymond Toy

Reputation: 6056

For chrome, the only way to get rid of the warning is to create the context from a user gesture. See also the chrome bug 943258

It would be nice if that bug were fixed. As the bug says, creating a context without a gesture is not wrong. Only resuming it without a gesture is wrong.

Upvotes: 5

Related Questions