Home > Web Front-end > H5 Tutorial > body text

H5 page audio and video automatically plays

高洛峰
Release: 2016-10-20 13:33:55
Original
2897 people have browsed it

Pure H5 pages cannot realize automatic playback on mobile phones. Most mobile browsers disable the autoplay function of video and audio
In addition, many mobile browsers do not support the first js call to the play method for playback (only the user manually clicks You can pause after playing and then use code to play).
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();
    }
}
Copy after login


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!