如何使用 Vimeo 在同一个播放器上播放更多视频 player.js

How to play more video on the same player with Vimeo player.js

我试图在同一个 Vimeo 播放器中一个接一个地播放视频,但没有成功。 这是我正在处理的代码。我找不到任何关于如何做到这一点的例子。 我确定我错了,但我不知道如何进一步...

var iframe = document.querySelector('iframe.main-player');
var player = new Vimeo.Player(iframe);
var video_ids = ['123456789', '987654321'];
video_ids.forEach(function(item, index) {
    player.pause();
    player.loadVideo(item);
    player.on('loaded', function() {
        player.play();
    });
})

我不确定,因为现在无法测试,但您可以尝试这样的操作:

var iframe = document.querySelector('iframe.main-player');
var player = new Vimeo.Player(iframe);
var video_ids = ['123456789', '987654321'];
var index = 0;
var playNext = function(data){
    player.pause();
    if(index<=video_ids.length)
       player.loadVideo(video_ids[index++])
}
player.pause();
player.loadVideo(video_ids[index++]);
player.on('loaded', function() {
    player.play();
});

player.on('ended', playNext);

这个想法非常简单,只需收听 ended 事件然后移动到下一个项目。

首先,我们只是创建一个class来保存一些信息,例如列表和当前播放索引:

import Player from "@vimeo/player";

class Playlist {
  constructor(playlist) {
    this.playlist = playlist;
    this.currentIdx = 0;
  }

  init() {
    this.player = new Player("app", {
      id: this.currentItem,
      width: 640
    });

    this.player.on("ended", this.onEnded.bind(this));
  }

  onEnded() {
    if (this.currentIdx < this.playlist.length) {
      this.currentIdx++;

      const nextId = this.currentItem;
      this.player.loadVideo(nextId);

      // Check next item has loaded then play it automatically
      // you might not receive any error in case of having to interact with document
      this.player.on("loaded", () => {
        this.player.play();
      });
    }
  }

  get currentItem() {
    return this.playlist[this.currentIdx];
  }
}

// Try to run 2 items
const pl = new Playlist([59777392, 28582484]);
pl.init();


注意:我还在这里为您创建了一个 codesandbox link https://codesandbox.io/s/focused-firefly-ej0fd?file=/src/index.js