Kevin
Kevin

Reputation: 101

How to consistently enable sound in reactjs?

I have a code that plays a sound when receiving a broadcast from an action cable

  const enableSound = () => {
    var audioCtx = new AudioContext();

    if (audioCtx) {
      audioCtx.resume().then(() => {
        window.context = audioCtx
      }).catch(() => {
        window.context = audioCtx
      });
    }
  }

  useEffect(() => {
    var context = new AudioContext();
    window.context = context;

    document.body.addEventListener('click', enableSound );

    return () => {
      document.body.removeEventListener('click', enableSound );
    }
  },[]);

  // This is called when the action cable is received. 
  const playSound = (payload) => {
        const audio = new Audio('url_sound_here');
        audio.play();
  }

The sound is played when the user receives a broadcast from the action cable and interacts with the page beforehand.

My struggle is that sometimes it requires a few clicks before the sound is played, especially on mobile. It also happens when the tab has been inactive for a while and becomes active again. It's not consistent at times, sometimes it won't work and requires a refresh.

The action cable seems fine. It's when playing the sound is the issue. I'm not sure what the cause is.

Edit 2/10/25:

Upvotes: 0

Views: 21

Answers (0)

Related Questions