如何显示多个YouTube视频没有重叠的音频



我有一个页面与几个YouTube视频嵌入代码。当用户在一个视频上点击">播放"时,页面上的其他视频都需要暂停,否则它们的音频会与刚刚播放的新视频重叠。

实现这一点最有效的方法是什么?

好了,下面是我从其他人那里得到的一些代码的解决方案。

在.js文件中添加以下内容:

var videos = {};
$(document).ready(function(){
  // assigns ids to all the embed tags
  var i = 0;
  $('embed').each(function() {
    $(this).attr('id', "embed"+i);
    i++
  });
});
function onYouTubePlayerReady(playerId) {
  // loop through all embed tags assign a listener object only if not already assigned
  $('embed').each(function() {
    var embedid = $(this).attr('id');
    var ytplayer = document.getElementById(embedid);
    if (videos[embedid] == undefined) {
        window["dynamicYouTubeEventHandler" + embedid] = function(state) { onytplayerStateChange(state, embedid); }
        ytplayer.addEventListener("onStateChange", "dynamicYouTubeEventHandler"+embedid);
    }
    videos[embedid] = true;
  });
}
function onytplayerStateChange(newState, playerId) {
    // If one of the videos was played
    if (newState == 1) {
        // loop through each of the embed tags
        $('embed').each(function() {
            var embedid = $(this).attr('id');
            var ytplayer = document.getElementById(embedid);
            // Only pause video if not the current player
            if(embedid != playerId) {
                var current_state = ytplayer.getPlayerState();
                // Only pause if not already started
                if (current_state != '-1') {    ytplayer.pauseVideo();  }
            }
        });
    }
}

然后在你的html文件中,像这样嵌入你的youtube。确保在YouTube文件的url末尾设置enablejsapi=1:

<object width="500" height="400">
    <param name="movie" value="http://www.youtube.com/v/ms6GAdy6dag?version=3&amp;enablejsapi=1">
    <param name="allowFullScreen" value="true">
    <param name="allowscriptaccess" value="always">
    <param name="wmode" value="transparent">
    <embed src="http://www.youtube.com/v/ms6GAdy6dag?version=3&amp;enablejsapi=1" type="application/x-shockwave-flash" width="500" height="400" wmode="transparent" allowscriptaccess="always" allowfullscreen="true">
</object>

<object width="500" height="400"><param name="movie" value="http://www.youtube.com/v/PegET_3FFAs?version=3&amp;enablejsapi=1">
    <param name="allowFullScreen" value="true">
    <param name="allowscriptaccess" value="always">
    <param name="wmode" value="transparent">
    <embed src="http://www.youtube.com/v/PegET_3FFAs?version=3&amp;enablejsapi=1" type="application/x-shockwave-flash" width="500" height="400" wmode="transparent" allowscriptaccess="always" allowfullscreen="true">
</object>

相关内容

  • 没有找到相关文章

最新更新