我有一个包含一些YouTube视频嵌入代码的页面。当用户在一个视频上点击“>播放”时,页面上的每个其他视频都需要暂停,否则他们的音频会与刚刚播放的新视频重叠。
实现这一目标的最有效方法是什么?
答案 0 :(得分:1)
好的,这是一个解决方案,我想出了一些来自其他几个代码的解决方案。
在.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。确保您的enablejsapi = 1位于YouTube文件的网址末尾:
<object width="500" height="400">
<param name="movie" value="http://www.youtube.com/v/ms6GAdy6dag?version=3&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&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&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&enablejsapi=1" type="application/x-shockwave-flash" width="500" height="400" wmode="transparent" allowscriptaccess="always" allowfullscreen="true">
</object>