HTML5 Video autoplay on iPhone

后端 未结 4 744
离开以前
离开以前 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

    0 讨论(0)
  • I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.

    1. Using dangerouslySetInnerHtml to embed the <video> code. For example:
    <div dangerouslySetInnerHTML={{ __html: `
        <video class="video-js" playsinline autoplay loop muted>
            <source src="../video_path.mp4" type="video/mp4"/>
        </video>`}}
    />
    
    1. Resizing the video weight. I noticed my iPhone does not autoplay videos over 3 megabytes. So I used an online compressor tool (https://www.mp4compress.com/) to go from 4mb to less than 500kb

    Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)

    0 讨论(0)
  • 2020-11-29 19:56

    Does playsinline attribute help?

    Here's what I have:

    <video autoplay loop muted playsinline class="video-background ">
      <source src="videos/intro-video3.mp4" type="video/mp4">
    </video>
    

    See the comment on playsinline here: https://webkit.org/blog/6784/new-video-policies-for-ios/

    0 讨论(0)
  • 2020-11-29 19:59

    iOs 10+ allow video autoplay inline. but you have to turn off "Low power mode" on your iPhone.

    0 讨论(0)
提交回复
热议问题