如何停止嵌入的Youtube视频同时播放 [英] How to stop embedded Youtube videos from playing simultaneously
问题描述
SoundCloud播放器具有默认功能,当用户启动播放器时,它会自动暂停当前正在播放的所有其他播放器. (例如: http://jsfiddle.net/Vx6hM/).
SoundCloud players have a default functionality where when a user starts a player, it automatically pauses all others that are currently playing. (example: http://jsfiddle.net/Vx6hM/).
我正在尝试使用通过常规嵌入代码动态添加的嵌入式youtube视频来重新创建该视频.
I'm trying to recreate this with embedded youtube videos that are added dynamically via the normal embed code.
使用它: https://stackoverflow.com/a/7513356/938089 这是 https://stackoverflow.com/a/7988536/1470827
我能够做到这一点:
function chain(){
$('.post').each(function(){
var player_id = $(this).children('iframe').attr("id");
var other_player_id = $(this).siblings().children('iframe').attr("id");
player = new YT.Player( player_id, {
events:
{
'onStateChange': function (event)
{
if (event.data == YT.PlayerState.PLAYING)
{ callPlayer( other_player_id , 'pauseVideo' );
alert('Trying to pause: ' + other_player_id);
}
}
}
});
});
}
这是一个可以正常工作的JS Bin: http://jsbin.com/oxoyes/2/编辑
Here's a JS Bin with it half working: http://jsbin.com/oxoyes/2/edit
当前,它是唯一的一位玩家.我需要它来暂停除正在玩游戏的玩家以外的所有其他玩家.
Currently, its only calling one of the players. I need it to pause ALL of the other players except the playing one.
此外,欢迎提供任何有关如何清理和/或以其他方式/更好地进行清洁的提示.我对javascript还是很陌生,所以我什至不确定我是否会以正确的方式进行操作.
Also, any tips on how to clean this up and/or do it differently/better are welcome. I'm still very new to javascript so I'm not even sure I'm going about it the right way.
谢谢!
推荐答案
在给定的时间最多只能有一个玩家在玩.与其尝试暂停所有正在播放的游戏,不如将其视为尝试暂停一个正在播放的游戏.当然,没有人可以玩.鉴于此,请看下面的代码.您可以维护一个外部作用域变量,并在必要时暂停该变量,同时将其设置为之后才开始播放的播放器.
You'll only have at most one player playing at a given time. Instead of trying to pause all that are playing, think of it as trying to pause the one playing. Of course, none could be playing. Given this, take a look at the following code. You maintain a single outer scope variable and pause that when necessary, while setting it to the player you just started playing thereafter.
var playerCurrentlyPlaying = null;
function chain(){
$('.post').each(function(){
var player_id = $(this).children('iframe').attr("id");
player = new YT.Player( player_id, {
events:
{
'onStateChange': function (event)
{
if (event.data == YT.PlayerState.PLAYING)
{
if(playerCurrentlyPlaying != null &&
playerCurrentlyPlaying != player_id)
callPlayer( playerCurrentlyPlaying , 'pauseVideo' );
playerCurrentlyPlaying = player_id;
}
}
}
});
});
}
这篇关于如何停止嵌入的Youtube视频同时播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!