关于移动端audio自动播放问题

本人小白全栈一枚,给公司写了一个监控中心,要求严重报警的时候需要触发音频播放,于是就有了以下的折腾。

刚开始一切都很顺利,自然而然的写了以下代码。

<audio id="myaudio" >
    <source src="/static/warn.mp3" type="audio/mpeg">
</audio>

<script>
var tt;
function audioPlay(){
    document.getElementById("myaudio").play();
    tt = setTimeout(audioPlay, 5000);
}

function audioLoad(){
    document.getElementById("myaudio").pause();
}
</script>

// 触发播放
audioPlay();

//清除定时任务
clearTimeout(tt);

  

随意在PC端测试了下,完美,然后我就没管它了....直到有一天,一时兴起拿起手机打开来看,结果发现没声音。PC端是正常的,没理由手机不行,初步怀疑是浏览器音频兼容性问题。

经过多方查证,居然是移动端做了限制,一定要用户交互才能触发,网上的解决方案大多是通过touchstart事件。

附上一个简单的JS做参考

https://github.com/MauriceButler/simple-audio

至于最终的解决方案..因为我这边只是内部使用,所以选择了万能的谷歌浏览器

chrome://flags/#disable-gesture-requirement-for-media-playback

开启这个flags完美解决。

原文地址:https://www.cnblogs.com/letong/p/4925785.html