javascriptreactjsgoogle-chromeaudiocontexthowler.js

Howler JS & React AudioContext console warning


I am using howler.js in a simple component which renders a button to play an audio file

In the console I am receiving the below warning:

AudioContext error

"The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page.

The sound is playing without any issue, but I cannot get rid of this warning

According to the warning a gesture needs to be performed, which I thought clicking the button would provide

Here is the code from the component:

import React from "react";
import { useState } from "react";
import { Howl } from "howler";

export const Sound = ({ name, path }) => {
  const [playing, setPlaying] = useState(false);

  const Sound = new Howl({
    src: [path],
  });

  const playSound = () => {
    setPlaying(true);
    Sound.play();
  };

  return (
    <div>
      <button onClick={() => playSound()}>{name}</button>
      <p>{playing ? "playing" : "Not playing"}</p>
    </div>
  );
};

I have checked multiple questions / forums / github issues but I can't find a solution

Any help or information on why this is showing up is appreciated!

Thanks!


Solution

  • I think in this case you can ignore this warning. It's triggered because howler.js creates an AudioContext upfront.

    https://github.com/goldfire/howler.js/blob/4537db79b3dca9ed490ee22cbb17048d4cba7316/src/howler.core.js#L2517

    That AudioContext gets automatically resumed when calling play().

    https://github.com/goldfire/howler.js/blob/4537db79b3dca9ed490ee22cbb17048d4cba7316/src/howler.core.js#L822

    Therefore the warning is annoying but already taken care of by the authors of howler.js. But if you really want to get rid of the warning you can lazily initialize the Sound variable right before playing it.

    // ...
    let Sound;
    
    const playSound = () => {
        setPlaying(true);
    
        if (Sound === undefined) {
            Sound = new Howl({
                src: [path]
            });
        }
    
        Sound.play();
    };
    // ...
    

    That should make the warning go away.