HTML5 Video autoplay on iPhone

后端 未结 4 745
离开以前
离开以前 2020-11-29 19:19

I have some kind of a strange problem. I try to create a website with a looped background video. The code looks like this one:

4条回答
  •  星月不相逢
    2020-11-29 19:41

    Here is the little hack to overcome all the struggles you have for video autoplay in a website:

    1. Check video is playing or not.
    2. Trigger video play on event like body click or touch.

    Note: Some browsers don't let videos to autoplay unless the user interacts with the device.

    So scripts to check whether video is playing is:

    Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
    get: function () {
        return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
    }});
    

    And then you can simply autoplay the video by attaching event listeners to the body:

    $('body').on('click touchstart', function () {
            const videoElement = document.getElementById('home_video');
            if (videoElement.playing) {
                // video is already playing so do nothing
            }
            else {
                // video is not playing
                // so play video now
                videoElement.play();
            }
    });
    

    Note: autoplay attribute is very basic which needs to be added to the video tag already other than these scripts.

    You can see the working example with code here at this link:

    How to autoplay video when the device is in low power mode / data saving mode / safari browser issue

提交回复
热议问题