YouTube API - 播放/暂停切换按钮

时间:2016-08-07 16:46:20

标签: jquery api youtube

我有一个嵌入式YouTube视频,前面有一个透明的PNG“框架”,所以我需要在PNG前面有一个看不见的播放/暂停按钮。一切正常,视频播放点击,但我不能暂停播放视频。我已经尝试了下面“第4节”的几种变体,似乎没有任何效果。有人可以告诉我我错过了什么吗?

    var video_id = $('#video-player').attr('data-id');
    // 1. 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);

    // 2. This function creates an <iframe> (and YouTube player) after the API code downloads.
    var player;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('video', {
            width: '470',
            height: '263',
            videoId: 'ubvR6_pwpIk',
            playerVars: {
                modestbranding: 1,
                controls: 0,
                showinfo: 0,
                wmode: 'opaque',
                branding: 0,
                autohide: 0,
                rel: 0
            },
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    // 3. The API calls this function when the video player is ready.
    function onPlayerReady(event) {
        $('#video-button').click(function(event){
            player.playVideo();
        });
    }

    // 4. The API calls this function when the player's state changes.
    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING) {
            $('#video-button').click(function(event){
                player.pauseVideo();
            });
        }
        else {
            $('#video-button').click(function(event){
                player.playVideo();
            });
        } 
    }

1 个答案:

答案 0 :(得分:2)

我不确定你的病情:

if (event.data == YT.PlayerState.PLAYING) {

请改为尝试:

var state = player.getPlayerState();
if(state==1){

这是州名单:

  • -1:unstarted
  • 0:结束
  • 1:正在播放
  • 2:暂停
  • 3:缓冲
  • 5:视频提示

Reference

修改
由于结果相同......

尝试在onPlayerStateChange ...中使用console.log 只是为了看它是否真的开火了 我建议你console.log我上面建议的state变量。
同时尝试console.log event以确认它在那里。

如果这些调试测试没有显示任何内容,我会感到惊讶......

---
我刚刚在文档中找到了这个:

function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("myytplayer");
  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
  alert("Player's new state: " + newState);
}