Solve the problem that audio in HTML5 can’t play automatically on mobile phone and wechat

Time:2020-1-16

When doing the H5 page again, I found that audio can’t play automatically after autoplay is added to the mobile phone and wechat. This is because the mobile phone is set to save vagrancy

The usual solution is to give an interactive event:

Label:


<audio loop src="/photo/aa.mp3" id="audio" autoplay preload="auto">

The browser does not support audio property < / audio >

resolvent:

//--Create a page monitor and wait for the wechat page to load to trigger the audio playback
document.addEventListener('DOMContentLoaded', function () {
    function audioAutoPlay() {
        var audio = document.getElementById('audio');
            audio.play();
        document.addEventListener("WeixinJSBridgeReady", function () {
            audio.play();
        }, false);
    }
    audioAutoPlay();
});
//--Create touch monitor. When the browser opens the page, touch the screen to trigger the event and play the audio
document.addEventListener('touchstart', function () {
    function audioAutoPlay() {
        var audio = document.getElementById('audio');
            audio.play();
    }
    audioAutoPlay();
});

There is also a solution for Apple’s mobile wechat

Step 1: introduce JS file


<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

Step 2: Profile


<script>
        function autoPlayVideo(){
            wx.config({
                debug:false,
                appId:"",
                timestamp:1,
                nonceStr:"",
                signature:"",
                jsApiList:[]
            });
            wx.ready(function(){
                var autoplayVideo=document.getElementById("audio");
                autoplayVideo.play()
            })
        };
        autoPlayVideo();
</script>

In this way, it can play automatically when the network is stable.

summary

The above is what Xiaobian introduced to you to solve the problem that audio in HTML5 can’t play automatically on the mobile phone and wechat, hoping to help you. If you have any questions, please leave a message to me, and Xiaobian will reply to you in time. Thank you very much for your support of the developepaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!