简体   繁体   中英

video doesn't autoplay after use react-snap

I have a video run in the background in my react app. It works perfectly and auto-plays on page load.

here is the code JSX I have used.

  <video
    autoPlay
    loop
    style={{
      backgroundImage: `url(${topVideoImage})`,
    }}
    muted
    playsInline
  >
    <source type="video/mp4" src={topVideo} />
  </video>

It doesn't auto play after I use react-snap . my package.json looks like this:

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "postbuild": "react-snap",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

It works after I remove "postbuild": "react-snap", . How can I solve (autoplay the video on load) this without removing react-snap ?

I found a solution to this problem. According to this muted is now required for chrome to autoplay the video on load. We can mute video using muted attribute But react-snap is not processing again now. So we have to manually set muted attribute to true .

For that, I have used this simple hack.

const makeMuted = (elt) => {
  if (elt) {
    elt.muted = true;
  }
};
export const LandingPage = (props) => {
     return ( <video
        id="background-video"
        autoPlay
        loop
        ref={makeMuted}
        playsInline
      >
        <source type="video/mp4" src={topVideo} />
      </video>)
}

I ran into this same issue even when explicitly setting muted to true in JSX as well as programmatically using Javascript.

Instead of using the autoPlay attribute, consider combining the .play() method with either or both of the following.

1. canplay event

The video's canPlay event will fire off once enough of the video has been downloaded to begin playback without likely encountering any buffering issues.

elt.addEventListener("canplay", () => {
  elt.play();
})

2. readyState attribute

The video's readyState attribute will have a value of 4 if enough of the video has been downloaded to begin playback without likely encountering any buffering issues.

if(elt.readyState > 4){
  elt.play()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM