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

查看:28
本文介绍了在 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天全站免登陆