JS API проигрывателя iframe Youtube с jQuery - объект проигрывателя не имеет метода getPlayerState

У меня есть следующий код, который должен приостанавливать автопрокрутку Slidedeck при каждом наведении курсора мыши. Для события mouseout автопрокрутка должна возобновить работу, если только видео Youtobe в Slidedeck в данный момент не воспроизводится или не буферизуется. У меня все работало нормально, если бы не было условия для видео на Youtube. Я считаю, что есть проблема с областью действия проигрывателя объектов, но не могу решить, как решить эту проблему.

Ошибка, которую я получаю в консоли при отключении мыши:

Uncaught TypeError: Object #‹T> не имеет метода getPlayerState.

Приветствуются любые советы.

Вот ссылка на справку по функциям JS API iframe проигрывателя YT: https://developers.google.com/youtube/iframe_api_reference#Functions

Вот мой код:

// remap jQuery to $
jQuery(function ($) {

/* trigger when page is ready */
$(document).ready(function (){

// Control for the video in Slidedeck
// Find slidedeck
$( "dl.slidedeck" )
    // On mouseenter stop the Slidedeck autoplay
    .mouseenter( function() {
        $( this ).slidedeck().pauseAutoPlay = true;
    })
    // On mouseleave start the Slidedeck autoplay again
    .mouseleave( function() {
        // But only if the YT player isn't actually playing or buffering
        if ( player && ( player.getPlayerState() == 1 || player.getPlayerState() == 3 )) {
            // If that's so, leave the function
            return;
        } else {
            // Turn on autoplay
            $( this ).slidedeck().pauseAutoPlay = false;
        }
    });


});
}); // end of remap for $ to jQuery


// Youtube player API
var player;
/*
 * The API will call this function when the page has finished downloading the JavaScript
 * for the player API, which enables you to then use the API on your page. Thus,
 * this function might create the player objects that you want to display when
 * the page loads.
 */
function onYouTubeIframeAPIReady() {
/*
 * Constructing a YT.Player object.
 * All methods and properties of the player will be found there later.
 */
player = new YT.Player( "myYTPlayer", {
    events: {
        /*
         * Here we attach callback for the onStateChange event.
         * That is called everytime a state of the player is changed.
         */
        "onStateChange": onPlayerStateChange
    }
});
return;
}

/*
 * Implementation of the onStateChange event.
 * Only parameter is an event object, its data property holds a value of a new player state.
 * Values: -1 (unstarted), 0 (ended), 1 (playing), 2 (paused), 3 (buffering), 5 (video cued)
 */
function onPlayerStateChange( event ) {
// integer indicating new state of the player
var newState = event.data,
    // store the slideck element for later calls, so we don't have to query the DOM again
    $slidedeck = jQuery( "dl.slidedeck" );

// Video loading or buffering?
if ( newState == 1 || newState == 3 ) {
    // Then pause the slidedeck autoplay.
    $slidedeck.slidedeck().pauseAutoPlay = true;
// Video has just ended?
} else if ( newState == 0 ) {
    // Then resume the Slidedeck autoplay.
    $slidedeck.slidedeck().pauseAutoPlay = false;
}
}

person crs1138    schedule 26.03.2013    source источник
comment
Возможно также прослушать событие onReady проигрывателя (developers.google.com/youtube/iframe_api_reference#Events) перед вызовом getPlayerState (может быть не готов, пока документ не будет загружен)   -  person Graham Robertson    schedule 26.03.2013


Ответы (1)


Хорошо, я решил это, стоило прочитать руководство Youtube. Проблема заключалась в определении идентификатора HTML для элемента iframe встроенного видео. При создании объекта проигрывателя есть первый параметр myYTPlayer — это должен быть идентификатор iframe.

<iframe id="myYTPlayer" width="729" height="410" src="http://www.youtube.com/embed/xxxxxxxxxxx?wmode=opaque&version=3&enablejsapi=1&origin=http://example.com" frameborder="0"></iframe>
person crs1138    schedule 26.03.2013