1.1.4 • Published 1 year ago

hplayer-js v1.1.4

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

hplayer

安装

script引入

  <link rel="stylesheet" href="https://static-live.haoshitong.com/sdk/player/hplayer.min.css">
  <script src="https://static-live.haoshitong.com/sdk/player/hplayer.min.js"></script>

npm 安装

  yarn add hplayer-js -D
  // yarn add @hst/hplayer

  import hplayer from 'hplayer-js'
  import  'hplayer-js/dist/hplayer.min.css' // 引入css文件

初始化

  let player = hplayer('xxxx', {
    controls: true, // 是否显示控制条
    preload: true, // 是否预加载
    autoplay: true, // 是否自动播放
    src: 'xxxx',// 设置源地址
    sources: [], // 可设置多源
    playbackRates: [0.5, 1, 1.5, 2, 3], // 设置倍速速率
    bigPlayButton: true, // 是否显示大的播放器按钮
    allowMutedPlay: false, // 是否允许静音自动播放 默认为true
    poster: 'xxxx', // 播放器封面
    videojs: {
      playbackRates: [1, 1.5, 2, 3],
      bigPlayButton: false,
      userActions: {
        hotkeys: true, // 是否启用热键
      },
      controlBar: {
        playbackRateMenuButton: false, // 播放速率,当前只有html5模式下才支持设置播放速率
        currentTimeDisplay: true, // 直播模式下显示
        playToggle: false, // 播放按钮显示
        // progressControl: true,   // 进度条
        // timeDivider: true, // ‘/‘ 分隔符
        durationDisplay: true, // 总时间
        // pictureInPictureToggle: true,
        // volumePanel: { // 竖着的音量条
        //   inline: false
        // },
        // fullscreenToggle: true // 全屏按钮是否显示
      },
      plugins: {
        videoJsResolutionSwitcher: {
          default: '720',// 默认清晰度
        }
      }
    }
  })

设置多清晰度

  let player = hplayer('xxxx', {
    controls: true, // 是否显示控制条
    preload: true, // 是否预加载
    sources: [
      {
        src: 'xxxx.mp4',
        type: 'video/mp4',
        label: '360'
      },
      {
        src: 'xxx.mp4',
        type: 'video/mp4',
        label: '720'
      }
    ],
    playbackRates: [0.5, 1, 1.5, 2, 3], // 设置倍速速率
    bigPlayButton: true, // 是否显示大的播放器按钮
    allowMutedPlay: false, // 是否允许静音自动播放 默认为true
    poster: 'xxxx', // 播放器封面
    videojs: {
      plugins: {
        videoJsResolutionSwitcher: {
          default: '720', // 设置默认清晰度
        }
      }
    }
  })

设置水印

  let player = hplayer('xxxx', {
    sources: [
      {
        src: 'xxxx.mp4',
        type: 'video/mp4',
        label: '360'
      },
      {
        src: 'xxx.mp4',
        type: 'video/mp4',
        label: '720'
      }
    ],
    videojs: {
      plugins: {
        waterMarker: {
          username: 'bill', // 必填
          userId: '2222' //必填
        }
      }
    }
  })
  player.waterMarker().close()  // 关闭水印
  player.waterMarker().open() // 打开水印

api

播放

  player.play()

暂停

  player.pause()

跳转到某个已加载的时刻进行播放

  player.seek(1) // 秒

获取当前播放时刻

  player.currentTime() // 秒

获取视频宽度

  player.videoWidth()

获取视频高度

  player.videoHeight()

获取音量值

  player.volume() // 0-1

设置音量值

  player.setVolume() // 0-1

更多(访问videojs官网)

  https://docs.videojs.com/html5

高级功能

Component

添加组件

使用new Component()创建组件, 并设置相关属性

  // Creating an instance of a button
  var player = hplayer('some-video-id');
  var Button = hplayer.getComponent('Button');
  var button = new Button(plzayer, {
    clickHandler: function(event) {
      hplayer.log('Clicked');
    },
    controlText: 'My button', // 文本内容
    className: 'vjs-visible-text' 
  });

  console.log(button.el());

上面的代码会输出

  <button class="vjs-control vjs-button" type="button" aria-disabled="false">
    <span class="vjs-icon-placeholder" aria-hidden="true"></span>
    <span class="vjs-control-text" aria-live="polite"></span>
  </button>

请注意,这已创建按钮,但未将其添加到 DOM。将其添加为组件的子组件会将其添加到 DOM

  player.getChild('ControlBar').addChild(button);

或者,通过将组件的名称传递给addChild,将在一个步骤中创建并添加组件的新实例。

  // Creating an instance of a button and addingit to the player's control bar
 var player = hplayer('some-video-id');
  var button = player.getChild('ControlBar').addChild('button', {
    clickHandler: function(event) {
      hplayer.log('Clicked');
    }
  });

  console.log(button.el());
  // will have the same html result as the previous example

创建组件

hplayer 组件可以继承并注册到 hplayer 以向播放器添加新功能和 UI。

有一些用于创建和注册组件:

hplayer.getComponent(String name): 从 hplayer 中检索组件构造函数。 hplayer.registerComponent(String name, Function Comp): 向 Video.js 注册组件构造函数。 hplayer.extend(Function component, Object properties):提供原型继承。可用于扩展组件的构造函数,返回具有给定属性的新构造函数

此示例创建一个标题栏组件,作为扩展的类Component。

// Get the Component base class from Video.js
const Component = hplayer.getComponent('Component');

class TitleBar extends Component {

  // The constructor of a component receives two arguments: the
  // player it will be associated with and an object of options.
  constructor(player, options = {}) {

    // It is important to invoke the superclass before anything else, 
    // to get all the features of components out of the box!
    super(player, options);

    // If a `text` option was passed in, update the text content of 
    // the component.
    if (options.text) {
      this.updateTextContent(options.text);
    }
  }

  // The `createEl` function of a component creates its DOM element.
  createEl() {
    return hplayer.dom.createEl('div', {

      // Prefixing classes of elements within a player with "vjs-" 
      // is a convention used in Video.js.
      className: 'vjs-title-bar'
    });
  }

  // This function could be called at any time to update the text 
  // contents of the component.
  updateTextContent(text) {

    // If no text was provided, default to "Title Unknown"
    if (typeof text !== 'string') {
      text = 'Title Unknown';
    }

    // Use Video.js utility DOM methods to manipulate the content
    // of the component's element.
    hplayer.emptyEl(this.el());
    hplayer.appendContent(this.el(), text);
  }
}

注册并使用

  // Register the component with Video.js, so it can be used in players.
  hplayer.registerComponent('TitleBar', TitleBar);

  // Create a player.
  var player = hplayer('some-video-id');

  // Add the TitleBar as a child of the player and provide it some text 
  // in its options.
  player.addChild('TitleBar', {text: 'The Title of The Video!'});

更多请查看组件api

插件

编写基本插件

编写一个 JavaScript 函数 基本插件是一个普通的 JavaScript 函数:

function examplePlugin(options) {
  if (options.customClass) {
    this.addClass(options.customClass);
  }
  this.on('playing', function() {
    hplayer.log('playback began!');
  });
}

注意:this插件函数中的值为播放器实例;因此,您可以访问其完整的 API。

注册一个基本插件

现在我们有了一个对播放器执行某些操作的函数,剩下的就是向 Video.js 注册插件:

hplayer.registerPlugin('examplePlugin', examplePlugin);

注意:插件名称的唯一规定是它不能与任何现有的插件或播放器方法冲突。

编写高级插件

编写一个 JavaScript 类/构造函数 如果您熟悉创建组件,则此过程类似。高级插件以 JavaScript 类(又名构造函数)开始。

如果您已经在使用 ES6,则可以将该语法与您选择的转译器/语言(Babel、TypeScript 等)一起使用:

const Plugin = hplayer.getPlugin('plugin');

class ExamplePlugin extends Plugin {

  constructor(player, options) {
    super(player, options);

    if (options.customClass) {
      player.addClass(options.customClass);
    }

    player.on('playing', function() {
      hplayer.log('playback began!');
    });
  }
}

或者使用 ES5:

var Plugin = hplayer.getPlugin('plugin');

var ExamplePlugin = hplayer.extend(Plugin, {

  constructor: function(player, options) {
    Plugin.call(this, player, options);

    if (options.customClass) {
      player.addClass(options.customClass);
    }

    player.on('playing', function() {
      hplayer.log('playback began!');
    });
  }
});

注册高级插件

高级插件的注册过程与基本插件的过程相同。

  hplayer.registerPlugin('examplePlugin', ExamplePlugin);
与基本插件的主要区别

高级插件与基本插件有两个关键区别,在描述其高级功能之前了解这些区别很重要。

this

对于基本插件,this插件函数中的值将是player。

对于高级插件, this的值是插件类的实例。播放器作为第一个参数传递给插件构造函数(并作为属性自动应用于插件实例player),之后传递任何其他参数。

播放器插件名称属性

基本插件和高级插件都是通过调用名称与插件匹配的播放器上的方法来设置的(例如,player.examplePlugin())。

然而,对于高级插件,这个方法就像一个工厂函数,它是一个返回插件实例的新函数

// `examplePlugin` has not been called, so it is a factory function.
player.examplePlugin();

// `examplePlugin` is now a function that returns the same instance of
// `ExamplePlugin` that was generated by the previous call.
player.examplePlugin().someMethodName();
高级插件的特点

到目前为止,我们的示例高级插件在功能上与我们的示例基本插件相同。然而,高级插件带来了许多基本插件所没有的好处。

与组件一样,高级插件提供事件的实现

  • on or one:
  player.examplePlugin().on('example-event', function() {
    hplayer.log('example plugin received an example-event');
  });
  • trigger:
  player.examplePlugin().trigger('example-event');
  • off:
  player.examplePlugin().off('example-event');
事件对象

插件触发的所有事件都包含一个额外的数据对象作为第二个参数。该对象具有三个属性:

name:插件的名称(例如"examplePlugin")作为字符串。 plugin: 插件构造函数(例如ExamplePlugin)。 instance:插件构造函数实例。

状态

为高级插件引入的一个新概念是statefulness。这类似于 React 组件的state属性和setState方法。

每个高级插件实例都有一个state属性,它是一个纯 JavaScript 对象——它可以包含插件作者想要的任何键和值。

state可以通过向插件构造函数添加静态属性来提供默认值:

  ExamplePlugin.defaultState = {
    customClass: 'default-custom-class'
  };

当state通过该setState方法更新时,插件实例会触发一个"statechanged"事件,但前提是某些内容发生了变化!此事件可用作更新 DOM 或执行其他操作的信号。传递给此事件侦听器的事件对象包括一个描述state属性上发生的更改的对象:

player.examplePlugin().on('statechanged', function(e) {
  if (e.changes && e.changes.customClass) {
    this.player
      .removeClass(e.changes.customClass.from)
      .addClass(e.changes.customClass.to);
  }
});

player.examplePlugin().setState({customClass: 'another-custom-class'});

生命周期

与组件一样,高级插件也有生命周期。它们可以使用工厂函数创建,也可以使用它们的dispose方法销毁:

// set up a example plugin instance
player.examplePlugin();

// dispose of it anytime thereafter
player.examplePlugin().dispose(); // 1. 清理插件实例上的所有事件监听器,这有助于避免在清理对象后触发事件导致的错误。2. 删除插件状态和对播放器的引用以避免内存泄漏。

版本

VERSION通过在注册插件之前定义插件的属性来向插件添加版本号:

ExamplePlugin.VERSION = '1.0.1';

hplayer.registerPlugin('examplePlugin', ExamplePlugin);
var version = hplayer.getPluginVersion('examplePlugin');
console.log(version);  // 1.0.1

日志记录

默认情况下,每个高级插件实例都有自己的属性log

player.examplePlugin().log('hello world!');
// 以上将记录以下内容:

// VIDEOJS: $PLAYER_ID: examplePlugin: hello world!

// 该log函数还将具有默认的所有方法/属性hplayer.log;比如, error(), warn(),level()等。

高级示例高级插件

下面是一个完整的 ES6 高级插件,当播放器的状态在播放和暂停之间发生变化时,它会记录一条自定义消息:

<!-- import videojs from ''; -->

const Plugin = hplayer.getPlugin('plugin');

class Advanced extends Plugin {

  constructor(player, options) {
    super(player, options);

    // Whenever the player emits a playing or pause event, we update the
    // state if necessary.
    this.on(player, ['playing', 'pause'], this.updateState);
    this.on('statechanged', this.logState);
  }

  dispose() {
    super.dispose();
    hplayer.log('the advanced plugin is being disposed');
  }

  updateState() {
    this.setState({playing: !this.player.paused()});
  }

  logState(changed) {
    hplayer.log(`the player is now ${this.state.playing ? 'playing' : 'paused'}`);
  }
}

hplayer.registerPlugin('advanced', Advanced);

const player = hplayer('example-player');

player.advanced();

// This will begin playback, which will trigger a "playing" event, which will
// update the state of the plugin, which will cause a message to be logged.
player.play();

// This will pause playback, which will trigger a "paused" event, which will
// update the state of the plugin, which will cause a message to be logged.
player.pause();

player.advanced().dispose();

// This will begin playback, but the plugin has been disposed, so it will not
// log any messages.
player.play();

设置插件

有两种方法可以在播放器上设置(或初始化)插件。对于基本插件和高级插件,这两种方式的工作方式相同。

第一种方式是在创建播放器期间。使用该plugins选项,可以在播放器上自动设置插件:

hplayer('example-player', {
  plugins: {
    examplePlugin: {
      customClass: 'example-class'
    }
  }
});

否则,可以手动设置插件:

var player = hplayer('example-player');
player.examplePlugin({customClass: 'example-class'});

这两种方法在功能上是相同的