简体   繁体   English

Android不会间隔播放html5音频

[英]Android not playing html5 audio from an interval

I'm trying to play audio using a HTML5 Audio tag on my phone. 我正在尝试使用手机上的HTML5音频标签播放音频。 I've loaded the sound but when I run the .play() command, nothing happens. 我加载了声音,但是当我运行.play()命令时,没有任何反应。 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. 我也试过通过从地址栏执行javascript来播放声音,这也是有效的。

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. 如果您将播放代码放入按钮单击事件中,它应该可以工作(假设代码中没有其他错误),但设备阻止您的音频从setInterval内部播放,因为它不认为它具有用户的权限发挥它。

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 . 我现在做了什么,我承认这是一个解决方法,我播放并立即停止我的按钮点击事件中的音频,然后调用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. 尽可能寻求替代方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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