乐闻世界logo
搜索文章和话题

How to embed an autoplaying YouTube video in an iframe?

1个答案

1
  1. First, locate the video you want to embed. Then, click the "Share" button below the video on YouTube.
  2. In the "Share" options, select "Embed," and YouTube will provide an embed code (an HTML snippet).
  3. To enable autoplay, add the parameter autoplay=1 to the URL in the src attribute of the embed code. Since 2021, due to browser autoplay policies, you typically need to add mute=1 as well to ensure the video plays automatically in muted mode.
  4. Additionally, for safety, add the allow attribute to the iframe tag to permit autoplay.

A typical embed code example is as follows (note that these example codes may change with updates to the YouTube platform):

html
<iframe width="560" height="315" src="https://www.youtube.com/embed/VIDEO_ID?autoplay=1&mute=1" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Here, replace VIDEO_ID with the ID of the video you want to embed. For example, if the URL of the video you want to autoplay is https://www.youtube.com/watch?v=dQw4w9WgXcQ, you need to extract dQw4w9WgXcQ as the video ID.

The final embed code will look like this:

html
<iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1&mute=1" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Embed this code into your webpage, and the video will autoplay when the page loads. However, note that the video will start playing muted.

Example Illustration: Suppose I am creating a promotional website for a concert event. On the homepage, I want a background video to autoplay, showcasing highlights from last year's concert. I would locate the YouTube video of last year's concert, obtain the embed code, and modify it according to the steps above to enable autoplay and mute. Then, I would insert this code into my HTML page, ensuring the iframe's styling and positioning meet the design requirements. This way, visitors opening the webpage will immediately see and feel the concert atmosphere, even without sound, as the video visuals convey the event's energy.

2024年6月29日 12:07 回复

你的答案