0

i'm building a dashboard in which user get notified(by sound) for new orders , so i want audio to play without letting user click any button
noticed this problem : "play() failed because the user didn't interact with the document first" .
tried answers from these posts but non of them worked same problem
link1
link2
link3
link4
link5

my google Chrome Version 80.0.3987.132 (Official Build) (64-bit)

code:

HTML

<div><audio src="../audio/message.mp3" id="mainaudio"></audio>
<button id="btn" hidden> clicked automatically</button></div>

JQuery

$('#btn').click(function(){document.getElementById("mainaudio").play();});
setInterval(function(){

var oldreq=$("[name='show-order[]'] span").html();
var oldsugg=$("[name='show-sugg[]'] span ").html();

$.ajax({
        url:"../include/uid.php",
        type:"post",
        data:"method=reloadNav&oldOrder="+oldreq+"&oldSug="+oldsugg,
        success:function(data){
            var js=$.parseJSON(data);
            if(js.notify == 1){
                $("#btn").click();
            }
            $("[name='show-order[]'] span").html(js.order);
            $("[name='show-sugg[]'] span").html(js.sug) ;  
        },
        error:function(){
            alert("ajax error");
        }
    })


},5000);
Ruaa Elias
  • 27
  • 1
  • 2
  • 9

1 Answers1

0

You can start playing music a few seconds after loading the page

$(window).on( "click", function() { //prevent 'no interact error'
    setTimeout(function() { // start play after 5 sec
        var el = document.getElementById("mainaudio");
        if(el.paused){ //check if music dont play now
            el.play();
        }
        else{
            console.log('already playing!');
        }
    }, 5000);
});
Arthur Veselov
  • 1,167
  • 10
  • 9