YouTube iframe API会两次触发所有事件

时间:2012-10-20 13:43:41

标签: php javascript iframe youtube youtube-api

虽然YouTube API使用embedswf工作正常,但在使用iframes嵌入播放器时,我的脚本无法正常工作。更具体地说,API的iframe版本似乎两次触发所有事件,导致各种问题,例如本例中的问题(hosted):

<html>

<head>
    <script type="text/javascript" src="http://www.youtube.com/iframe_api"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
</head>

<body>

This script initializes a YouTube API player in an iframe which cycles through the array an video IDs. Every time a video ends, the next video ID in the array is retrieved and its video is played. <b>Unfortunately, the player reports the ending of a video twice, which results in every other video being skipped</b>.

<pre>

<?php
$videos = array("TLU2DZqhsSs","8CJn4T5ulL8","gdzf5oQJWxo","VTxKMiPXOGU","BeuwxSHHFh8");
print_r($videos);
?>

</pre>

<div id="ytapiplayer">This text will be replaced by a player.</div>

<script type="text/javascript">
playlistids = <?php echo json_encode($videos); ?>;

var playing = playlistids[0];

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

var ytplayer;

function onYouTubeIframeAPIReady() {
    ytplayer = new YT.Player('ytapiplayer', {
        width: '922',
        height: '522',
        videoId: playing,
        events: {
            'onStateChange': onytplayerStateChange,
            'onReady': onPlayerReady
        }
    });
}

function onPlayerReady(event) {
    event.target.setPlaybackQuality('hd720')
    event.target.setVolume(100)
    alert('Start playing entry #0 (preloaded).')
    event.target.playVideo()
}

function play(ytid) {
    if (ytplayer) {
        playing = ytid
        alert('On to entry #'+ nextentrykey +', playing set to: ' + playing)
        ytplayer.loadVideoById(ytid, 0, "hd720");
    }
}

function onytplayerStateChange(event) {
    //alert('NEW STATE: ' + event.data)
    if ( event.data == 0 ) {
        alert('Since the new player state is '+ event.data +', the video has ended. Getting next key after playing ' + playing + '.');
        nextentrykey = parseInt(playlistids.getKey(playing))+1
        if (nextentrykey >= playlistids.length) {
                nextentrykey = 0
        }
        play(playlistids[nextentrykey]);
    }
}

Object.prototype.getKey = function(value){
  for(var key in this){
    if(this[key] == value){
      return key;
    }
  }
  return -1;
};
</script>

</body>

</html>

我是否应该忽略从API获得的所有其他调用并实施解决方法?或者可以用更明智的方式解决这个问题吗?

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:4)

我认为问题是你加载iframe_api库两次

并在YouTubeIframeAPIReady

上运行两次

尝试删除这些行:

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