【问题标题】:How to Dynamically change Youtube Player videoID如何动态更改 Youtube Player videoID
【发布时间】:2012-10-22 05:52:42
【问题描述】:

我想使用 YT.Player 代码来检测事件。我有一个带有 Youtube 视频 ID 的 CSV 文件和一个将 ID 放入数组中的函数,并且希望能够在用户单击图像时动态更改 ID。基本上是这样的:

html

<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

javascript

// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
// NOTE: videoId is taken out and instead is placed as the generated IFRAME src from the postSelection function

var player;
function onYouTubeIframeAPIReady() {
   player = new YT.Player('player', {
      height: '100%',
      width: '100%',
      videoId: '<<CALL TO FUNCTION OR VARIABLE HERE>>',
      events: {
         //'onReady': onPlayerReady,
         'onStateChange': onPlayerStateChange
      }
   });
}

如果您熟悉此代码,那么会发生#player DIV 被 IFRAME 替换。我可以用这个函数改变 IFRAME 源:

function postSelection() {
    $("#player").attr("src", _selected.attributes.url); //_selected.attributes.url comes from the CVS file
}

但这是非常错误的,而且对跨浏览器不友好。如果我使用标准 IFRAME 而不是 YT Player API,那么一切正常。但我想检测结束,暂停等等,所以我必须使用 API。我的猜测是,这是一个状态问题,并且在创建 IFRAME 的过程中丢失了持久性。

问候。

【问题讨论】:

标签: javascript jquery iframe youtube-api


【解决方案1】:

使用 js api 非常简单。当您想加载新视频时,只需致电player.loadVideoById(videoId); 详细信息https://developers.google.com/youtube/iframe_api_reference#loadVideoById

【讨论】:

  • 请注意,这是 iFrame API,因为“JavaScript API”现在已弃用。
  • @sheriffderek as 15/01/2019 我可以确认player.loadVideoById(videoId); 有效。
【解决方案2】:

如果这对像我一样挣扎的人有帮助...

这个player.loadVideoById(videoId) 仅在 videoId 被硬编码时为我工作,例如 player.loadVideoById('sdfexxdfse')

当我尝试将该值直接放入变量中或存储在数组中时,即使它包含相同的信息,它也不起作用。

视频每次都出现错误的参数。

以这种方式将其添加到变量中

var x = new String(variabledatahere)

完成了这项工作。

【讨论】:

  • 这难以置信。
猜你喜欢
  • 2020-08-01
  • 1970-01-01
  • 2020-12-08
  • 2016-04-14
  • 1970-01-01
  • 2018-12-10
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多