Mark Zhiu
Mark Zhiu

Reputation: 53

Request permission to automatically play an audio file

I have a function in js that checks a variable date, and if it is present it starts an audio file.

Since with the new privacy it is not possible to start an audio file automatically, in fact in my case it is blocked. I would like to have the broswer box appear to give consent to the reproduction of the audio file.

But, I do not know how can I do it. Can you help me?

var audio = new Audio('/sound/file-one.mp3');

setInterval(function() {
    $.ajax({
        url: '/check_data.php',
        type: 'post',
        data: {
            'check_data' : 1
        },
        success: function(response){
            if (response != "false") {
                audio.addEventListener('ended', function () {
                    audio.play();
                }, false);
                audio.play();
            }
        }
    });
}, 5000);

Upvotes: 5

Views: 12140

Answers (1)

User must start Audio, after Audio is started by a user action, you can change source whenever you want.

const audio = document.getElementById("au");
let bt = document.getElementById("bt");
console.log(audio);
bt.addEventListener("click", ()=>{
  audio.play();
});
const startPlaying = ()=>{
  audio.removeEventListener('playing', startPlaying);
  bt.classList.add("hide");
  audio.src = 'https://freesound.org/data/previews/475/475736_4397472-lq.mp3';
  audio.play();
}
audio.addEventListener('playing', startPlaying);
audio.addEventListener('error', ()=>{
  console.log("error");
});
.hide{
  display:none;
}
<input id="bt" type="button" value="Accept">
<audio id="au" preload="auto" src="https://raw.githubusercontent.com/anars/blank-audio/master/500-milliseconds-of-silence.mp3"></audio>

Upvotes: 9

Related Questions