在youtube api中检测播放事件 [英] Detecting a play event in youtube api

查看:94
本文介绍了在youtube api中检测播放事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种通过Javascript检测嵌入式Youtube视频中的播放事件的方法。现在我能够检测到状态变化,但我无法弄清楚如何取消绑定事件并触发另一个事件,说它已完成。我也不想使用add / removeEventListener,因为我猜IE8及以下版本没有这个功能。

I'm looking for a way to detect a play event in an embedded Youtube video via Javascript. Right now I'm able to detect state change, but I can't figure out how to unbind the event after and fire another event saying that it's complete. I'd also prefer not to use add/removeEventListener because I guess IE8 and below don't have this function.

我的代码到目前为止,

    function onYouTubePlayerReady(playerId) {
    console.log('loaded');
    var ytPlayer = document.getElementById(playerId);
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
    console.log("Player's new state: " + newState);
    if(newState === 1) {
        sendYtUrl();
     }
}

function sendYtUrl() {
    console.log('play detected');
    ytplayer.removeEventListener("onStateChange");
} 

我希望弹出sendYtUrl,删除监听器,然后做任何我做的事情我需要做,甚至更好,保持清洁,并保持相同的功能。

I'm hoping to pop into sendYtUrl, remove listener, then do whatever I need to do, or even better, keep it cleaner and leave it in the same function.

提前致谢!

推荐答案

您无需取消绑定 onStateChange 事件,以了解视频何时结束或完成。 onStateChange 只需要有一个事件监听器。每次出现以下任何情况时,它都会被触发并返回以下状态:

You don't have to unbind the onStateChange event to know when the video ends or is completed. The onStateChange only needs to have one event listener. It will be fired and return the following states every time any of these situations occur:

-1 (unstarted)
0 (ended)
1 (playing)
2 (paused)
3 (buffering)
5 (video cued)

在您的函数 onytplayerStateChange 中,添加另一个 if 视频完成时要捕获的语句:

In your function onytplayerStateChange, add another if statement to catch when the video is complete:

function onytplayerStateChange(newState) {
    console.log("Player's new state: " + newState);
    if(newState === 1) {
        sendYtUrl();
    } else if(newState === 0) {
        console.log("Video has ended!");
    }
}

这篇关于在youtube api中检测播放事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆