使用 React 让 YouTube 视频自动播放

Make YouTube video autoplay using React

我正在尝试使用 React 让我的视频自动播放。添加 autoplay=1 作为参数不起作用。有什么建议吗?`

这是我的代码。

<div
  className="video mt-5"
  style={{
         position: "relative",
         paddingBottom: "56.25%" /* 16:9 */,
         paddingTop: 25,
         height: 0
       }}
>
    <iframe
       style={{
             position: "absolute",
             top: 0,
             left: 0,
             width: "100%",
             height: "100%"
             }}
        src={'https://www.youtube.com/embed/hEnr6Ewpu_U?'}
        frameBorder="0"
    />
</div>

我不会使用 <iframe> 因为当你去 Youtube 时你仍然需要点击才能播放。我会使用一个名为 react-player

的库
import ReactPlayer from "react-player";

<ReactPlayer
  url={props.url}
  playing={true}
  width={props.width}
  height={props.height}
/>

它会自动播放 :)

根据 2018 年 YouTube 政策的变化,他们省略了自动播放有声视频的选项。如果您想自动静音播放,仍然可以选择使用 iframe 来实现:

<iframe src='https://www.youtube.com/embed/hEnr6Ewpu_U?autoplay=1&mute=1'
        frameBorder='0'
        allow='autoplay; encrypted-media'
        allowFullScreen
        title='video'
/>

这帮我解决了

如果你在 react

中使用 <video>
  • 使用 autoPlay 而不是 autoplay 进行反应。
  • 同时添加muted

<video autoPlay muted src="/vid.mp4" />

如果要使用小写的autoplay,应该赋值为autoplay="true"