0

I am trying the following

import campFire from "../assets/audio/fire.ogg";
import forestAmbience from "../assets/audio/ambience.ogg";

const AudioData = {
   loops: [new Audio(campFire), new Audio(forestAmbience)]
};

class AudioManager {
    constructor(loops){
       //initialise our looping sounds
       this._loops = loops;
       this._currentlyPlaying = "Not playing";
       //start looping sounds
       this.BeginLoops();
    }
  
   //starts playing the sounds which simply loop
   BeginLoops(){
       for (let audio  of this._loops){
          audio.autoplay = true;
          audio.muted = true;
          audio.play();
       }
       this._currentlyPlaying = "Loops playing";
   }
   CurrentlyPlaying() {
       return this._currentlyPlaying;
   }
}

export const SoundscapeManager = new AudioManager(AudioData.loops);

But I get this error message from Chrome: Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first..

I am creating a React.js project. I import SoundscapeManager into a component which I expect to create an instance of AudioManager passing the two sound files defined in AudioData.

import { SoundscapeManager } from "../modules/Audio";

export const Soundscape = () => {

    return (
        <div>{SoundscapeManager.CurrentlyPlaying()}</div>
    );
};

As per answers to other questions about this error I have set autoplay and muted properties of HTMLAudioElement to true. But for some reason I still get the error.

In addition I have tried running this in Firefox and while I don't get the error message, the sound still doesn't play.

Am I doing something wrong?

  • As the error says, you can't start playing audio before the user has interacted with the document. Also, if you set `muted`, you obviously won't hear the audio... – AKX Feb 12 '23 at 13:25
  • @AKX I would divert you to this thread: https://stackoverflow.com/questions/49930680/how-to-handle-uncaught-in-promise-domexception-play-failed-because-the-use. I am taking on board the answer there. The muted property is required to be false to autoplay without user interaction. While the error says that a user must interact, it is possible to play audio without that interaction and I am trying to implement a work around. – Fohristiwhirl Feb 12 '23 at 13:37

0 Answers0