Home > Blockchain >  Need help getting Web Audio to play from a Javascript file
Need help getting Web Audio to play from a Javascript file

Time:12-26

I am trying to get an audio file to play from my Javascript file.

I have this line in my HTML File within the Body section:

<audio id="play" src="https://freesound.org..."></audio>

In my JS file I make these calls:

var audio = document.getElementById("play");
audio.play();

Now, when I run my code through the Browser, I get this error:

Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

What does this mean? Where can I reference audio that the Web Server allows access?

CodePudding user response:

From https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play:

NotAllowedError DOMException Provided if the user agent (browser) or operating system doesn't allow playback of media in the current context or situation. This may happen, for example, if the browser requires the user to explicitly start media playback by clicking a "play" button.

Nowadays, fortunately, website are no longer allowed to just start playing audio when you open them. The user first needs to interact with the page in some way. If you use the same code in a click-handler of a button, e.g., it should work.

CodePudding user response:

It might be the website refuse your request but there is other way to do it. You can put the music file to your project folder and then type the folder path the music file in to src path in audio tag.

  • Related