YouTube IFrame API,加载PHP数据和添加播放器控件功能

时间:2017-02-22 14:56:40

标签: javascript php youtube youtube-api media

我有一个数据库驱动的YouTube视频播放器,视频代码从表中加载并在<div>中播放。但我有两个问题:

1)如何将我的php代码中的视频代码加载到Javascript中?

这是我的PHP代码:

<?php
$code_sql = "SELECT * FROM music_codes WHERE id = '$url_id'";
$code_res = mysqli_query($con, $code_sql);
while($code = mysqli_fetch_assoc($code_res)){

    $code_1 = $code["one"];
    $code_2 = $code["two"];
    $code_3 = $code["three"];
    $code_4 = $code["four"];
    $code_5 = $code["five"];
    $code_6 = $code["six"];
    $code_7 = $code["seven"];
    $code_8 = $code["eight"];

};
?>

Javascript我需要显示php:

<div id="player"></div>
<script src="//www.youtube.com/iframe_api"></script>
<script>
    /**
     * Put your video IDs in this array
     */
    var videoIDs = [
        ' ** $code_1 ** ', // PHP Code Display
        ' ** $code_2 ** ', // PHP Code Display
        etc,
        etc
    ];

    var player, currentVideoId = 0;

    function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
            height: '350',
            width: '425',
            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]);
            }
        }
    }
</script>

2)如何为用户添加更好的控件以跳过视频?目前它一个接一个地播放每个视频,但没有办法让他们点击下一个或上一个。我非常需要这样做。

1 个答案:

答案 0 :(得分:0)

您需要创建一个更改currentVideoId的函数:

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

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

HTML:

<input type="button" value=""Next" onclick="next()" />
<input type="button" value=""Previous" onclick="prev()" />

以前也一样。