停止YouTube API自动播放

时间:2017-02-23 11:55:50

标签: javascript video youtube autoplay

我的网站上有一个由数据库中的代码组成的视频播放器,我希望它能停止在自动播放中播放第一个视频。需要什么代码以及它在哪里?

我目前使用的代码是:

var $vid1 = <?php echo json_encode($code_1); ?>;
var $vid2 = <?php echo json_encode($code_2); ?>;
var $vid3 = <?php echo json_encode($code_3); ?>;
var $vid4 = <?php echo json_encode($code_4); ?>;
var $vid5 = <?php echo json_encode($code_5); ?>;
var $vid6 = <?php echo json_encode($code_6); ?>;
var $vid7 = <?php echo json_encode($code_7); ?>;
var $vid8 = <?php echo json_encode($code_8); ?>;
var videoIDs = [
    $vid1,
    $vid2,
    $vid3,
    $vid4,
    $vid5,
    $vid6,
    $vid7,
    $vid8
];

var player, currentVideoId = 0;

function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '248',
        width: '440',
        playerVars: {
            autoplay: 0
        },
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
}

function onPlayerReady(event) {
    event.target.loadVideoById(videoIDs[currentVideoId]);
}

function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.ENDED) {
        currentVideoId++;
        if (currentVideoId < videoIDs.length) {
            player.loadVideoById(videoIDs[currentVideoId]);
        }
    }
}

function next(){
    currentVideoId++;
    if (currentVideoId < videoIDs.length) {
            player.loadVideoById(videoIDs[currentVideoId]);
    }
}

function previous(){
    currentVideoId--;
    if (currentVideoId >= 0) {
            player.loadVideoById(videoIDs[currentVideoId]);
    }
    else currentVideoId = 0;
}

2 个答案:

答案 0 :(得分:0)

应该有一个参数 autoplay:0 来添加新的YT.player()参数。

此处有更多详情: https://developers.google.com/youtube/player_parameters#autoplay

答案 1 :(得分:0)

您可以提供一个参数来停止自动播放的视频。您只需将其添加到现有代码中......

function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '248',
        width: '440',
        playerVars: {
            autoplay: 0
        },
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
}

您可以在此处找到有关playerVars选项的更多信息...

https://developers.google.com/youtube/player_parameters?playerVersion=HTML5