在自动播放时如何静音多个YouTube视频?
我的代码:
<iframe id="ytplayer0" src="https://www.youtube.com/embed/ab0TSkLe-E0?controls=1&showinfo=0&rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<script>
// http://jsfiddle.net/BFDKS/966/
// http://stackoverflow.com/questions/24868226/how-do-you-mute-an-embedded-youtube-player
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer0', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady() {
player.playVideo();
// Mute!
player.mute();
}
</script>
<iframe id="ytplayer1" src="https://www.youtube.com/embed/QVGeilNsJFU?controls=1&showinfo=0&rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer1', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady() {
player.playVideo();
// Mute!
player.mute();
}
</script>
结果:
它仅静音,第二个...
有什么想法?
jsfiddle
您可能需要创建两个播放器,但onYouTubeIframeAPIReady
只会被调用一次。应用此方法,您可以这样做:
javaScript(在<head></head>
中):
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var players = new Array();
var players_attr = new Array();
players_attr["ytplayer0"] = {
events: {
'onReady': onPlayer1Ready
}
};
players_attr["ytplayer1"] = {
events: {
'onReady': onPlayer2Ready
}
};
function onYouTubeIframeAPIReady() {
for (key in players_attr) {
players[key] = new YT.Player(key, players_attr[key]);
}
}
function onPlayer1Ready() {
players["ytplayer0"].playVideo();
players["ytplayer0"].mute();
}
function onPlayer2Ready() {
players["ytplayer1"].playVideo();
players["ytplayer1"].mute();
}
html:
<iframe id="ytplayer0" src="https://www.youtube.com/embed/ab0TSkLe-E0?controls=1&showinfo=0&rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<iframe id="ytplayer1" src="https://www.youtube.com/embed/QVGeilNsJFU?controls=1&showinfo=0&rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
-
players
数组包含玩家对象 -
players_attr
数组包含玩家属性
两个数组的关键是播放器名称,例如 ytplayer0
&amp;ytplayer1
您可以在这里找到小提琴