5

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);
GramThanos
  • 3,572
  • 1
  • 22
  • 34
Mark Zhiu
  • 53
  • 1
  • 6
  • Possible duplicate of [Audio Tag Autoplay Not working in mobile](https://stackoverflow.com/questions/34837930/audio-tag-autoplay-not-working-in-mobile) – yuval.bl Jul 01 '19 at 11:31
  • I'm just gonna add that automatically playing audio can cause a very bad user experience. But I don't know what it's for. A music app is fine, but if its for ads or something it could be very annoying – Martijn Vissers Jul 01 '19 at 13:05
  • I don't think that what you are trying to do is blocked by the browser. Also, your code have some problems, check if audio is loaded before trying playing it, stop audio when the responce is false and reset the currentTime on your 'ended' event. – GramThanos Jul 01 '19 at 13:40
  • Great question. The optimal solution would be to ask the user for a one-time consent dialog to allow auto playing sounds on this specific page. – Nathan B Jul 14 '21 at 07:13

1 Answers1

6

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>
GramThanos
  • 3,572
  • 1
  • 22
  • 34