在youtube javascript api中禁用自动播放

时间:2013-11-18 18:20:14

标签: javascript jquery youtube-api youtube-javascript-api youtube-data-api

我知道在params和url中使用自动播放:0。问题是当我使用loadVideoByID()函数时。最初的视频似乎总是不会自动启动。但是当我在新视频中加载新的自动启动时。我不希望那个新的自动启动

$(document).ready(function() {
var player;
window.onYouTubePlayerAPIReady = function() {
    player = new YT.Player('player', {
        height : '390',
        width : '640',
        videoId : 'JW5meKfy3fY',
        playerVars : {
            'autoplay' : 0,
            'rel' : 0,
            'showinfo' : 0,
            'egm' : 0,
            'showsearch' : 0,
            'controls' : 0,
            'modestbranding' : 1,
        },
        events : {
            'onReady' : onPlayerReady,
            'onStateChange' : onPlayerStateChange
        }
    });

};

window.onPlayerReady = function(event) {
    //event.target.playVideo();
    loadNewVid("bHQqvYy5KYo");
};

window.onPlayerStateChange = function(event, element) {
    //When the video has ended
    if (event.data == YT.PlayerState.ENDED) {
        //Get rid of the player
        element.style.display = "none";
    }
};

function loadNewVid(vidID){
    player.loadVideoById(vidID, "large");

}

});

2 个答案:

答案 0 :(得分:31)

根据定义,loadVideoById()加载并播放视频。您想要使用的是cueVideoById(),它将为此做好准备,但等待命令实际播放。

https://developers.google.com/youtube/js_api_reference#cueVideoById

答案 1 :(得分:0)

我认为这篇文章已经很老了,但无论如何我都会分享我的方法,万一有人偶然发现它,就像我刚才那样:

由于无法调用loadVideoById并阻止自动播放,我建议在播放器上调用destroy()方法并使用新ID重新安装它。

让我们说:

$(document).ready(function() {
var player;
var playerParams = {
    height : '390',
    width : '640',
    videoId : 'JW5meKfy3fY',
    playerVars : {
        'autoplay' : 0,
        'rel' : 0,
        'showinfo' : 0,
        'egm' : 0,
        'showsearch' : 0,
        'controls' : 0,
        'modestbranding' : 1,
    },
    events : {
        'onReady' : onPlayerReady,
        'onStateChange' : onPlayerStateChange
    }
}

window.onYouTubePlayerAPIReady = function() {
    player = new YT.Player('player', playerParams);

};

window.onPlayerReady = function(event) {
    //event.target.playVideo();
    loadNewVid("bHQqvYy5KYo");
};

window.onPlayerStateChange = function(event, element) {
    //When the video has ended
    if (event.data == YT.PlayerState.ENDED) {
        //Get rid of the player
        element.style.display = "none";
    }
};

function loadNewVid(vidID){
    player.destroy();
    playerParams.videoId = vidID;
    player = new YT.Player('player', playerParams);

}
});

我希望这可能有所帮助