0

I have a react app and in that there's a component called AudioComponent. I want to play an audio when that component loads. My code for the AudioComponent is as follow.

import mp3 from './Hymn.mp3'
    
function AudioComponent() {

     const audio = new Audio(mp3)

     useEffect(() => {
        audio.play()
      }, [])
      
        return (
          <div className="pp">
            
      This is the Audio component

    <div >

    </div>
 
          </div>
        );
      }
      
      export default AudioComponent;

when running the app the following error shows in the console.

AudioComponent.jsx:41 Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

I want to play the audio when ever the audio component is used without any user interactions. what might be the issue?

Mohd
  • 1
  • 2
  • *I want to play the audio when ever the audio component is used without any user interactions* - yet the error states *play() failed because the user didn't interact with the document first* - clearly your browser doesn't allow what you want – Bravo Feb 28 '22 at 08:54
  • I tried with several browsers. all shows the same error – Mohd Feb 28 '22 at 09:01
  • 1
    maybe https://stackoverflow.com/questions/49930680/how-to-handle-uncaught-in-promise-domexception-play-failed-because-the-use - or just research yourself using the phrase "play failed because the user didn't interact with the document first" for a wealth of dubious information – Bravo Feb 28 '22 at 09:11
  • I understand. I want to play the sound without interacting with the document. the same code works for me if I interacted with the document using an event listener or adding a button. I want this to play without any interactions – Mohd Feb 28 '22 at 09:17
  • 1
    yes, but it seems that's not allowed in modern browsers - have you researched the issue like I suggested? google "play failed because the user didn't interact with the document first" and do some research – Bravo Feb 28 '22 at 09:19

0 Answers0