Home >Web Front-end >H5 Tutorial >H5 page audio and video automatically plays

H5 page audio and video automatically plays

高洛峰
高洛峰Original
2016-10-20 13:33:552934browse

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();
    }
}


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
Previous article:HTML5+CSS3Next article:HTML5+CSS3