如何让嵌入式 iframe 中的多个 YouTube 视频一键播放?

2023-11-30

我在几个 iframe 中嵌入了一些 YouTube 视频,并且希望仅使用一个按钮即可立即停止所有视频。我尝试了几种不同的方法,但就是无法得到正确的结果。

这是我得到的。

main.html:

<!DOCTYPE html>
<html>
<head>
    <title>YT Mosaic</title>
    <link href="main.css" rel="stylesheet">
</head>

<body>

<!-- begin snippet: js hide: false console: true babel: false -->

<div class="container">
    <div class="mosaic">
        <iframe id="if1" src="https://www.youtube.com/embed/5mL-OkdM7Tc?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- TRT -->
        <iframe id="if2" src="https://www.youtube.com/embed/9Auq9mYxFEE?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- SKY -->
        <iframe id="if3" src="https://www.youtube.com/embed/VBTdNwm5CDY?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- Global News -->
        <iframe id="if4" src="https://www.youtube.com/embed/ntmPIzlkcJk?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- Euronews -->
        <iframe id="if5" src="https://www.youtube.com/embed/GE_SfNVNyqk?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- DW -->
        <iframe id="if6" src="https://www.youtube.com/embed/h3MuIUNCCzI?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- F24 -->        
    </div>

    <button onclick="iframe1play(); return false;">⏯️</button>
    <button onclick="stop();">⏹</button>
    <button onclick="playAll();">▶▶ Play All</button>
</div>

<script>

    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var ifa  = [];       // array of iframe id's
    var ifos = [];       // array of iframe YT objects for use elsewhere

    // For each iframe you find, add its ID to the ifa array
    var iframes = document.querySelectorAll("div.mosaic iframe");
    iframes.forEach(function(iframe) {
        ifa.push(iframe.id);
    });
    console.log('[LOG] iframe array:', ifa)
    // Array(6) [ "if1", "if2", "if3", "if4", "if5", "if6" ]

    // Once the YouTube API is ready, for each iframeId in your array, 
    // create a new YT player and give it the onReady event.
    function onYouTubeIframeAPIReady() {
        ifa.forEach(function(iframeId) {
            var player = new YT.Player(iframeId, {
                events: {
                    'onReady': onPlayerReady,
                }
            });
        });
    }

    function onPlayerReady(event) {
        var ifo = event.target;

        ifos.push(ifo);                 // Push current iframe object to ifo array
        ifos.forEach(function(j) {
            j.setVolume(30);
            j.playVideo();
            j.unMute();
        });
    }
    
    var player;
    // WARNING this need to be commented out as it interferes with the other version.
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('if1', {
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange,
                'onError': catchError
            }
        });
    }

    var done = false;
    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
            setTimeout(stopVideo, 6000);    // wait 6 s. before stopping player
            done = true;
        }
    }
    
    function catchError(event) {
        if (event.data == 2)   console.log("[LOG] Error: The request contains an invalid parameter value.");
        if (event.data == 5)   console.log("[LOG] Error: content cannot be played in an HTML5 player.");
        if (event.data == 100) console.log("[LOG] Error: Video doesn't exists (or has been removed)!");
        if (event.data == 101) console.log("[LOG] Error: Not allowed to be played in an embedded player.");
        if (event.data == 150) console.log("[LOG] Error: Not allowed to be played in an embedded player.");
        // This should never happen!
        console.log("Error:\n", event);
    }

    // This was a test, not working, trying to use:
    // onload="p1=new YT.Player(this);">
    function playAll() {
        var ifs = [p1,p2,p3,p4,p5,p6];
        for(var i=0; i<ifs.length; i++) {
            console.log("Try to Play: ", toString(ifs[i]));
            ifs[i].playVideo();
        }
    }

    function play() {
        //player.unMute();
        player.playVideo();
        //show_video_url();
    }
    function pause() {       player.pauseVideo();   }
    function stop() {        player.stopVideo();    }
    function stopVideo() {   player.stopVideo();    }
    function mute() {        player.unMute();       }

    function iframe1play() {
        if (player.getPlayerState() == YT.PlayerState.PLAYING) {
            player.pauseVideo();
            document.getElementById("if1").style.opacity = "0.7";
        } else {
            player.playVideo();
            document.getElementById("if1").style.opacity = "1";
        }
    }

</script>

</body>
<footer>FTSE</footer>

</html>

这是 CSS 文件main.css:

body {
    background-color: #404040;
    color: lightgrey;
    margin: 0;
    padding: 1em;
    /*height: 100vh;*/
    box-sizing: border-box;
}

.container {
    max-width: 1100px;  
    /*  width: 100%;*/
    border: 1px solid black;
    padding: 10px;
}

.mosaic {
    display: grid;
    /* Setup a 2x3 frame: */
    /* fr is a fractional unit and 1fr is for 1 part of the available space */
    grid-template-columns: 1fr 1fr;
    grid-template-rows:    50% 50% 50%;
    /*grid-template-rows:  1fr 1fr 1fr;*/
    max-width: 1100px;              /* 100% */
    max-height: 100%;               /* 100% */
    /*aspect-ratio: 16/9;*/         /* 16/9 */ 
    /* margin: auto; */             /* auto */
    margin-bottom: 1em;             /* 1em */
    /*padding: 2em; */
    gap: 5px;                       /* 1em */
}

iframe {
    /* iframe width="560" height="315" */
    display: block;
    width:  100%;
    height: 100%;
    aspect-ratio: 16/9;             /*  */ 
    /*min-width: 350px;*/           /* 350px */
    /*min-height: 200px;*/          /* 200px */
    background: gray;             /* yellow */ 
    border: 1px solid black;      /* border: solid red */
    margin: 0px;                    /*  */
}

我如何使用 iframeid=标签使用一键启动所有 iframe 视频?

  • 最好使用JSwithout其他库,例如jQuery.

  • JSfiddle代码


您可以使用 Youtube 的 IFrame Player API。他们这里有很棒的文档https://developers.google.com/youtube/iframe_api_reference

您基本上可以通过 API 生成视频来控制所有 YouTube 嵌入视频。

一个工作示例如下:

<body>
       <div id="container">
        <div id="player-5mL-OkdM7Tc"></div> <!-- TRT -->
        <div id="player-9Auq9mYxFEE"></div> <!-- SKY -->
        <div id="player-VBTdNwm5CDY"></div> <!-- Global News -->
        <div id="player-ntmPIzlkcJk"></div> <!-- Euronews -->
        <div id="player-GE_SfNVNyqk"></div> <!-- DW -->
        <div id="player-h3MuIUNCCzI"></div> <!-- F24 --> 
       </div>

       <button onclick="play()">
         Play All
       </button>
        <script src="https://www.youtube.com/iframe_api"></script>
        <script src="main.js" async defer></script>
</body>
let playersObjs = [];

window.onYouTubeIframeAPIReady = () => {
    const playerContainers = document.querySelectorAll('div[id^="player"]');


    playerContainers.forEach((container) => {
        const videoId = container.id.slice(7);

        playersObjs.push(new YT.Player(container.id, {
            height: '200',
            width: '100',
            videoId,
            playerVars: {
                'playsinline': 1
            }
        }))
    })
}

const play = () => {
    playersObjs.forEach((player) => {
        player.playVideo();
    })
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何让嵌入式 iframe 中的多个 YouTube 视频一键播放? 的相关文章

随机推荐

  • IPv6 组播示例

    我搜索了如何实现简单 ipv6 多播示例的示例 但是我只找到了使用 ipv4 的示例 谁能提供一个简单的 ipv6 多播 helloworld 示例 这是一个简单的客户端服务器示例 顺便说一句 在网络上的多台计算机上运行它将使所有计算机相互
  • Verilog 位更改位置

    假设我有一个寄存器reg 15 0 my reg 其中包含一个16位signed sample 如何找到第一位变化的位置 意思是 如果假设my reg 16 b0001011011010111 我怎么知道第一个变化是0 to 1 is at
  • 如何使用 openpyxl 设置图表绘图区域的背景颜色

    我想更改图表的背景颜色 如本例所示 使用 openpyxl 在谷歌小组讨论中我发现了以下代码片段 from openpyxl chart shapes import GraphicalProperties props GraphicalPr
  • eclipse 插件 - 将非 java 扩展文件视为 java 文件

    我们正在开发一个 Eclipse 插件 我们有一个扩展名 比如 xyz 但它实际上 包含java代码 JavaCore createCompilationUnitFrom 仅接受扩展名为 java 的文件 JavaCore 有 JAVA S
  • 如何从命令行打开 Microsoft Edge 中的 URL?

    我需要在 Microsoft Edge 在 Windows 10 上 中打开 URL 当我调用 start shell AppsFolder Microsoft MicrosoftEdge 8wekyb3d8bbwe MicrosoftEd
  • 使用 VLookup 时更改工作表会导致问题

    我想从两个不同的工作表中总共导入两个值 我有工作表Site1 and Site2 我想从中导入与行相对应的值 Product1 Cost and Product2 Cost 分别 为此我尝试过 Set currentWb ActiveWor
  • 如何在jquery中获取新元素的第n个子元素

    我使用 jquery 创建了表行 var tableRow tr append td text one append td text two append td text three 现在我将其添加到文档中的表格中 table id app
  • 带条纹的柏树:元素高度未加载

    我已经使用 cypress 一周了 并且成功地与 stripe iframe 进行了集成 我使用了以下代码 in cypress support command js Cypress Commands add iframeLoaded pr
  • 未为 Solver 定义 VBA Sub

    每当我尝试使用以下代码行时 都会给我未定义的 Sub 或 Function 我尝试过仔细检查拼写 重命名它 在线查找其他问题 大多数其他错误是忘记在工作表或工作表后添加 s 但我不知道我的代码出了什么问题 我最初是从宏记录器中获得这段代码的
  • 如何避免分布式条件类型

    这些是我有的类型 type Action
  • Javascript AJAX 包含带有 eval 的文件

    假设我有 1 HTML 文档 2 该 HTML 文档加载 Javascript 文件 code js 如下所示
  • 从我的应用程序打开 iBooks

    我的应用程序中有一些 PDF 我想提供一个选项 可以在设备上可能安装的其他第三方电子阅读器应用程序 例如 Stanza 和 iBooks 中打开这些 PDF Dropbox 应用程序已成功实现此功能 但我找不到任何有关如何检测设备上可用的其
  • 在 JavaFX 中实现撤消/重做

    我正在尝试在 JavaFX 中实现撤消 重做 我使用以下命令绘制所有形状graphicsContext 我环顾四周 发现有一个save图形上下文上的方法 但它只保存属性 而不保存画布的实际形状 状态 解决这个问题的最佳方法是什么 这是我创建
  • C++ Excel 加载项加载错误:XLL 文件被 Excel 作为文本文件加载

    我正在使用 C 为 Excel 构建 XLL 加载项XLW库 它在我的电脑和许多其他电脑上运行良好 但在某些情况下 当我将 XLL 拖到新的 Excel 窗口中时 会出现以下错误 您尝试打开的文件 my addin xll 位于不同的路径中
  • 检测 Flutter 上的推送路由

    如何检查命名路由当前是否在堆栈中 我不想每次用户推送已存在的命名路由时都构建新路由 另外 有没有办法弹出命名路线 就像是Navigator of context popNamed routeToPop https docs flutter
  • azure应用程序服务中的Python ModuleNotFoundError包

    我在 Azure 中使用 Python3 7 Flask webapp 我还确认了 Web 应用程序 Stack 运行时也运行 Python3 7 该项目在 127 0 0 1 5000 localhost 中运行良好 当我尝试将脚本部署到
  • 如何获取从两个月前的第一天到昨天的日期表?

    我遇到一种情况 通常会通过创建一个供给表 例如 五年前到未来一百年之间的每个日期 进行查询来解决 但不幸的是 这个特定的作业不允许创建这样的表 所以我向 SO 社区开放 今天是 2010 年 1 月 29 日 我可以运行什么查询来提供一个包
  • C# 从反射类型实例化通用列表[重复]

    这个问题在这里已经有答案了 是否可以从 C Net 2 0 中的反射类型创建通用对象 void foobar Type t IList
  • 使用 Mustache 填充 html 标签参数

    我正在尝试使用 Mustache 将标识符 is 附加到下面的 href 模板 div a href product detail link a div var template tmpl html Data var model id 22
  • 如何让嵌入式 iframe 中的多个 YouTube 视频一键播放?

    我在几个 iframe 中嵌入了一些 YouTube 视频 并且希望仅使用一个按钮即可立即停止所有视频 我尝试了几种不同的方法 但就是无法得到正确的结果 这是我得到的 main html div class container div cl