javascriptreactjshowler.js

How to play audio onload in react using Howler library?


I was trying to figure out why the audio is not running onload of webpage until an event such as mouse click is triggered somewhere on the screen. The audio plays but I want to play the audio as soon as the page loads.

import React, { useEffect } from "react";
import Muse from "./assets/music.mp3";
import { Howl, Howler } from "howler";

function Aud() {
  const sound = new Howl({
    src: Muse,
  });

  useEffect(() => {
    console.log("In useEffect");
    sound.play();
    Howler.volume(0.5);
  }, []);

  return <div></div>;
}

export default Aud;

useEffect executes but for some reason the sound doesn't play. Any help would be appreciated.


Solution

  • This is default behaviour for recent versions of Chrome. The user must Interact with the page before any video/audio can be played. If you check the console, you may see the error message. You may want to try setting autoplay attribute.