Home  >  Article  >  Web Front-end  >  How to implement HTML5 page audio and video to automatically play under WeChat and app

How to implement HTML5 page audio and video to automatically play under WeChat and app

不言
不言Original
2018-06-11 16:20:223587browse

Now most H5 pages have the function of playing background music and playing videos. So how to implement automatic playback? The following brings you how to implement automatic playback of audio and video on HTML5 pages under WeChat and apps

Nowadays, most H5 pages have the function of playing background music and playing videos. So how to implement automatic playback?

Pure H5 pages cannot realize automatic playback on mobile phones. Most mobile browsers disable the autoplay function of video and audio. Moreover, many mobile browsers do not support the first js call to the play method for playback ( Only the user manually clicks playback, pauses it, and then uses code to play it.)

This is mainly done to prevent unnecessary automatic playback from wasting traffic.

The following code is to implement playback after the user’s first touch and automatic playback under the WeChat app

function autoPlayMusic() {   
    /* 自动播放音乐效果,解决浏览器或者APP自动播放问题 */   
    function musicInBrowserHandler() {   
        musicPlay(true);   
        document.body.removeEventListener('touchstart', musicInBrowserHandler);   
    }   
    document.body.addEventListener('touchstart', musicInBrowserHandler);   
    /* 自动播放音乐效果,解决微信自动播放问题 */   
    function musicInWeixinHandler() {   
        musicPlay(true);   
        document.addEventListener("WeixinJSBridgeReady", function () {   
            musicPlay(true);   
        }, false);   
        document.removeEventListener('DOMContentLoaded', musicInWeixinHandler);   
    }   
    document.addEventListener('DOMContentLoaded', musicInWeixinHandler);   
}   
function musicPlay(isPlay) {   
    var media = document.getElementById('myMusic');   
    if (isPlay && media.paused) {   
        media.play();   
    }   
    if (!isPlay && !media.paused) {   
        media.pause();   
    }   
}

The above is the entire content of this article, I hope it will be helpful to everyone’s learning, more Please pay attention to the PHP Chinese website for related content!

Related recommendations:

How to use HTML5 to realize the function of sharing to WeChat friends circle QQ friends QQ space Weibo QR code

HTML5 implements the method of using buttons to control the background music switch

The above is the detailed content of How to implement HTML5 page audio and video to automatically play under WeChat and app. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn