MP3 does not work in Javasccript

Asked

Viewed 66 times

2

I want mp3 to be triggered when entering the html page, but it is giving error and does not work.

The code in javascript:

var audio, playbtn;

function initAudioPlayer(){
    audio = new Audio();
    audio.src = "audio/Loka%20ft%20Anitta.mp3";
    audio.loop = true;
    audio.play();
    
    }
window.addEventListener("load", initAudioPlayer);

Javascript responds in the console:

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. 
initAudioPlayer @ audioproj.js:9
load (async)
(anonymous) @ audioproj.js:12

  • Your code ran perfectly here, see if this answer in English helps you: https://stackoverflow.com/questions/49930680/how-to-handle-uncaught-in-promise-domexception-play-failed-because-the-use

1 answer

5

Chrome has changed the behavior relative to video and audio to prevent the sound from starting automatically by opening a page. Both in audio and video it is now only possible to start "producing" sound within a function that occurs from an DOM event. You can start playing the video but without sound, with the attribute muted. Already audio is blocked from playing if there is no user generated event.

In Javascript is the property audio.muted = true.

More about this (in English): https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

var audio, playbtn;

function initAudioPlayer() {
  audio = new Audio();
  audio.src = "//www.soundhelix.com/examples/mp3/SoundHelix-Song-13.mp3";
  audio.loop = true;
  audio.play();

}
window.addEventListener("load", initAudioPlayer);
playbtn = document.querySelector('#play');
mute = document.querySelector('#mute');

playbtn.addEventListener('click', (e) => {
  audio.paused ? audio.play() : audio.pause();
  e.target.textContent = audio.paused ? 'Play' : 'Pause';
})

mute.addEventListener('click', (e) => {
  audio.muted = !audio.muted;
  e.target.textContent = audio.muted ? 'Unmute' : 'Mute';
})
<button type="button" id="play">Play</button>
<button type="button" id="mute">Mute</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.