Guide
Advanced

Advanced

Listening and sending events

type eventName =
  | 'abort'
  | 'canplay'
  | 'canplaythrough'
  | 'durationchange'
  | 'emptied'
  | 'ended'
  | 'error'
  | 'loadeddata'
  | 'loadedmetadata'
  | 'loadstart'
  | 'pause'
  | 'play'
  | 'playing'
  | 'progress'
  | 'ratechange'
  | 'seeked'
  | 'seeking'
  | 'stalled'
  | 'suspend'
  | 'timeupdate'
  | 'volumechange'
  | 'waiting'
  | 'encrypted'
  | 'waitingforkey'
  | 'enterpictureinpicture'
  | 'leavepictureinpicture'
  | 'fullscreenchange'
  | 'fullscreenerror'
  | 'loadedplugin'
  | 'videoqualitychange'
  | 'videosourcechange'
  | 'destroy'
const listener = (event) => {
  console.log(event)
}
 
// listen
player.on('play', listener)
 
// listen multiple event
player.on(['play', 'pause'], listener)
 
// only once
player.once('play', listener)
 
// remove listener
player.off('play', listener)
 
// emit event
player.emit('cool', { msg: "It's pretty cool!" })

Dynamic change video source

// First, create empty source player
const player = Player.make('#player').create()
 
// just change source
player.changeSource({ src, poster })
 
// will keep time or play state
player.changeQuality({ src })
 
// also be a promise
player.changeSource(
  fetch('xxx').then((resp) => {
    // do anything
    return { src, poster }
  })
)

Write a plugin

class HelloPlugin {
  key = 'hello'
  name = 'oplayer-plugin-hello'
  version = '0.0.1'
 
  apply(player) {
    this.say()
 
    player.on('play', () => {
      console.log('enjoy the video!')
    })
 
    // The return value will be mounted to the player's context
    return this
  }
 
  say(who = this.name) {
    console.log(`hello! ${who}`)
  }
 
  destroy() {
    console.log('bye bye!')
  }
}
 
const player = Player.make('#player', {
  source: {
    title: '君の名は',
    src: '/君の名は.mp4',
    poster: '/poster.png'
  }
})
  .use([new HelloPlugin()])
  .create()
 
player.context.hello.say('world')