html5 视频结束后切换来源

Switching sources after html5 video has ended

我知道如果我只使用 onended 事件,这应该是直截了当的,就像这样:

  <video src="video.ogv" id="myVideo">
  </video>

<script type='text/javascript'>
    document.getElementById('myVideo').addEventListener('ended',myHandler,false);
    function myHandler(e) {
        // What you want to do after the event
    }
</script>

但是,ended 事件在我切换曲目后触发了 evn。我正在使用 videojs 播放器。

在这种情况下,我正在寻找播放剪辑 B,播放完后,切换到剪辑 C。

我的代码如下所示:

// clipA is currently playing......
// User hits a button which calls switchVideo();

// video = videojs('video-player');
var switchVideo = function (clipB, clipC) {
    video.src(clipB);
    video.play();

    // When clipB has ended...
    video.ended(function () {
        console.log("clipB ended");
        video.src(clipC);
        video.play();
    })
};

我调用这个函数的那一刻,我可以看到它跳转到 clipB 片刻,然后 onended 事件被触发,然后视频源跳转到 clipC。 如何忽略 clipA 的第一个 onended 事件,而只监听 clipB?

更新: 这是最终的正确答案:

   // video = videojs('video-player');
    var switchVideo = function (clipB, clipC) {
        video.src(clipB);
        video.play();

        // When clipB has ended...
        video.one('ended', function () {
            console.log("clibB ended");
            video.src(clipC);
            video.play();
        })
    };

更新 2: 我发现上面的代码只能工作一次。 (毕竟它被称为 'one'。在我的特殊情况下,我需要能够多次执行此操作。

我做了一个小改动,那就是使用 video.on('ended', myfunction) 而不是 video.one('ended', myFunction)。现在我可以根据需要多次调用它。

我在阅读了 this Stack Overflow 回复后得出了这个结论。

"addEvent" and "removeEvent" were replaced by "on" and "off" per the videojs API. - @Lyn Headley

最终解:

       // video = videojs('video-player');
        var switchVideo = function (clipB, clipC) {
            video.src(clipB);
            video.play();

            // When clipB has ended...
            video.on('ended', function () {
                console.log("clibB ended");
                video.src(clipC);
                video.play();
            })
        };

对于读者:提问者正在使用一个名为 videojs 的库,它封装了原生 JS-

原始代码在每次调用 switchVideo 时都会创建一个新的事件侦听器,导致多次调用 ended 回调。

解决办法是用one('ended')代替ended[相当于on('ended')]:

video.one('ended', function () {
    whatever;
});