西瓜播放器 HTML5 video video.js 播放器 HTML5播放器 mp4 hls hls.js flv flv.js dash dash.js 无缝切换

API

Hint

The API codes in this section are based on the following environment by default

import Player, { Events } from 'xgplayer'

const player =  new Player({...})

play

  • @return: { Promise<void> | null }
player.play()

// OR

player.play().then(() => {
    // play success
}).catch(() => {
    // play failed, generally occurs when autoplay without user interaction
})

pause

player.pause()

start

  • @param{ string } url video src address

Start the player, start loading media resources, and initialize the video element

Notice

It is not recommended to call manually, and this API may be discarded externally. It is recommended to configure according to the scene autoplay & videoInit

player.start(url)

replay

The player returns to the beginning of the title and plays again, usually called when the playback ends (invalid for live scenes)

player.replay()

seek

  • @param: { Number } time

Jump to a certain time point to continue playing, the parameter is number type, and the unit is second (invalid for live broadcast scene)

player.seek(20)

reload

Reload current video resource

player.reload()

setConfig

Update the configuration information, if the new configuration list contains the configuration items of the built-in plugin, it will call the plugin setConfig to update it

player.setConfig({
  url: '/url',
})

playNext

switch source

Notice

This API is a way to switch playback sources, and internally implements the following functions:

  1. Reset player state: player.resetState()
  2. Update the player and plugin configurations according to the arguments
  3. Start playback (regardless of whether it is paused or not before switching)
player.playNext({
  url: 'new_url',
  poster: 'new_poster_url'...
})

switchURL

  • @param{string} src
  • @param{boolean?} seamless Seamless switching when switch video definition, no black background. Only works if certain plugins implement this behavior (eg.xgplayer-flv

switch source

Hint

This API is a way to switch playback sources, and it implements two functions internally:

  1. set the source for the player, player.src = src
  2. According to the playback state before switching, if it is playing, start playing at the right time
player.switchURL('url')

changeDefinition

@typedef { { url: any, definition: any, [propName: string]: any } } IDefinition

  • @param{ IDefinition } to
  • @param{ IDefinition? } from

Switch playback clarity, please refer to the definition plugin for specific usage

player.changeDefinition({
  url: '/url',
  definition: 1...
})

destroy

Destroy the player object, all built-in objects will be destroyed, and Events.DESTROY will be sent when calling

Notice

After the player instance is destroyed, please clear the reference of the player instance to release the memory.
Calling related APIs after the instance is destroyed may cause errors

player.destroy()
player = null

resetState

Try to pause MediaElement and restore the player UI state

player.resetState()

on

Add event listener

  • param: { String } event Event name, see Events for all supported events
  • param: { function } callback Callback function
const boundFunc = () => {
  // Do sth after play event
}
player.on(Events.PlAY, boundFunc)

off

  • param: { String } event Event name, see Events for all supported events
  • param: { function } callback Registered callback function

Remove an event listener

player.off(Events.PlAY, boundFunc)

emit

  • param: { String } event Event name, see Events for all supported events
  • param: { any } data

Broadcast an event

// Customize an error situation and emit event
player.emit(Events.ERROR, {})

focus

  • @desc: Focus on player, generally for showing control bar, player.isActivewould be turned to true, Events.PLAYER_FOCUSwould be emitted

  • @param: { { autoHide?: boolean, delay?: number } } data

    • autoHide: Auto blur time, default to true 即经过delay时长之后,会自动调用player.blur()
    • delay: Delay time of auto blur by ms, when autoHide: false, delay would be ignored, player will use config.inactive as default

blur

  • @desc: Player UI turns to blur state

  • @param: { { ignorePaused?: boolean } } data

    • ignorePaused: When player was paused, blur action would be ignored, default to true, which means player won't blur when it is paused

canPlayType

  • @param{ string } mimeType MimeType to be detected
  • @return{ boolean } Is it playable

Detect whether the current browser can play the specified type of video

const mimeType = 'video/mp4; codecs="avc1.64001E, mp4a.40.5"'
player.canPlayType(mimeType);

getBufferedRange

  • @param{ TimeRanges? } buffered Get player.buffered if not passed
  • @return{ [number, number] } [start, end] return buffer start time and end time

Returns the buffering time range according the playback currentTime, start indicates the buffering start time, end indicates the buffering expiration time

const [start, end] = player.getBufferedRange();

checkBuffer

  • @param{number} time time point
  • @return{ boolean }

Verify that a point in time is within the current buffer interval

const flag = player.checkBuffer(10);

getFullscreen

  • @desc: Enter fullscreen mode, when entering, a Events.FULLSCREEN_CHANGE Event would be emitted

  • @param: { HTMlElement } el Root element for fullscreen, default to player.root, and must be an ancestral node for player.root.

// listen to fullscreen mode status change
player.on(Events.FULLSCREEN_CHANGE, (isFullscreen) => {
  if (isFullscreen) {
    // fullscreen mode entered
  } else {
    // fullscreen mode exited
  }
})

player.getFullscreen()

exitFullscreen

  • @desc: Exit fullscreen mode. when exiting, a Events.FULLSCREEN_CHANGE event would be emitted

  • @param: { HTMlElement } el Root element for fullscreen, default to player.root, and must be an ancestral node for player.root.

player.exitFullscreen()

getCssFullscreen

  • @desc: Enter css-fullscreen mode (fullscreen mode simulated by css), when entering, a Events.CSS_FULLSCREEN_CHANGE event would be emitted
  • @param: { HTMlElement } el Root element for fullscreen, default to player.root, and must be an ancestral node for player.root.
// listen to css-fullscreen mode status change
player.on(Events.CSS_FULLSCREEN_CHANGE, (isFullscreen) => {
  if (isFullscreen) {
    // css-fullscreen mode entered
  } else {
    // css-fullscreen mode exited
  }
})
player.getCssFullscreen()

exitCssFullscreen

  • @desc: Exit css-fullscreen mode (fullscreen mode simulated by css). when exiting, a Events.CSS_FULLSCREEN_CHANGE event would be emitted
  • @param: { HTMlElement } el Root element for fullscreen, default to player.root, and must be an ancestral node for player.root.
player.exitCssFullscreen()

addClass

  • @param{ string } className class name

Add a CSS class name to the player container player.root

player.addClass('className')

removeClass

  • @param{ string } className class name

Remove the CSS class name for the player container player.root

player.removeClass('className')

hasClass

  • @param{ string } className class name
  • @return{ boolean }

Determine whether the CSS class name exists in the player container player.root

const flag = player.hasClass('className')

setAttribute

  • @param{ string } key
  • @param{ string } value

Set an DOM attribute on player.root

player.setAttribute('key', 'value')

resize

Adjust the size of the player. If there is configuration during initialization fitVideoSizevideoFillMode or the video screen is rotated, this api will trigger the overall size calculation, based on the video screen and the current player container size.

player.resize()

getPlugin

  • @desc: Get plugin instance by name
  • @param: { String } pluginName
const pluginInstance = player.getPlugin('pluginName')

registerPlugin

  • @desc: Dynamic plugin registration
  • @param: { {plugin: function, options:object} | function } plugin constructor
  • @param: { {[propName: string]: any} } Plugin config
  • @return: { object } pluginInstance Plugin instance()
const pluginInstance = player.registerPlugin(MyPlugin)

unRegisterPlugin

  • @desc: Unregister a plugin
  • @param: { {pluginName: string } | string } Registered plugin instance or plugin name
const pluginInstance = player.unRegisterPlugin(pluginName)

usePluginHooks

  • @desc: Enable a hook for specified plugin. See Hooks for detail about hooks
  • @param: { String } pluginName Plugin name
  • @param: { String } hookName Predefined hook name
  • @param: { Function } handler Hook callback
player.usePluginHooks('error', 'errorRetry', (plugin, ...args) => {
  // TODO
})

removePluginHooks

  • @param{ string } pluginName Plugin name
  • @param{ string } hookName Predefined hook name
  • @param{ function } handler Hook callback

Remove a certain hook of a certain plugin, please see Hooks

function errorRetry(plugin, ...args) {
  console.log('errorRetry hook')
}
player.removePluginHooks('error', 'errorRetry', errorRetry)

useHooks

Notice

We don't recommand you to use this api, because it's designed for advanced plugin such as hls/flv/dash playback.

  • @desc: Register a hook callback on player, see Hooks for more detail about player hook
  • @param: { String } hookName Predefined hook name
  • @param: { Function } handler Hook callback
player.useHooks('play', (player, ...args) => {
  // TODO
})

removeHooks

  • @param{ string } hookName Predefined hook name
  • @param{ function } handler Hook callback

Remove a certain hook of the player, please refer to Hooks

const playHook = (player, ...args) => {
  // todo
}
player.removeHooks('play', playHook)

attachVideoEvents

  • @desc: Attach a media element to player, DOM events from this media element would be listened by player
  • @param: { HTMLVideoElement | HTMLAudioElement | customized media elemnt } video Media element
const video = document.createElement('video')
player.attachVideoEvents(video)

detachVideoEvents

  • @desc: Detach media element for current player, player won't listen to DOM events from this media element any more
  • @param: { HTMLVideoElement | HTMLAudioElement | customized media element } video Media element, default to player.video
player.detachVideoEvents()

setEventsMiddleware

Notice

This function is an advanced function. Generally You can directly listen to events

  • @desc: Set a middleware that triggered before player event emitted, and with ability to prevent event emitting, see EventsMiddleware for more detail about middleware
  • @param: { { [eventName: string]: function } } middlewares Middlewares map
const middlewares = {
  play: () => {
    console.log('play middleware')
  },
  pause: () => {
    console.log('pause middleware')
  }
}
player.setEventsMiddleware(middlewares)

removeEventsMiddleware

  • @desc: Remove middlewares
  • @param: { { [propName: string]: function } } middlewares Middlewares map
player.removeEventsMiddleware(middlewares)