如何在 iframe 中嵌入自动播放的 YouTube 视频?

发布于 2024-12-02 18:20:45 字数 121 浏览 3 评论 0原文

我正在尝试嵌入 YouTube 视频的新 iframe 版本并使其自动播放。

据我所知,没有办法通过修改 URL 的标志来做到这一点。有没有办法通过使用 JavaScript & 来做到这一点? API?

I am trying to embed the new iframe version of a YouTube video and get it to auto play.

As far as I can tell, there is no way of doing this by amending flags to the URL. Is there a way to do it by using JavaScript & the API?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

筑梦 2024-12-09 18:20:46

这适用于 Chrome,但不适用于 Firefox 3.6(警告:RickRoll 视频):

<iframe width="420" height="345" src="http://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1" frameborder="0" allowfullscreen></iframe>

用于 iframe 嵌入的 JavaScript API存在,但仍作为实验性功能发布。

更新:现已完全支持 iframe API,并且“创建 YT.Player 对象 - 示例 2” 展示了如何在 JavaScript 中设置“自动播放”。

This works in Chrome but not Firefox 3.6 (warning: RickRoll video):

<iframe width="420" height="345" src="http://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1" frameborder="0" allowfullscreen></iframe>

The JavaScript API for iframe embeds exists, but is still posted as an experimental feature.

UPDATE: The iframe API is now fully supported and "Creating YT.Player objects - Example 2" shows how to set "autoplay" in JavaScript.

堇色安年 2024-12-09 18:20:46

自 2018 年 4 月起,Google 对自动播放政策。您不仅需要添加 autoplay=1 作为查询参数,还需要添加 allow='autoplay' 作为 iframe 的属性,

因此您必须执行以下操作:

<iframe src="https://www.youtube.com/embed/VIDEO_ID?autoplay=1" allow='autoplay'></iframe>

Since April 2018, Google made some changes to the Autoplay Policy. You not only need to add the autoplay=1 as a query param, but also add allow='autoplay' as an iframe's attribute

So you will have to do something like this:

<iframe src="https://www.youtube.com/embed/VIDEO_ID?autoplay=1" allow='autoplay'></iframe>
我ぃ本無心為│何有愛 2024-12-09 18:20:46

2018 年 8 月,我没有找到有关 iframe 实现的工作示例。
其他问题仅与 Chrome 相关,这暴露了一些信息。

您必须将声音静音 mute=1 才能在 Chrome 上自动播放。使用 autoplay=1 作为参数,FF 和 IE 似乎工作得很好。

<iframe src="//www.youtube.com/embed/{{YOUTUBE-ID}}?autoplay=1&mute=1" name="youtube embed" allow="autoplay; encrypted-media" allowfullscreen></iframe>

August 2018 I didn't find a working example on the iframe implementation.
Other questions were related to Chrome only, which gave it away a little.

You'll have to mute sound mute=1 in order to autoplay on Chrome. FF and IE seem to be working just fine using autoplay=1 as parameter.

<iframe src="//www.youtube.com/embed/{{YOUTUBE-ID}}?autoplay=1&mute=1" name="youtube embed" allow="autoplay; encrypted-media" allowfullscreen></iframe>

YouTube 的嵌入代码默认关闭自动播放。只需在“src”属性末尾添加 autoplay=1 即可。例如:

<iframe src="http://www.youtube.com/embed/xzvScRnF6MU?autoplay=1" width="960" height="447" frameborder="0" allowfullscreen></iframe>

The embedded code of youtube has autoplay off by default. Simply add autoplay=1at the end of "src" attribute. For example:

<iframe src="http://www.youtube.com/embed/xzvScRnF6MU?autoplay=1" width="960" height="447" frameborder="0" allowfullscreen></iframe>
年少掌心 2024-12-09 18:20:46

2014 iframe 嵌入如何嵌入具有自动播放功能的 YouTube 视频,并且剪辑末尾没有建议视频

rel=0&autoplay 

示例如下: 。

<iframe width="640" height="360" src="//www.youtube.com/embed/JWgp7Ny3bOo?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

2014 iframe embed on how to embed a youtube video with autoplay and no suggested videos at end of clip

rel=0&autoplay 

Example Below: .

<iframe width="640" height="360" src="//www.youtube.com/embed/JWgp7Ny3bOo?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
深海里的那抹蓝 2024-12-09 18:20:46

在 iframe src 的末尾,添加 &enablejsapi=1 以允许在视频上使用 js API

,然后使用 jquery:

jQuery(document).ready(function( $ ) {
  $('.video-selector iframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
});

这应该在 document.ready 上自动播放视频

注意,您还可以在单​​击功能中使用此功能来单击另一个元素来启动视频

更重要的是,您无法在移动设备上自动启动视频,因此用户始终必须单击视频播放器本身来启动视频

编辑:
实际上,我不能 100% 确定 document.ready iframe 是否已准备好,因为 YouTube 仍可能正在加载视频。我实际上是在点击函数中使用这个函数:

$('.video-container').on('click', function(){
  $('video-selector iframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
  // add other code here to swap a custom image, etc
});

at the end of the iframe src, add &enablejsapi=1 to allow the js API to be used on the video

and then with jquery:

jQuery(document).ready(function( $ ) {
  $('.video-selector iframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
});

this should play the video automatically on document.ready

note, that you could also use this inside a click function to click on another element to start the video

More importantly, you cannot auto-start videos on a mobile device so users will always have to click on the video-player itself to start the video

Edit:
I'm actually not 100% sure on document.ready the iframe will be ready, because YouTube could still be loading the video. I'm actually using this function inside a click function:

$('.video-container').on('click', function(){
  $('video-selector iframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
  // add other code here to swap a custom image, etc
});
幼儿园老大 2024-12-09 18:20:46

此处记录了可与 IFRAME 和 OBJECT 嵌入一起使用的标志或参数;还明确提到了哪些参数适用于哪些播放器的详细信息:

YouTube 嵌入式播放器和播放器参数

您会注意到autoplay。

The flags, or parameters that you can use with IFRAME and OBJECT embeds are documented here; the details about which parameter works with what player are also clearly mentioned:

YouTube Embedded Players and Player Parameters

You will notice that autoplay is supported by all players (AS3, AS2 and HTML5).

源来凯始玺欢你 2024-12-09 18:20:46

为那些不知道的人(过去的我和未来的我)提供多个查询提示

如果您使用 URL 进行单个查询,只需 ?autoplay=1 即可 如 mjhm 的回答所示

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1"></iframe>

如果您要进行多个查询,请记住第一个查询以 ? 开头,而其余查询则以&

假设您想关闭相关视频但启用自动播放...

这可行

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?rel=0&autoplay=1"></iframe>

,这可行,

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1&rel=0"></iframe>

但这些行不通..

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?rel=0?autoplay=1"></iframe>

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0&autoplay=1&rel=0"></iframe>

示例比较

https://jsfiddle.net/Hastig/p4dpo5y4/

更多信息

阅读 NextLocal 的回复有关使用多个查询字符串的更多信息,请参见下文

Multiple queries tip for those who don't know (past me and future me)

If you're making a single query with the url just ?autoplay=1 works as shown by mjhm's answer

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1"></iframe>

If you're making multiple queries remember the first one begins with a ? while the rest begin with a &

Say you want to turn off related videos but enable autoplay...

This works

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?rel=0&autoplay=1"></iframe>

and this works

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1&rel=0"></iframe>

But these won't work..

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?rel=0?autoplay=1"></iframe>

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0&autoplay=1&rel=0"></iframe>

example comparisons

https://jsfiddle.net/Hastig/p4dpo5y4/

more info

Read NextLocal's reply below for more info about using multiple query strings

゛时过境迁 2024-12-09 18:20:46

为了让 mjhm 在 2018 年 5 月在 Chrome 66 上工作时接受的答案,我将 allow=autoplay 添加到 iframe 并将 enable_js=1 添加到查询字符串:

<iframe allow=autoplay width="420px" height="345px" src="http://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1&enable_js=1"></iframe>

To have the accepted answer by mjhm working on Chrome 66 in May 2018, I added allow=autoplay to the iframe and enable_js=1 to the query string:

<iframe allow=autoplay width="420px" height="345px" src="http://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1&enable_js=1"></iframe>
我的鱼塘能养鲲 2024-12-09 18:20:46

现在我在 iframe 标签上添加了一个新属性“allow”,例如:

allow="加速度计;自动播放;加密媒体;陀螺仪;
画中画”

最终代码为:

<iframe src="https://www.youtube.com/embed/[VIDEO-CODE]?autoplay=1" 
frameborder="0" style="width: 100%; height: 100%;"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"></iframe>

Nowadays I include a new attribute "allow" on iframe tag, for example:

allow="accelerometer; autoplay; encrypted-media; gyroscope;
picture-in-picture"

The final code is:

<iframe src="https://www.youtube.com/embed/[VIDEO-CODE]?autoplay=1" 
frameborder="0" style="width: 100%; height: 100%;"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"></iframe>
一个人的旅程 2024-12-09 18:20:46

如果有人正在寻找,这是一个完美的解决方案,自动播放*是这里的关键,这在任何地方都没有提到。

  <iframe allow="autoplay *; fullscreen *" allowfullscreen="true" 
      src="https://example.com">
   </iframe>

&如果你想完全延迟加载 YouTube 视频,请使用此-

  <iframe
        srcdoc="<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img,span{position:absolute;width:100%;top:0;bottom:0;margin:auto}span{height:1.5em;text-align:center;font:48px/1.5 sans-serif;color:white;text-shadow:0 0 0.5em black}</style><a href=https://www.youtube.com/embed/unICbsPGFIA?autoplay=1><img src=https://img.youtube.com/vi/zEkgWzi5T-Y/hqdefault.jpg><span>▶</span></a>"
        src="https://www.youtube.com/embed/unICbsPGFIA?autoplay=1&loop=1&playlist=zEkgWzi5T-Y"
        frameborder="0"
        allow="accelerometer; autoplay *; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
        allowfullscreen
      ></iframe>

This is the perfect solution if someone is looking for, autoplay* is the key here, which is not mentioned anywhere.

  <iframe allow="autoplay *; fullscreen *" allowfullscreen="true" 
      src="https://example.com">
   </iframe>

& if you want to lazy load the youtube video completely use this-

  <iframe
        srcdoc="<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img,span{position:absolute;width:100%;top:0;bottom:0;margin:auto}span{height:1.5em;text-align:center;font:48px/1.5 sans-serif;color:white;text-shadow:0 0 0.5em black}</style><a href=https://www.youtube.com/embed/unICbsPGFIA?autoplay=1><img src=https://img.youtube.com/vi/zEkgWzi5T-Y/hqdefault.jpg><span>▶</span></a>"
        src="https://www.youtube.com/embed/unICbsPGFIA?autoplay=1&loop=1&playlist=zEkgWzi5T-Y"
        frameborder="0"
        allow="accelerometer; autoplay *; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
        allowfullscreen
      ></iframe>
不醒的梦 2024-12-09 18:20:46

1 - 将 &enablejsapi=1 添加到 IFRAME SRC

2 - jQuery 函数:

  $('iframe#your_video')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');

工作正常

1 - add &enablejsapi=1 to IFRAME SRC

2 - jQuery func:

  $('iframe#your_video')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');

Works fine

哥,最终变帅啦 2024-12-09 18:20:46

要使用 javascript api,

<script type="text/javascript" src="swfobject.js"></script>
  <div id="ytapiplayer">
    You need Flash player 8+ and JavaScript enabled to view this video.
  </div>

  <script type="text/javascript">

    var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/OyHoZhLdgYw?enablejsapi=1&playerapiid=ytplayer&version=3",
                       "ytapiplayer", "425", "356", "8", null, null, params, atts);

  </script>

要使用 id: 播放 youtube:

swfobject.embedSWF

参考:https://developers.google.com/ youtube/js_api_reference杂志

To use javascript api,

<script type="text/javascript" src="swfobject.js"></script>
  <div id="ytapiplayer">
    You need Flash player 8+ and JavaScript enabled to view this video.
  </div>

  <script type="text/javascript">

    var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/OyHoZhLdgYw?enablejsapi=1&playerapiid=ytplayer&version=3",
                       "ytapiplayer", "425", "356", "8", null, null, params, atts);

  </script>

To play the youtube with the id:

swfobject.embedSWF

reference: https://developers.google.com/youtube/js_api_referencemagazine

Hello爱情风 2024-12-09 18:20:46
<iframe width="560" height="315" 
        src="https://www.youtube.com/embed/9IILMHo4RCQ?rel=0&controls=0&showinfo=0&autoplay=1" 
        frameborder="0" allowfullscreen></iframe>
<iframe width="560" height="315" 
        src="https://www.youtube.com/embed/9IILMHo4RCQ?rel=0&controls=0&showinfo=0&autoplay=1" 
        frameborder="0" allowfullscreen></iframe>
无可置疑 2024-12-09 18:20:46

2018 年 12 月,

寻找一个用于 React 的 AUTOPLAY、LOOP、MUTE youtube 视频。

其他答案没有用。

我找到了一个带有库的解决方案: react-youtube

class Video extends Component {

    _onReady(event) {
        // add mute
        event.target.mute();
        // add autoplay
        event.target.playVideo();
    }

    render() {
        const opts = {
            width: '100%',
            height: '700px',
            playerVars: {
                // remove video controls 
                controls: 0,
                // remove related video
                rel: 0
            }
        };

        return (
            <YouTube
                videoId="oHg5SJYRHA0"
                opts={opts}
                // add autoplay
                onReady={this._onReady}
                // add loop
                onEnd={this._onReady}
            />
        )
    }

}

December 2018,

Looking for an AUTOPLAY, LOOP, MUTE youtube video for react.

Other answers didn't worked.

I found a solution with a library: react-youtube

class Video extends Component {

    _onReady(event) {
        // add mute
        event.target.mute();
        // add autoplay
        event.target.playVideo();
    }

    render() {
        const opts = {
            width: '100%',
            height: '700px',
            playerVars: {
                // remove video controls 
                controls: 0,
                // remove related video
                rel: 0
            }
        };

        return (
            <YouTube
                videoId="oHg5SJYRHA0"
                opts={opts}
                // add autoplay
                onReady={this._onReady}
                // add loop
                onEnd={this._onReady}
            />
        )
    }

}
万劫不复 2024-12-09 18:20:46

是的,您可以按照 Google 自动播放的规定,嵌入带有 Iframe 标记的自动播放 YouTube 视频Iframe 政策

尝试这种方式:

<iframe src="https://www.youtube.com/embed/video-id" frameborder="0" allow="autoplay; fullscreen"></iframe>

虽然此过程一次仅适用于一个视频,但要使用 Iframe 代码嵌入一组 YouTube 视频,您需要使用第三方工具(例如 Taggbox) Widget,与 Google 的 API 集成,允许用户使用频道和视频嵌入 YouTube 视频、短片。 YouTube 小部件形式的播放列表网址。

此外,您可以使用生成的 Iframe 代码轻松地将响应式 YouTube 小部件嵌入到您的网站上。

<iframe src="https://widget.taggbox.com/unique-id" style="width:100%;height:600px;border:none;"></iframe>

Yes, you can embed an auto-playing YouTube video with an Iframe tag as per Google's autoplay Iframe policy

Try this way:

<iframe src="https://www.youtube.com/embed/video-id" frameborder="0" allow="autoplay; fullscreen"></iframe>

While this process is only applicable for one video at a time, to embed a collection of YouTube videos using an Iframe code, you need to use a third-party tool like Taggbox Widget, which is integrated with Google's API that allows users to embed YouTube videos, shorts using channel & playlist URLs in the form of a YouTube widget.

Furthermore, you can easily embed that responsive YouTube widget on your website with the generated Iframe code.

<iframe src="https://widget.taggbox.com/unique-id" style="width:100%;height:600px;border:none;"></iframe>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文