简体   繁体   中英

Android not playing html5 audio from an interval

I'm trying to play audio using a HTML5 Audio tag on my phone. I've loaded the sound but when I run the .play() command, nothing happens. I made the default controls visible so that I test by pressing that play button and that one works and the sound plays. I've also tried playing the sound by executing the javascript from the address bar and that works aswell.

The code I'm using to play looks something like this:

setInterval(function(){
    if(blahblah){
        document.getElementById("player").play();
    }
},500);

To make sure that it even tries to play the sound, I put an alert after it, like this:

setInterval(function(){
    if(blahblah){
        document.getElementById("player").play();
        alert("Played!");
    }
},500);

I saw the alert, but no sound was played.

Thanks for any help :)

Most mobile devices will only allow you to play audio when it is the result of a user interaction . If you put your play code into a button click event, it should work (assuming you have no other bugs in the code), but the device is preventing your audio from playing from inside setInterval because it doesn't think it has the user's permission to play it.

What I do now, and I admit this is a workaround, is I play and immediately stop the audio inside my button click event, and then call setInterval . It works--for now--because the device thinks it has been granted permission to play that audio by the user, even if I trigger it later. The code inside my button click event looks like this:

document.getElementById("player").play();
document.getElementById("player").pause();

setInterval(function(){
    document.getElementById("player").play();
}, 500);

Keep in mind that on mobile, it may not play nearly as smoothly as it does on your computer. Seek alternative approaches where possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM