===== Documentation Summary =====
Advanced Properties
The Advanced Properties refer to the secondary properties attached to the instance, which are less commonly used.
option
The player's options.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.option);
Note: If you directly modify this option object, the player will not respond immediately.
template
Manages all DOM elements of the player.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.template);
console.info(art.template.$video);
Note: To easily distinguish between DOM elements and regular objects, all DOM elements within the player are named with a $ prefix.
This is the definition of all DOM elements: artplayer/types/template.d.ts
events
Manages all DOM events for the player. It essentially proxies addEventListener and removeEventListener. When using the following methods to handle events, the event will be automatically destroyed when the player is destroyed.
The proxy method is used to proxy DOM events.
The hover method is used to proxy custom hover events.
var container = document.querySelector('.artplayer-app');
var art = new Artplayer({
container: container,
url: '/assets/sample/video.mp4',
});
art.events.proxy(container, 'click', event => {
console.info('click', event);
});
art.events.hover(container, (event) => {
console.info('mouseenter', event);
}, (event) => {
console.info('mouseleave', event);
});
Note: If you need DOM events that only exist during the player's lifecycle, it is strongly recommended to use these functions to avoid memory leaks.
storage
Manages the player's local storage.
The name property is used to set the cache key.
The set method is used to set a cache value.
The get method is used to get a cache value.
The del method is used to delete a cache value.
The clear method is used to clear all cache.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.storage.set('test', { foo: 'bar' });
const test = art.storage.get('test');
console.info(test);
art.storage.del('test');
art.storage.clear();
Note: By default, all player instances share the same localStorage, and the default key is artplayer_settings.
If you want different players to use different localStorage, you can modify art.storage.name.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.storage.name = 'your-storage-key';
art.storage.set('test', { foo: 'bar' });
icons
Manages all svg icons for the player.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.icons.loading);
This is the definition of all icons: artplayer/types/icons.d.ts
i18n
Manages the player's i18n.
The get method is used to get an i18n value.
The update method is used to update the i18n object.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.i18n.get('Play'));
art.i18n.update({
'zh-cn': {
Play: 'Your Play'
}
});
Note: Using art.i18n.update can only update the i18n after instantiation. If you want to update the i18n before instantiation, please use the i18n option in the basic options.
notice
Manages the player's notifications. It only has a show property for displaying notifications.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.notice.show = 'Video Ready To Play';
})
Note: If you want to hide the notice immediately: art.notice.show = '';
layers
Manages the player's layers.
The add method is used to dynamically add a layer.
The remove method is used to dynamically remove a layer.
The update method is used to dynamically update a layer.
The show property is used to set whether all layers are visible.
The toggle method is used to toggle the visibility of all layers.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.layers.add({
html: 'Some Text',
});
setTimeout(() => {
art.layers.show = false;
}, 1000);
});
Refer to the following address for Component Configuration: /component/layers.html
controls
Manages the player's controls.
The add method is used to dynamically add a control.
The remove method is used to dynamically remove a control.
The update method is used to dynamically update controls.
The show property is used to set whether to display all controls.
The toggle method is used to toggle the display of all controls.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.controls.add({
html: 'Some Text',
position: 'left',
});
setTimeout(() => {
art.controls.show = false;
}, 1000);
});
For Component Configuration, please refer to: /component/controls.html
contextmenu
Manages the player's context menu.
The add method is used to dynamically add menu items.
The remove method is used to dynamically remove menu items.
The update method is used to dynamically update menu items.
The show property is used to set whether to display all menu items.
The toggle method is used to toggle the display of all menu items.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.contextmenu.add({
html: 'Some Text',
});
art.contextmenu.show = true;
setTimeout(() => {
art.contextmenu.show = false;
}, 1000);
});
For Component Configuration, please refer to: /component/contextmenu.html
subtitle
Manages the player's subtitle functionality.
The url property sets and returns the current subtitle URL.
The style method sets the style of the current subtitle.
The switch method sets the current subtitle URL and options.
textTrack gets the current text track.
activeCues gets the list of currently active cues.
cues gets the overall list of cues.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.subtitle.url = '/assets/sample/subtitle.srt'
art.subtitle.style({
color: 'red',
});
});
info
Manages the player's information panel, commonly used to view the current status of the player and video, such as version number, resolution, duration, etc.
ArtPlayer Documentation
Info Panel
Control the panel's visibility via art.info.show. The triggered event is named info (see the event documentation for details).
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.info.show = true;
setTimeout(() => {
art.info.show = false;
}, 3000);
});
Loading Layer
Manages the player's loading layer. The show property is used to set whether to display the loading layer. The toggle property is used to toggle the display of the loading layer.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.loading.show = true;
setTimeout(() => {
art.loading.show = false;
}, 1000);
});
Hotkey
Manages the player's hotkey functionality. The add method is used to add hotkeys. The remove method is used to remove hotkeys.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
function hotkeyEvent(event) {
console.info('click', event);
}
art.on('ready', () => {
art.hotkey.add(32, hotkeyEvent);
setTimeout(() => {
art.hotkey.remove(32, hotkeyEvent);
}, 5000);
});
Note: These hotkeys only take effect after the player gains focus (e.g., after clicking on the player).
Mask Layer
Manages the player's mask layer. The show property is used to set whether to display the mask layer. The toggle property is used to toggle the display of the mask layer.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.mask.show = false;
setTimeout(() => {
art.mask.show = true;
}, 1000);
});
Setting Panel
Manages the player's settings panel. The add method is used to dynamically add settings items. The remove method is used to dynamically remove settings items. The update method is used to dynamically update settings items. The show property is used to set whether to display all settings items. The toggle method is used to toggle the display of all settings items.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
flip: true,
playbackRate: true,
aspectRatio: true,
subtitleOffset: true,
});
art.on('ready', () => {
art.setting.show = true;
setTimeout(() => {
art.setting.show = false;
}, 1000);
});
For the Settings Panel, please refer to: /component/setting.html
Plugins
Manages the player's plugin functionality, with only the add method for dynamically adding plugins.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
function myPlugin(art) {
console.info(art);
return {
name: 'myPlugin',
something: 'something',
doSomething: function () {
console.info('doSomething');
},
};
}
art.on('ready', () => {
art.plugins.add(myPlugin);
});
Static Properties
Static Properties refer to the top-level properties mounted on the constructor function, which are very rarely used.
Instances
Returns an array of all player instances. This property can be useful when you need to manage multiple player instances simultaneously.
Example code:
console.info([...Artplayer.instances]);
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info([...Artplayer.instances]);
Version
Returns the version information of the player.
Example code:
console.info(Artplayer.version);
Env
Returns the environment variables of the player.
Example code:
console.info(Artplayer.env);
Build
Returns the build time of the player.
Example code:
console.info(Artplayer.build);
Config
Returns the default configuration for videos.
Example code:
console.info(Artplayer.config);
Utils
Returns the collection of utility functions for the player.
Example code:
console.info(Artplayer.utils);
For all utility functions, please refer to the following address: artplayer/types/utils.d.ts
Scheme
Returns the validation schema for player options.
Example code:
console.info(Artplayer.scheme);
Emitter
Returns the constructor function for the event emitter.
Example code:
console.info(Artplayer.Emitter);
Validator
Returns the validation function for options.
Example code:
console.info(Artplayer.validator);
KindOf
Returns the utility function for type detection.
Example code:
console.info(Artplayer.kindOf);
Html
Returns the html string required by the player.
Example code:
console.info(Artplayer.html);
Option
Returns the default options for the player.
Example code:
console.info(Artplayer.option);
Instance Events
Player events are divided into two types: native events (prefixed with video:) and custom events.
Listen to an event:
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('video:canplay', () => {
console.info('video:canplay');
});
Listen to an event only once:
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.once('video:canplay', () => {
console.info('video:canplay');
});
Manually trigger an event:
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.emit('focus');
Remove an event listener:
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
const onReady = () => {
console.info('ready');
art.off('ready', onReady);
}
art.on('ready', onReady);
For a complete list of events, please refer to: artplayer/types/events.d.ts
Ready Event
Triggered when the player is ready for the first time.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info('ready');
});
Restart Event
Triggered when the player switches URL and becomes playable.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.url = '/assets/sample/video.mp4'
});
art.on('restart', (url) => {
console.info('restart', url);
});
Pause Event
Triggered when the player is paused.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('pause', () => {
console.info('pause');
});
ArtPlayer Event Documentation
The following events are available in ArtPlayer. Each event can be bound using the `art.on()` method. The basic player setup is consistent across examples.
Event: pause
Triggered when the player pauses.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('pause', () => {
console.info('pause');
});
Event: play
Triggered when the player starts playing.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('play', () => {
console.info('play');
});
Event: hotkey
Triggered when a hotkey is pressed on the player. The event object contains details about the key press.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('hotkey', (event) => {
console.info('hotkey', event);
});
Event: destroy
Triggered when the player instance is destroyed. This example shows destroying the player in the ready event handler.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.destroy();
});
art.on('destroy', () => {
console.info('destroy');
});
Event: focus
Triggered when the player element gains focus.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('focus', (event) => {
console.info('focus', event);
});
Event: blur
Triggered when the player element loses focus.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('blur', (event) => {
console.info('blur', event);
});
Event: dblclick
Triggered when the player is double-clicked.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('dblclick', (event) => {
console.info('dblclick', event);
});
Event: click
Triggered when the player is clicked.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('click', (event) => {
console.info('click', event);
});
Event: error
Triggered when an error occurs while loading the video. The callback provides the error and a reconnectTime parameter.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/404.mp4',
});
art.on('error', (error, reconnectTime) => {
console.info(error, reconnectTime);
});
Event: hover
Triggered when the mouse enters or leaves the player area. The state parameter indicates 'enter' or 'leave'.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('hover', (state, event) => {
console.info('hover', state, event);
});
Event: mousemove
Triggered when the mouse moves over the player.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('mousemove', (event) => {
console.info('mousemove', event);
});
Event: resize
Triggered when the player's container dimensions change.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('resize', () => {
console.info('resize');
});
Event: view
Triggered when the player enters or leaves the browser viewport. The state parameter indicates the visibility.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('view', (state) => {
console.info('view', state);
});
Event: lock
Triggered when the screen lock state changes, primarily on mobile devices. Requires the lock option to be enabled.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lock: true,
});
art.on('lock', (state) => {
console.info('lock', state);
});
Event: aspectRatio
Triggered when the player's aspect ratio changes. Requires the aspectRatio and setting options to be enabled.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
aspectRatio: true,
setting: true,
});
art.on('aspectRatio', (aspectRatio) => {
console.info('aspectRatio', aspectRatio);
});
Event: autoHeight
Triggered when the player automatically adjusts its height, typically after calling the art.autoHeight() method.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.autoHeight();
});
art.on('autoHeight', (height) => {
console.info('autoHeight', height);
});
Event: autoSize
Triggered when the player automatically adjusts its size. Requires the autoSize option to be enabled.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoSize: true,
});
art.on('autoSize', () => {
console.info('autoSize');
});
Event: flip
Triggered when the video flip state changes. Requires the flip and setting options to be enabled.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
flip: true,
setting: true,
});
art.on('flip', (flip) => {
console.info('flip', flip);
});
Event: fullscreen
Triggered when the player enters or exits traditional window fullscreen mode. Requires the fullscreen option.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreen: true,
});
art.on('fullscreen', (state) => {
console.info('fullscreen', state);
});
Event: fullscreenError
Triggered when an error occurs while attempting to enter window fullscreen mode.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.fullscreen = true;
});
art.on('fullscreenError', (event) => {
console.info('fullscreenError', event);
});
Event: fullscreenWeb
Triggered when the player enters or exits web fullscreen mode (fullscreen within the browser). Requires the fullscreenWeb option.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreenWeb: true,
});
art.on('fullscreenWeb', (state) => {
console.info('fullscreenWeb', state);
});
Event: mini
Triggered when the player enters or exits mini-player mode.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.mini = true;
});
art.on('mini', (state) => {
console.info('mini', state);
});
Event: pip
Triggered when the player enters or exits picture-in-picture mode. Requires the pip option.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
pip: true,
});
art.on('pip', (state) => {
console.info('pip', state);
});
Event: screenshot
Triggered when a screenshot is captured. Requires the screenshot option. The callback receives the image as a Data URI.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
screenshot: true,
});
art.on('screenshot', (dataUri) => {
console.info('screenshot', dataUri);
});
Event: seek
Triggered when the playback time is sought, either by dragging the progress bar or calling a method.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('seek', (currentTime) => {
console.info('seek', currentTime);
});
Event: subtitleOffset
Triggered when the subtitle synchronization offset is changed. Requires the subtitleOffset option and a subtitle track.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitleOffset: true,
subtitle: {
url: '/assets/sample/subtitle.srt',
},
setting: true,
});
ArtPlayer Event: subtitleOffset
Triggered when the subtitle offset changes.
Example usage:
art.on('subtitleOffset', (offset) => {
console.info('subtitleOffset', offset);
});
ArtPlayer Event: subtitleBeforeUpdate
Triggered before subtitles are updated.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitle: {
url: '/assets/sample/subtitle.srt',
},
});
art.on('subtitleBeforeUpdate', (cues) => {
console.info('subtitleBeforeUpdate', cues);
});
ArtPlayer Event: subtitleAfterUpdate
Triggered after subtitles are updated.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitle: {
url: '/assets/sample/subtitle.srt',
},
});
art.on('subtitleAfterUpdate', (cues) => {
console.info('subtitleAfterUpdate', cues);
});
ArtPlayer Event: subtitleLoad
Triggered when subtitles are loaded.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitle: {
url: '/assets/sample/subtitle.srt',
},
});
art.on('subtitleLoad', (option, cues) => {
console.info('subtitleLoad', cues, option);
});
ArtPlayer Event: info
Triggered when the info panel is shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('info', (state) => {
console.log(state);
});
ArtPlayer Event: layer
Triggered when custom layers are shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('layer', (state) => {
console.log(state);
});
ArtPlayer Event: loading
Triggered when the loader is shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('loading', (state) => {
console.log(state);
});
ArtPlayer Event: mask
Triggered when the mask layer is shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('mask', (state) => {
console.log(state);
});
ArtPlayer Event: subtitle
Triggered when the subtitle layer is shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('subtitle', (state) => {
console.log(state);
});
ArtPlayer Event: contextmenu
Triggered when the context menu is shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('contextmenu', (state) => {
console.log(state);
});
ArtPlayer Event: control
Triggered when the controls are shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('control', (state) => {
console.log(state);
});
ArtPlayer Event: setting
Triggered when the settings panel is shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
});
art.on('setting', (state) => {
console.log(state);
});
ArtPlayer Event: muted
Triggered when the mute state changes.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('muted', (state) => {
console.log(state);
});
ArtPlayer Event: keydown
Listens for keydown events from the document.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('keydown', (event) => {
console.log(event.code);
});
Video Element Events
The following are standard HTML5 video events that ArtPlayer can listen to.
video:canplay - The browser can start playing the media, but estimates there isn't enough data to play through to the end without having to stop for further buffering.
video:canplaythrough - The browser estimates it can play the media through to the end without stopping to buffer content.
video:complete - OfflineAudioContext rendering is complete.
video:durationchange - Triggered when the value of the duration property changes.
video:emptied - The media has become empty; for example, this event is sent when the media has already been loaded (or partially loaded), and the load() method is called to reload it.
video:ended - Playback has stopped because the media has reached its end point.
video:error - An error occurred while fetching media data, or the resource type is not a supported media format.
video:loadeddata - The first frame of the media has finished loading.
video:loadedmetadata - Metadata has been loaded.
video:pause - Playback has been paused.
video:play - Playback has begun.
video:playing - Playback is ready to start after having been paused or delayed due to lack of data.
video:progress - Periodically triggered while the browser is loading the resource.
video:ratechange - The playback rate has changed.
video:seeked - A seek operation has completed.
video:seeking - A seek operation has begun.
video:stalled - The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
video:suspend - Media data loading has been suspended.
video:timeupdate - The time indicated by the currentTime attribute has been updated.
video:volumechange - The volume has changed.
video:waiting - Playback has stopped due to temporary lack of data.
Global Properties
These global properties refer to the top-level properties mounted on the constructor. The property names are all in uppercase. They are subject to change in the future and are generally not used.
DEBUG - Whether to enable debug mode, which can print all built-in events of the video. Default is off.
Example usage:
Artplayer.DEBUG = true;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
STYLE - Returns the player style text.
Example usage:
console.log(Artplayer.STYLE);
CONTEXTMENU - Whether to enable the context menu. Default is on.
Example usage:
Artplayer.CONTEXTMENU = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
NOTICE_TIME - The display duration for notification messages, in milliseconds. Default is 2000.
Example usage:
Artplayer.NOTICE_TIME = 5000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
SETTING_WIDTH - The default width of the settings panel, in pixels. Default is 250.
Example usage:
Artplayer.SETTING_WIDTH = 300;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
loop: true,
flip: true,
playbackRate: true,
aspectRatio: true,
});
SETTING_ITEM_WIDTH - The default width of settings items in the settings panel, in pixels. Default is 200.
Example usage:
Artplayer.SETTING_ITEM_WIDTH = 300;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
loop: true,
flip: true,
playbackRate: true,
aspectRatio: true,
});
SETTING_ITEM_HEIGHT - The default height of settings items in the settings panel, in pixels. Default is 35.
Example usage:
Artplayer.SETTING_ITEM_HEIGHT = 300;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
loop: true,
flip: true,
playbackRate: true,
aspectRatio: true,
});
ArtPlayer provides several static properties that allow you to customize its behavior. These can be set before creating a new player instance.
SETTING_ITEM_HEIGHT
The height of each item in the settings panel, in pixels. The default is 40.
Example of setting a custom height and initializing a player with various settings enabled:
Artplayer.SETTING_ITEM_HEIGHT = 40;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
loop: true,
flip: true,
playbackRate: true,
aspectRatio: true,
});
RESIZE_TIME
The throttle time for the resize event, in milliseconds. The default is 200.
Example of setting a custom throttle time and listening for the resize event:
Artplayer.RESIZE_TIME = 500;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('resize', () => {
console.log('resize');
});
SCROLL_TIME
The throttle time for the scroll event, in milliseconds. The default is 200.
Example of setting a custom throttle time and listening for the scroll event:
Artplayer.SCROLL_TIME = 500;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('scroll', () => {
console.log('scroll');
});
SCROLL_GAP
The boundary tolerance distance for the view event, in pixels. The default is 50.
Example of setting a custom gap and listening for the scroll event:
Artplayer.SCROLL_GAP = 100;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('scroll', () => {
console.log('scroll');
});
AUTO_PLAYBACK_MAX
The maximum record count for the auto-playback feature. The default is 10.
Example of setting a custom maximum and enabling auto-playback:
Artplayer.AUTO_PLAYBACK_MAX = 20;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoPlayback: true,
});
AUTO_PLAYBACK_MIN
The minimum record duration for the auto-playback feature, in seconds. The default is 5.
Example of setting a custom minimum duration and enabling auto-playback:
Artplayer.AUTO_PLAYBACK_MIN = 10;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoPlayback: true,
});
AUTO_PLAYBACK_TIMEOUT
The hide delay duration for the auto-playback feature, in milliseconds. The default is 3000.
Example of setting a custom timeout and enabling auto-playback:
Artplayer.AUTO_PLAYBACK_TIMEOUT = 5000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoPlayback: true,
});
RECONNECT_TIME_MAX
The maximum number of automatic reconnection attempts when a connection error occurs. The default is 5.
Example of setting a custom maximum reconnection count:
Artplayer.RECONNECT_TIME_MAX = 10;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/404.mp4',
});
RECONNECT_SLEEP_TIME
The delay time for automatic reconnection when a connection error occurs, in milliseconds. The default is 1000.
Example of setting a custom reconnection delay:
Artplayer.RECONNECT_SLEEP_TIME = 3000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/404.mp4',
});
CONTROL_HIDE_TIME
The delay time in milliseconds for auto-hiding the bottom control bar. The default is 3000.
Example of setting a custom control hide delay:
Artplayer.CONTROL_HIDE_TIME = 5000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
DBCLICK_TIME
The delay time in milliseconds for double-click events. The default is 300.
Example of setting a custom double-click delay and listening for the event:
Artplayer.DBCLICK_TIME = 500;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('dblclick', () => {
console.log('dblclick');
});
DBCLICK_FULLSCREEN
On desktop, determines whether double-click toggles fullscreen mode. The default is true.
Example of disabling double-click fullscreen:
Artplayer.DBCLICK_FULLSCREEN = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
MOBILE_DBCLICK_PLAY
On mobile devices, determines whether double-click toggles play/pause. The default is true.
Example of disabling double-click play/pause on mobile:
Artplayer.MOBILE_DBCLICK_PLAY = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
MOBILE_CLICK_PLAY
On mobile devices, determines whether single-click toggles play/pause. The default is false.
Example of enabling single-click play/pause on mobile:
Artplayer.MOBILE_CLICK_PLAY = true;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
AUTO_ORIENTATION_TIME
On mobile devices, the delay time in milliseconds for automatic screen rotation. The default is 200.
Example of setting a custom orientation delay and enabling auto-orientation:
Artplayer.AUTO_ORIENTATION_TIME = 500;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoOrientation: true,
});
INFO_LOOP_TIME
The refresh interval in milliseconds for the information panel. The default is 1000.
Example of setting a custom refresh interval and showing the info panel:
Artplayer.INFO_LOOP_TIME = 2000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.info.show = true;
FAST_FORWARD_VALUE
On mobile devices, the speed multiplier for fast-forward during long-press. The default is 3.
Example of setting a custom fast-forward speed and enabling the feature:
Artplayer.FAST_FORWARD_VALUE = 5;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fastForward: true,
});
FAST_FORWARD_TIME
On mobile devices, the delay time in milliseconds for activating fast-forward during long-press. The default is 1000.
Example of setting a custom activation delay and enabling fast-forward:
Artplayer.FAST_FORWARD_TIME = 2000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fastForward: true,
});
TOUCH_MOVE_RATIO
On mobile devices, the speed multiplier for seeking when swiping left/right. The default is 0.5.
Example of setting a custom seek sensitivity:
Artplayer.TOUCH_MOVE_RATIO = 1;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
VOLUME_STEP
The volume adjustment step for keyboard shortcuts. The default is 0.1.
Example of setting a custom volume step:
Artplayer.VOLUME_STEP = 0.2;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
SEEK_STEP
The seeking step in seconds for keyboard shortcuts. The default is 5.
Example of setting a custom seek step:
Artplayer.SEEK_STEP = 10;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
PLAYBACK_RATE
The built-in list of playback rates. The default is [0.5, 0.75, 1, 1.25, 1.5, 2].
Example of setting a custom playback rate list and enabling the feature in settings:
Artplayer.PLAYBACK_RATE = [0.5, 1, 2, 3, 4, 5];
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
playbackRate: true,
});
art.contextmenu.show = true;
art.setting.show = true;
ASPECT_RATIO
The built-in list of video aspect ratios. The default is ['default', '4:3', '16:9'].
Example of setting a custom aspect ratio list and enabling the feature in settings:
Artplayer.ASPECT_RATIO = ['default', '1:1', '2:1', '4:3', '6:5'];
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
aspectRatio: true,
});
art.contextmenu.show = true;
art.setting.show = true;
FLIP
The built-in list of video flip modes. The default is ['normal', 'horizontal', 'vertical'].
Example of setting a custom flip mode list and enabling the feature in settings:
Artplayer.FLIP = ['normal', 'horizontal'];
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
flip: true,
});
art.contextmenu.show = true;
art.setting.show = true;
FULLSCREEN_WEB_IN_BODY
Determines whether to mount the player under the body element during web fullscreen mode. The default is true.
Example of setting this property:
Artplayer.FULLSCREEN_WEB_IN_BODY = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
ArtPlayer Global Configuration
FULLSCREEN_WEB_IN_BODY
This setting determines whether fullscreen mode is applied to the entire web page body. By default, it is set to false.
Example:
Artplayer.FULLSCREEN_WEB_IN_BODY = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreenWeb: true,
});
LOG_VERSION
Sets whether to print the player version in the console. The default value is true.
Example:
Artplayer.LOG_VERSION = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
USE_RAF
Sets whether to use requestAnimationFrame for smoother animations, such as the progress bar. The default value is false.
Example:
Artplayer.USE_RAF = true;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
miniProgressBar: true,
});
REMOVE_SRC_WHEN_DESTROY
Determines whether to remove the video's src attribute and call load() to release media resources when the player is destroyed. The default is true. Set this to false if you want to preserve the video element's state and only remove the UI.
Example:
Artplayer.REMOVE_SRC_WHEN_DESTROY = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
// Only destroys the UI, does not actively clear src
art.destroy();
Writing Plugins
Once you are familiar with the player's properties, methods, and events, writing plugins is straightforward. You can load plugins during player instantiation or add them afterward.
Loading a plugin during instantiation:
function myPlugin(art) {
console.info(art);
return {
name: 'myPlugin',
something: 'something',
doSomething: function () {
console.info('doSomething');
},
};
}
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
plugins: [myPlugin],
});
art.on('ready', () => {
console.info(art.plugins.myPlugin);
});
Loading a plugin after instantiation:
function myPlugin(art) {
console.info(art);
return {
name: 'myPlugin',
something: 'something',
doSomething: function () {
console.info('doSomething');
},
};
}
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.plugins.add(myPlugin);
art.on('ready', () => {
console.info(art.plugins.myPlugin);
});
Example Plugin: Displaying an Image Ad on Pause
This plugin shows an image ad when the video is paused and provides controls to hide or show it.
function adsPlugin(option) {
return (art) => {
art.layers.add({
name: 'ads',
html: ``,
style: {
display: 'none',
position: 'absolute',
top: '20px',
right: '20px',
},
});
function show() {
art.layers.ads.style.display = 'block';
}
function hide() {
art.layers.ads.style.display = 'none';
}
art.controls.add({
name: 'hide-ads',
position: 'right',
html: 'Hide Ads',
tooltip: 'Hide Ads',
click: hide,
style: {
marginRight: '20px'
}
});
art.controls.add({
name: 'show-ads',
position: 'right',
html: 'Show Ads',
tooltip: 'Show Ads',
click: show,
});
art.on('play', hide);
art.on('pause', show);
return {
name: 'adsPlugin',
show,
hide
};
}
}
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
plugins: [
adsPlugin({
url: '/assets/sample/layer.png'
})
],
});
Instance Properties
These are first-level properties available on the player instance.
play
Type: Function
Plays the video.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
art.on('ready', () => {
art.play();
});
pause
Type: Function
Pauses the video.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
art.on('ready', () => {
art.play();
setTimeout(() => {
art.pause();
}, 3000);
});
toggle
Type: Function
Toggles between play and pause.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
art.on('ready', () => {
art.toggle();
setTimeout(() => {
art.toggle();
}, 3000);
});
destroy
Type: Function
Parameter: Boolean
Destroys the player. Accepts a boolean parameter indicating whether to remove the player's HTML from the DOM after destruction. Defaults to true.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.destroy();
});
reset
Type: Function
Resets the player's video element by removing the current src and calling load(). Useful for manually releasing media resources or reinitializing the video tag in single-page applications. Note: The global configuration Artplayer.REMOVE_SRC_WHEN_DESTROY also triggers similar logic when destroy() is called.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
// Only reset the video, do not remove the interface
art.reset();
});
seek
Type: Setter
Parameter: Number
Seeks to a specific time in the video, in seconds.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.seek = 5;
});
forward
Type: Setter
Parameter: Number
Fast-forwards the video by a specified number of seconds.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.forward = 5;
});
backward
Type: Setter
Parameter: Number
Rewinds the video by a specified number of seconds.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.seek = 5;
setTimeout(() => {
art.backward = 2;
}, 3000);
});
volume
Type: Setter/Getter
Parameter: Number
Sets or gets the video volume. The value must be between 0 and 1.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.volume);
art.volume = 0.5;
console.info(art.volume);
});
url
Type: Setter/Getter
Parameter: String
Sets or gets the video URL.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
ArtPlayer Documentation
The following sections describe various properties and methods available on an ArtPlayer instance.
Setting the video URL directly.
Example:
art.on('ready', () => {
art.url = '/assets/sample/video.mp4?t=0';
});
Property: switch
Type: Setter
Parameter: String
Description: Sets the video URL. Similar to `art.url` when setting, but performs some optimization operations.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.seek = 10;
setTimeout(() => {
art.switch = '/assets/sample/video.mp4?t=0';
}, 3000);
});
Method: switchUrl
Type: Function
Parameter: String
Description: Sets the video URL. Similar to `art.url` when setting, but performs some optimization operations.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.seek = 10;
setTimeout(() => {
art.switchUrl('/assets/sample/video.mp4?t=0');
}, 3000);
});
Note: `art.switch` and `art.switchUrl` have the same functionality, but the `art.switchUrl` method returns a `Promise`. It `resolve`s when the new URL is playable and `reject`s when the new URL fails to load.
Method: switchQuality
Type: Function
Parameter: String
Description: Sets the video quality URL. Similar to `art.switchUrl`, but retains the previous playback progress.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.seek = 10;
setTimeout(() => {
art.switchQuality('/assets/sample/video.mp4?t=0');
}, 3000);
});
Property: muted
Type: Setter/Getter
Parameter: Boolean
Description: Sets and gets whether the video is muted.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.muted);
art.muted = true;
console.info(art.muted);
});
Property: currentTime
Type: Setter/Getter
Parameter: Number
Description: Sets and gets the current playback time of the video. Setting the time is similar to `seek`, but it does not trigger additional events.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.currentTime);
art.currentTime = 5;
console.info(art.currentTime);
});
Property: duration
Type: Getter
Description: Gets the duration of the video.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.duration);
});
Note: Some videos may not have a duration, such as live streams or videos that have not been fully decoded. In these cases, the obtained duration will be `0`.
Method: screenshot
Type: Function
Description: Downloads a screenshot of the current video frame. An optional parameter specifies the screenshot filename.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.screenshot('your-name');
});
Method: getDataURL
Type: Function
Description: Gets the `base64` URL of a screenshot of the current video frame. Returns a `Promise`.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', async () => {
const url = await art.getDataURL();
console.info(url)
});
Method: getBlobUrl
Type: Function
Description: Gets the `blob` URL of a screenshot of the current video frame. Returns a `Promise`.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', async () => {
const url = await art.getBlobUrl();
console.info(url);
});
Property: fullscreen
Type: Setter/Getter
Parameter: Boolean
Description: Sets and gets the player's window fullscreen state.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
position: 'right',
html: 'Fullscreen Switch',
click: function () {
art.fullscreen = !art.fullscreen;
},
},
],
});
Note: Due to browser security mechanisms, the page must have prior user interaction (e.g., the user has clicked on the page) before triggering window fullscreen.
Property: fullscreenWeb
Type: Setter/Getter
Parameter: Boolean
Description: Sets and gets the player's web page fullscreen state.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreenWeb: true,
});
art.on('ready', () => {
art.fullscreenWeb = true;
setTimeout(() => {
art.fullscreenWeb = false;
}, 3000);
});
Property: pip
Type: Setter/Getter
Parameter: Boolean
Description: Sets and gets the player's Picture-in-Picture mode.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
position: 'right',
html: 'PIP',
click: function () {
art.pip = !art.pip;
},
},
],
});
Note: Due to browser security mechanisms, the page must have prior user interaction (e.g., the user has clicked on the page) before triggering Picture-in-Picture.
Property: poster
Type: Setter/Getter
Parameter: String
Description: Sets and gets the video poster. The poster effect is only visible before video playback starts.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
poster: '/assets/sample/poster.jpg',
});
art.on('ready', () => {
console.info(art.poster);
art.poster = '/assets/sample/poster.jpg?t=0';
console.info(art.poster);
});
Property: mini
Type: Setter/Getter
Parameter: Boolean
Description: Sets and gets the player's mini mode.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.mini = true;
});
Property: playing
Type: Getter
Parameter: Boolean
Description: Gets whether the video is currently playing.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
art.on('ready', () => {
console.info(art.playing);
});
Property: state
Type: Setter/Getter
Parameter: String
Description: Gets or sets the player's current state. Supported values: `standard` (normal), `mini` (mini window), `pip` (picture-in-picture), `fullscreen` (fullscreen window), `fullscreenWeb` (webpage fullscreen).
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.state); // Default: standard
art.state = 'mini';
});
Method: autoSize
Type: Function
Description: Sets whether the video adapts its size automatically.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.autoSize();
});
Property: rect
Type: Getter
Description: Gets the player's dimensions and coordinate information.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
Here is the documentation reorganized into a clean, plain text format.
First, an example of how to access the player's rect property, which contains its dimensions and coordinates. The information is obtained via getBoundingClientRect.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(JSON.stringify(art.rect));
});
The following properties are getters that provide shortcut access to the rect object. bottom, top, left, right, x, and y correspond to the fields of the same name in a DOMRect. width and height represent the player's current visible width and height.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.width, art.height, art.left, art.top);
});
The flip property is both a setter and a getter. It controls the player's flip state and accepts a string parameter. Supported values are normal, horizontal, and vertical.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.flip);
art.flip = 'horizontal';
console.info(art.flip);
});
The playbackRate property is a setter and getter for the player's playback speed. It accepts a number parameter.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.playbackRate);
art.playbackRate = 2;
console.info(art.playbackRate);
});
The aspectRatio property is a setter and getter for the player's aspect ratio. It accepts a string parameter.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.aspectRatio);
art.aspectRatio = '16:9';
console.info(art.aspectRatio);
});
The autoHeight function is useful when your container has a defined width but an unknown height. It automatically calculates and sets the video height. You need to determine the appropriate timing to call this function.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.autoHeight();
});
art.on('resize', () => {
art.autoHeight();
});
The attr function dynamically gets and sets attributes of the video element. It accepts a string parameter for the attribute name.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.attr('playsInline'));
art.attr('playsInline', true);
console.info(art.attr('playsInline'));
});
The type property is a setter and getter for the video type. It accepts a string parameter.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.type);
art.type = 'm3u8';
console.info(art.type);
});
The theme property is a setter and getter for the player's theme color. It accepts a string parameter.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.theme);
art.theme = '#000';
console.info(art.theme);
});
The airplay function initiates AirPlay.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
position: 'right',
html: 'AirPlay',
click: function () {
art.airplay();
},
},
],
});
The loaded property is a getter that returns the proportion of the video that has been buffered, ranging from 0 to 1. It is often used with the video:timeupdate event.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('video:timeupdate', () => {
console.info(art.loaded);
});
The loadedTime property is a getter that returns the amount of media that has been buffered, in seconds. It is typically used alongside loaded to display detailed buffering progress.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('video:timeupdate', () => {
console.info(art.loadedTime);
});
The played property is a getter that returns the proportion of the video that has been played, ranging from 0 to 1. It is often used with the video:timeupdate event.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('video:timeupdate', () => {
console.info(art.played);
});
The proxy function is a proxy for DOM events, essentially handling addEventListener and removeEventListener. When using proxy to handle events, the event listener is automatically removed when the player is destroyed. This is strongly recommended to avoid memory leaks if you need DOM events to exist only for the duration of the player's lifecycle.
var container = document.querySelector('.artplayer-app');
var art = new Artplayer({
container: container,
url: '/assets/sample/video.mp4',
});
art.proxy(container, 'click', event => {
console.info(event);
});
The query function is a DOM query function similar to document.querySelector, but the search is scoped to the current player instance, preventing errors from duplicate class names.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.query('.art-video'));
The video property quickly returns the player's video element.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.video);
The cssVar function dynamically gets or sets CSS variables.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.log(art.cssVar('--art-theme'));
art.cssVar('--art-theme', 'green');
console.log(art.cssVar('--art-theme'));
});
The quality property is a setter that dynamically sets the list of available quality levels. It accepts an array parameter.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
quality: [
{
default: true,
html: 'SD 480P',
url: '/assets/sample/video.mp4',
},
{
html: 'HD 720P',
url: '/assets/sample/video.mp4',
},
],
});
art.on('ready', () => {
setTimeout(() => {
art.quality = [
{
default: true,
html: '1080P',
url: '/assets/sample/video.mp4',
},
{
html: '4K',
url: '/assets/sample/video.mp4',
},
];
}, 3000);
})
The thumbnails property is a setter and getter for dynamically setting thumbnails. It accepts an object parameter.
Example code for thumbnails would be placed here.
ArtPlayer Documentation
Thumbnails Example
This example shows how to set thumbnails for a video after the player is ready.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.thumbnails = {
url: '/assets/sample/thumbnails.png',
number: 60,
column: 10,
};
});
subtitleOffset
Type: Setter/Getter
Parameter: Number
This property allows you to dynamically set the subtitle offset in seconds.
Example of setting a subtitle offset:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitle: {
url: '/assets/sample/subtitle.srt',
},
});
art.on('ready', () => {
art.subtitleOffset = 1;
});
Context Menu
Configuration
The contextmenu component can be configured with the following properties:
Property Type Description
disable Boolean Whether to disable the component
name String Unique component name for CSS class
index Number Component index for display priority
html String, Element Component DOM element
style Object Component style object
click Function Component click event
mounted Function Triggered after component mount
tooltip String Component tooltip text
Creation
You can create context menu items during player initialization.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
contextmenu: [
{
name: 'your-menu',
html: 'Your Menu',
click: function (...args) {
console.info(args);
art.contextmenu.show = false;
},
},
],
});
art.contextmenu.show = true;
// Get the Element of contextmenu by name
console.info(art.contextmenu['your-menu']);
Addition
You can add a context menu item after the player has been created.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.contextmenu.add({
name: 'your-menu',
html: 'Your Menu',
click: function (...args) {
console.info(args);
art.contextmenu.show = false;
},
});
art.contextmenu.show = true;
// Get the Element of contextmenu by name
console.info(art.contextmenu['your-menu']);
Removal
You can remove a context menu item by its name.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
contextmenu: [
{
name: 'your-menu',
html: 'Your Menu',
click: function (...args) {
console.info(args);
art.contextmenu.show = false;
},
},
],
});
art.contextmenu.show = true;
art.on('ready', () => {
setTimeout(() => {
// Delete the contextmenu by name
art.contextmenu.remove('your-menu')
}, 3000);
});
Update
You can update the properties of an existing context menu item.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
contextmenu: [
{
name: 'your-menu',
html: 'Your Menu',
click: function (...args) {
console.info(args);
art.contextmenu.show = false;
},
},
],
});
art.contextmenu.show = true;
art.on('ready', () => {
setTimeout(() => {
// Update the contextmenu by name
art.contextmenu.update({
name: 'your-menu',
html: 'Your New Menu',
})
}, 3000);
});
Controls
Configuration
Controls can be configured with the following properties:
Property Type Description
disable Boolean Whether to disable the control
name String Unique control name for CSS class identification
index Number Control index for display priority
html String, Element Control's DOM element
style Object Control style object
click Function Control click event handler
mounted Function Triggered after control is mounted
tooltip String Control tooltip text
position String 'left' or 'right' - controls display position
selector Array Array of selector list objects
onSelect Function Function triggered when selector item is clicked
Creation
You can define controls during the player's initialization.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
name: 'your-button',
index: 10,
position: 'left',
html: 'Your Button',
tooltip: 'Your Button',
style: {
color: 'red',
},
click: function (...args) {
console.info('click', args);
},
mounted: function (...args) {
console.info('mounted', args);
},
},
{
name: 'subtitle',
position: 'right',
html: 'Subtitle',
selector: [
{
default: true,
html: 'subtitle 01',
},
{
html: 'subtitle 02',
},
],
onSelect: function (item, $dom) {
console.info(item, $dom);
return 'Your ' + item.html;
},
},
],
});
// Get the Element of control by name
console.info(art.controls['your-button']);
console.info(art.controls['subtitle']);
Adding
You can add a new control to the player after it has been created.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.controls.add({
name: 'button1',
index: 10,
position: 'left',
html: 'Your Button',
tooltip: 'Your Button',
style: {
color: 'red',
},
click: function (...args) {
console.info('click', args);
},
mounted: function (...args) {
console.info('mounted', args);
},
});
// Get the Element of control by name
console.info(art.controls['button1']);
Removal
You can remove a control by its name.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
name: 'button1',
index: 10,
position: 'right',
html: 'Your Button',
tooltip: 'Your Button',
style: {
color: 'red',
},
}
]
});
art.on('ready', () => {
setTimeout(() => {
// Delete the control by name
art.controls.remove('button1');
}, 3000);
});
Updating
You can update the properties of an existing control.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
name: 'button1',
index: 10,
position: 'right',
html: 'Subtitle',
selector: [
{
default: true,
html: 'subtitle 01',
},
{
html: 'subtitle 02',
},
],
}
]
});
ArtPlayer Documentation: Controls Update Example
This example shows how to update a control after the player is ready. After a 3-second delay, it updates a control named 'button1', changing its position, HTML content, and adding a selector list.
art.on('ready', () => {
setTimeout(() => {
// Update the control by name
art.controls.update({
name: 'button1',
index: 10,
position: 'right',
html: 'New Subtitle',
selector: [
{
default: true,
html: 'new subtitle 01',
},
{
html: 'new subtitle 02',
},
],
});
}, 3000);
});
ArtPlayer Documentation: Layer Component
Layer Configuration
The following properties can be used when creating or updating a layer component.
Property Type Description
disable Boolean Whether to disable the component
name String Unique component name for CSS class
index Number Component index for display priority
html String, Element Component DOM element
style Object Component style object
click Function Component click event
mounted Function Triggered after component mount
tooltip String Component tooltip text
Layer Creation
This example shows how to add a layer during the initial Artplayer configuration. It creates a layer with an image, custom styling, and event handlers.
var img = '/assets/sample/layer.png';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
layers: [
{
name: 'potser',
html: `
`,
tooltip: 'Potser Tip',
style: {
position: 'absolute',
top: '50px',
right: '50px',
},
click: function (...args) {
console.info('click', args);
},
mounted: function (...args) {
console.info('mounted', args);
},
},
],
});
// Get the Element of layer by name
console.info(art.layers['potser']);
Layer Addition
This example shows how to add a layer after the Artplayer instance has been created, using the layers.add method.
var img = '/assets/sample/layer.png';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.layers.add({
name: 'potser',
html: `
`,
tooltip: 'Potser Tip',
style: {
position: 'absolute',
top: '50px',
right: '50px',
},
click: function (...args) {
console.info('click', args);
},
mounted: function (...args) {
console.info('mounted', args);
},
});
// Get the Element of layer by name
console.info(art.layers['potser']);
Layer Removal
This example shows how to remove a layer by its name after a delay, using the layers.remove method.
var img = '/assets/sample/layer.png';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
layers: [
{
name: 'potser',
html: `
`,
style: {
position: 'absolute',
top: '50px',
right: '50px',
},
},
],
});
art.on('ready', () => {
setTimeout(() => {
// Delete the layer by name
art.layers.remove('potser');
}, 3000);
});
Layer Update
This example shows how to update an existing layer's properties, such as its HTML content and style, using the layers.update method.
var img = '/assets/sample/layer.png';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
layers: [
{
name: 'potser',
html: `
`,
style: {
position: 'absolute',
top: '50px',
right: '50px',
},
},
],
});
art.on('ready', () => {
setTimeout(() => {
// Update the layer by name
art.layers.update({
name: 'potser',
html: `
`,
style: {
position: 'absolute',
top: '50px',
left: '50px',
},
});
}, 3000);
});
ArtPlayer Documentation: Settings Panel
Built-in Settings
To use the settings panel, set the 'setting' option to true. You can then enable specific built-in settings like flip, playbackRate, aspectRatio, and subtitleOffset.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
flip: true,
playbackRate: true,
aspectRatio: true,
subtitleOffset: true,
});
Creating Button Settings
A button in the settings panel can be configured with the following properties.
Property Type Description
html String, Element Element DOM
icon String, Element Element icon
onClick Function Element click event
width Number List width
tooltip String Tooltip text
This example creates a simple button setting with a custom icon and a click handler.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
settings: [
{
html: 'Button',
icon: '
',
tooltip: 'tooltip',
onClick(item, $dom, event) {
console.info(item, $dom, event);
return 'new tooltip'
}
},
],
});
Creating Selection List Settings
A selection list in the settings panel can be configured with the following properties. The 'selector' array defines the list items.
Property Type Description
html String, Element Element DOM
icon String, Element Element icon
selector Array Element list
onSelect Function Element click event
width Number List width
tooltip String Tooltip text
This example creates two selection lists: one for subtitles and one for video quality. Each item in the selector can have a default state, custom HTML, and a data URL.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
settings: [
{
html: 'Subtitle',
width: 250,
tooltip: 'Subtitle 01',
selector: [
{
default: true,
html: 'Subtitle 01',
url: '/assets/sample/subtitle.srt?id=1',
},
{
html: 'Subtitle 02',
url: '/assets/sample/subtitle.srt?id=2',
},
],
onSelect: function (item, $dom, event) {
console.info(item, $dom, event);
art.subtitle.url = item.url;
return item.html;
},
},
{
html: 'Quality',
width: 150,
tooltip: '1080P',
selector: [
{
default: true,
html: '1080P',
url: '/assets/sample/video.mp4?id=1080',
},
{
html: '720P',
url: '/assets/sample/video.mp4?id=720',
},
{
html: '360P',
url: '/assets/sample/video.mp4?id=360',
},
],
onSelect: function (item, $dom, event) {
console.info(item, $dom, event);
art.switchQuality(item.url, item.html);
return item.html;
},
},
],
});
Creating Nested Lists
The documentation mentions the ability to create nested lists within the settings panel, but a specific code example was not provided in the source text.
ArtPlayer Documentation for AI Learning
This documentation covers the installation, usage, and configuration of ArtPlayer, with a focus on creating and managing settings.
Installation and Usage
You can install ArtPlayer via several package managers or include it directly via script tag.
Using npm:
npm install artplayer
Using yarn:
yarn add artplayer
Using pnpm:
pnpm add artplayer
Using a script tag in HTML:
CDN Links
You can also load ArtPlayer from a CDN.
From jsdelivr.net:
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js
From unpkg.com:
https://unpkg.com/artplayer/dist/artplayer.js
Basic Usage Example
Here is a basic HTML example to get started with ArtPlayer.
',
state: '
',
},
});
Note: For all icon definitions, refer to artplayer/types/icons.d.ts.
Type
Type: String
Default: ''
Used to specify the video format. It needs to be used in conjunction with customType. By default, the video format is determined by the suffix of the video URL (e.g., .m3u8, .mkv, .ts). However, sometimes the video URL lacks the correct suffix, so explicit specification is necessary.
Example specifying an HLS stream:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.m3u8',
type: 'm3u8',
});
Note: The player can parse suffixes like /assets/sample/video.m3u8 but not query parameters like /assets/sample/video?type=m3u8. If you use customType, it is best to also specify the type.
Custom Type
Type: Object
Default: {}
Matches based on the video's type and delegates video decoding to third-party programs. The handler function receives three parameters: video (the video DOM element), url (the video URL), and art (the current instance).
Example setting up a custom handler for HLS streams:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.m3u8',
customType: {
m3u8: function (video, url, art) {
// Your custom playback logic here
},
},
});
Language
Type: String
Default: navigator.language.toLowerCase()
The default display language. Currently supported: en, zh-cn.
Example setting the player to English:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lang: 'en',
});
Note: For more language settings, see /start/i18n.html.
Internationalization (i18n)
Type: Object
Default: {}
Custom i18n configuration. This configuration will be deeply merged with the built-in i18n.
Example adding a new language:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lang: 'your-lang',
i18n: {
'your-lang': {
Play: 'Your Play'
},
},
});
Example modifying an existing language:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
i18n: {
'zh-cn': {
Play: 'Your Play'
},
'zh-tw': {
Play: 'Your Play'
},
},
});
Note: For more language settings, see /start/i18n.html.
Lock
Type: Boolean
Default: false
Whether to display a lock button on mobile devices to hide the bottom control bar.
Example enabling the lock feature:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lock: true,
});
Gesture
Type: Boolean
Default: true
Whether to enable gesture events on the video element on mobile devices.
Example disabling gestures:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
gesture: false,
});
Fast Forward
Type: Boolean
Default: false
Whether to add a long-press video fast-forward feature on mobile devices.
Example enabling fast-forward:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fastForward: true,
});
Here is the documentation reorganized into a clean, plain text format.
Initialization Example
This is a basic example of creating an ArtPlayer instance.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fastForward: true,
});
autoPlayback
Type: Boolean
Default: false
Determines whether to use the automatic playback feature, which resumes video playback from the last watched position.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
id: 'your-url-id',
autoPlayback: true,
});
Note: By default, the player uses the video URL as the key to cache playback progress. If the same video can be accessed via different URLs, you must provide a unique 'id' to serve as the cache key.
autoOrientation
Type: Boolean
Default: false
When enabled on mobile web, this will automatically rotate the player during fullscreen mode based on the video's dimensions and the screen size.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoOrientation: true,
});
airplay
Type: Boolean
Default: false
Controls the visibility of the AirPlay button. Note that this feature is only supported in certain browsers.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
airplay: true,
});
cssVar
Type: Object
Default: {}
This object allows you to override the player's built-in CSS variables for custom styling.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
cssVar: {
// Define custom CSS variables here
},
});
For a full list of available CSS variables, please refer to the official type definition file: artplayer/types/cssVar.d.ts
proxy
Type: function
Default: undefined
This function can return a third-party HTMLCanvasElement or HTMLVideoElement. A common use case is to proxy an existing video DOM element for the player to use.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
proxy: () => document.createElement('video')
});
===== Type Definitions Overview =====
artplayer-plugin-ads.d.ts
This plugin adds advertising capabilities to ArtPlayer, supporting video, image, and HTML ad formats.
interface Option {
/**
* 广告源文本,支持视频链接、图片链接、HTML文本
* Ad source text, supports video links, image links, HTML text
*/
source: string
/**
* 知名广告的类型:'video' | 'image' | 'html'
* Known ad type: 'video' | 'image' | 'html'
*/
type: 'video' | 'image' | 'html'
/**
* 广告必看的时长,单位为秒
* Mandatory ad viewing duration in seconds
*/
playDuration?: number
/**
* 广告总的时长,单位为秒
* Total ad duration in seconds
*/
totalDuration?: number
/**
* 视频广告是否默认静音
* Whether video ads are muted by default
*/
muted?: boolean
}
interface Ads {
name: 'artplayerPluginAds'
/**
* 跳过广告
* Skip ad
*/
skip: () => void
/**
* 暂停广告
* Pause ad
*/
pause: () => void
/**
* 播放广告
* Play ad
*/
play: () => void
}
// The plugin is a function that takes an Option object and returns a function that takes an Artplayer instance, returning an Ads instance.
declare const artplayerPluginAds: (option: Option) => (art: Artplayer) => Ads
export default artplayerPluginAds
export = artplayerPluginAds
export as namespace artplayerPluginAds;
artplayer-plugin-ambilight.d.ts
This plugin creates an ambient light effect around the video player based on the video content.
interface Option {
blur?: string
opacity?: number
frequency?: number
zIndex?: number
duration?: number
}
interface Result {
name: 'artplayerPluginAmbilight'
start: () => void
stop: () => void
}
declare const artplayerPluginAmbilight: (option: Option) => (art: Artplayer) => Result
export default artplayerPluginAmbilight
export = artplayerPluginAmbilight
export as namespace artplayerPluginAmbilight;
artplayer-plugin-asr.d.ts
This plugin provides Automatic Speech Recognition (ASR) functionality, capturing audio chunks for subtitle generation.
interface AudioChunk {
pcm: ArrayBuffer
wav: ArrayBuffer
}
interface AsrPluginOption {
length?: number
interval?: number
sampleRate?: number
autoHideTimeout?: number
onAudioChunk?: (chunk: AudioChunk) => void | Promise
',
// 视频广告的地址
video: '/assets/sample/test1.mp4',
// 广告跳转网址,为空则不跳转
url: 'http://artplayer.org',
// 必须观看的时长,期间不能被跳过,单位为秒
// 当该值大于或等于totalDuration时,不能提前关闭广告
// 当该值等于或小于0时,则随时都可以关闭广告
playDuration: 5,
// 广告总时长,单位为秒
totalDuration: 10,
// 多语言支持
i18n: {
close: '关闭广告',
countdown: '%s秒',
detail: '查看详情',
canBeClosed: '%s秒后可关闭广告',
},
}),
],
})
// 广告被点击
art.on('artplayerPluginAds:click', (ads) => {
console.info('广告被点击', ads)
})
// 广告被跳过
art.on('artplayerPluginAds:skip', (ads) => {
console.info('广告被跳过', ads)
})
ambilight.js example: This example shows the use of the artplayer-plugin-ambilight plugin to create an ambient lighting effect around the video player. It uses the Artplayer constructor and the artplayerPluginAmbilight plugin API. The feature demonstrated is a dynamic color border that samples video content, with configurable blur, opacity, update frequency, and transition duration.
// npm i artplayer-plugin-ambilight
// import artplayerPluginAmbilight from 'artplayer-plugin-ambilight';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoSize: true,
plugins: [
artplayerPluginAmbilight({
blur: '50px',
opacity: 1,
frequency: 10,
duration: 0.3,
}),
],
})
asr.js example: This example demonstrates using a plugin (presumably artplayer-plugin-asr) for Automatic Speech Recognition (ASR) to generate live subtitles from video audio. It uses the Artplayer constructor and a plugin configuration that processes audio chunks. The example includes a custom WebSocket implementation to send PCM audio data to an external ASR service and append the recognized text to the player as subtitles.
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/steve-jobs.mp4',
autoSize: true,
fullscreen: true,
fullscreenWeb: true,
moreVideoAttr: {
// crossOrigin: 'anonymous',
},
plugins: [
artplayerPluginAsr({
length: 2,
interval: 40,
sampleRate: 16000,
autoHideTimeout: 10000,
// Use your AI tool to convert pcm into subtitles
onAudioChunk: ({ pcm }) => startAsr(pcm),
}),
],
})
let ws = null
let loading = false
function stopAsr() {
try {
ws.send(JSON.stringify({ type: 'end' }))
ws.close()
}
catch {}
ws = null
loading = false
}
async function startAsr(buffer) {
if (loading)
return
if (!ws) {
loading = true
const api = 'https://api.aimu.app/asr/tencent?engine_model_type=16k_en'
const { url } = await (await fetch(api)).json()
ws = new WebSocket(url)
ws.binaryType = 'arraybuffer'
ws.onmessage = (event) => {
const { code, result, message } = JSON.parse(event.data)
if (code === 0) {
art.plugins.artplayerPluginAsr.append(result?.voice_text_str)
}
else {
console.error(code, message)
stopAsr()
}
}
loading = false
}
if (ws?.readyState === WebSocket.OPEN) {
ws.send(buffer)
}
}
art.on('destroy', stopAsr)
audio.track.js example: This example demonstrates using the artplayer-plugin-audio-track plugin to add an external audio track (like a commentary or dubbed track) synchronized with the main video. It uses the Artplayer constructor and the artplayerPluginAudioTrack plugin API. The feature shown is playing an AAC audio file alongside the video with configurable offset and sync parameters.
// npm i artplayer-plugin-audio-track
// import artplayerPluginAudioTrack from 'artplayer-plugin-audio-track';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/sprite-fight.mp4',
plugins: [
artplayerPluginAudioTrack({
url: '/assets/sample/sprite-fight.aac',
offset: 0,
sync: 0.3,
}),
],
});
auto.thumbnail.js example: This example demonstrates using the artplayer-plugin-auto-thumbnail plugin to automatically generate video thumbnails for the progress bar. It uses the Artplayer constructor and the artplayerPluginAutoThumbnail plugin API. The feature shown is enabling a visual preview of the video content on hover over the progress bar.
// npm i artplayer-plugin-auto-thumbnail
// import artplayerPluginAutoThumbnail from 'artplayer-plugin-auto-thumbnail';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
plugins: [
artplayerPluginAutoThumbnail({
//
}),
],
})
canvas.js example: This example demonstrates using the artplayer-proxy-canvas proxy to enable canvas-based video rendering, which can be used for advanced visual effects or processing. It uses the Artplayer constructor and the artplayerProxyCanvas proxy API. The example also enables many built-in Artplayer features like thumbnails, screenshot, settings, and playback controls.
// npm i artplayer-proxy-canvas
// import artplayerProxyCanvas from 'artplayer-proxy-canvas';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
poster: '/assets/sample/poster.jpg',
volume: 0.5,
autoplay: false,
autoSize: false,
screenshot: true,
setting: true,
loop: true,
flip: true,
pip: true,
playbackRate: true,
aspectRatio: true,
fullscreen: true,
fullscreenWeb: true,
miniProgressBar: true,
autoPlayback: true,
autoOrientation: true,
thumbnails: {
url: '/assets/sample/thumbnails.png',
number: 60,
column: 10,
scale: 0.85,
},
proxy: artplayerProxyCanvas(),
})
chapter.js example: This example demonstrates using the artplayer-plugin-chapter plugin to add chapter markers and navigation to the video progress bar. It uses the Artplayer constructor and the artplayerPluginChapter plugin API. The feature shown is defining video segments with start/end times and titles, allowing users to jump between chapters.
// npm i artplayer-plugin-chapter
// import artplayerPluginChapter from 'artplayer-plugin-chapter';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoSize: true,
fullscreen: true,
fullscreenWeb: true,
miniProgressBar: true,
autoOrientation: true,
thumbnails: {
url: '/assets/sample/thumbnails.png',
number: 60,
column: 10,
},
plugins: [
artplayerPluginChapter({
chapters: [
{ start: 0, end: 18, title: 'One more chance' },
{ start: 18, end: 36, title: '谁でもいいはずなのに' },
{ start: 36, end: 54, title: '夏の想い出がまわる' },
{ start: 54, end: 72, title: 'こんなとこにあるはずもないのに' },
{ start: 72, end: Infinity, title: '终わり' },
],
}),
],
})
chromecast.js example: This example demonstrates using the artplayer-plugin-chromecast plugin to enable Google Chromecast support for casting video to external devices. It uses the Artplayer constructor and the artplayerPluginChromecast plugin API. The feature shown is integrating casting capability, with optional configuration for the Cast SDK URL and media MIME type.
// npm i artplayer-plugin-chromecast
// import artplayerPluginChromecast from 'artplayer-plugin-chromecast';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreen: true,
fullscreenWeb: true,
plugins: [
artplayerPluginChromecast({
// sdk: '', // The URL of the Cast SDK
// mimeType: '', // The MIME type of the media
}),
],
})
danmuku.js example: This example demonstrates using the artplayer-plugin-danmuku plugin to display danmaku (bullet comments) over the video player. It uses the Artplayer constructor and the artplayerPluginDanmuku plugin API. The feature shown is loading danmaku from an XML file, with extensive configuration for appearance, behavior, filtering, and a custom async function to handle sending new comments.
// npm i artplayer-plugin-danmuku
// import artplayerPluginDanmuku from 'artplayer-plugin-danmuku';
// 使用文档 https://artplayer.org/document/plugin/danmuku.html
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoSize: true,
fullscreen: true,
fullscreenWeb: true,
autoOrientation: true,
plugins: [
artplayerPluginDanmuku({
danmuku: '/assets/sample/danmuku.xml',
// 以下为非必填
speed: 5, // 弹幕持续时间,范围在[1 ~ 10]
margin: [10, '25%'], // 弹幕上下边距,支持像素数字和百分比
opacity: 1, // 弹幕透明度,范围在[0 ~ 1]
color: '#FFFFFF', // 默认弹幕颜色,可以被单独弹幕项覆盖
mode: 0, // 默认弹幕模式: 0: 滚动,1: 顶部,2: 底部
modes: [0, 1, 2], // 弹幕可见的模式
fontSize: 25, // 弹幕字体大小,支持像素数字和百分比
antiOverlap: true, // 弹幕是否防重叠
synchronousPlayback: false, // 是否同步播放速度
mount: undefined, // 弹幕发射器挂载点, 默认为播放器控制栏中部
heatmap: true, // 是否开启热力图
width: 512, // 当播放器宽度小于此值时,弹幕发射器置于播放器底部
points: [], // 热力图数据
filter: danmu => danmu.text.length <= 100, // 弹幕载入前的过滤器
beforeVisible: () => true, // 弹幕显示前的过滤器,返回 true 则可以发送
visible: true, // 弹幕层是否可见
emitter: true, // 是否开启弹幕发射器
maxLength: 200, // 弹幕输入框最大长度, 范围在[1 ~ 1000]
lockTime: 5, // 输入框锁定时间,范围在[1 ~ 60]
theme: 'dark', // 弹幕主题,支持 dark 和 light,只在自定义挂载时生效
OPACITY: {}, // 不透明度配置项
FONT_SIZE: {}, // 弹幕字号配置项
MARGIN: {}, // 显示区域配置项
SPEED: {}, // 弹幕速度配置项
COLOR: [], // 颜色列表配置项
// 手动发送弹幕前的过滤器,返回 true 则可以发送,可以做存库处理
beforeEmit(danmu) {
return new Promise((resolve) => {
console.log(danmu)
setTimeout(() => {
resolve(true)
}, 1000)
})
},
}),
],
})
danmuku.mask.js example: This example demonstrates using both the artplayer-plugin-danmuku and artplayer-plugin-danmuku-mask plugins together. The mask plugin uses MediaPipe Selfie Segmentation to create a background mask, allowing danmaku comments to appear behind the speaker in the video. It uses the Artplayer constructor and both plugin APIs, showing integration of computer vision for enhanced danmaku display.
// npm i artplayer-plugin-danmuku-mask
// import artplayerPluginDanmukuMask from 'artplayer-plugin-danmuku-mask';
// npm i @mediapipe/selfie_segmentation
// 把 node_modules/@mediapipe/selfie_segmentation 目录复制到你的项目下
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/steve-jobs.mp4',
autoSize: true,
fullscreen: true,
fullscreenWeb: true,
autoOrientation: true,
plugins: [
artplayerPluginDanmuku({
danmuku: '/assets/sample/danmuku.xml',
}),
artplayerPluginDanmukuMask({
solutionPath: '/assets/@mediapipe/selfie_segmentation',
}),
],
})
dash.control.js example: This example demonstrates the setup for using the artplayer-plugin-dash-control plugin alongside the dash.js library to play MPEG-DASH adaptive streaming videos. It shows the import statements and dependencies required but does not include the full player instantiation code. The feature indicated is control and playback of DASH streams.
// npm i dashjs
// npm i artplayer-plugin-dash-control
// import dashjs from 'dashjs';
// import artplayerPluginDashControl from 'artplayer-plugin-dash-control';
Example 1: ArtPlayer with DASH plugin and custom playback handler
This example shows how to set up ArtPlayer with a DASH stream, using the dash.js library and a custom plugin for quality and audio track selection. It demonstrates the customType API for handling non-native video formats and the plugin system for extended controls.
const art = new Artplayer({
container: '.artplayer-app',
url: 'https://media.axprod.net/TestVectors/v7-Clear/Manifest_1080p.mpd',
setting: true,
plugins: [
artplayerPluginDashControl({
quality: {
// Show qualitys in control
control: true,
// Show qualitys in setting
setting: true,
// Get the quality name from level
getName: level => `${level.height}P`,
// I18n
title: 'Quality',
auto: 'Auto',
},
audio: {
// Show audios in control
control: true,
// Show audios in setting
setting: true,
// Get the audio name from track
getName: track => track.lang.toUpperCase(),
// I18n
title: 'Audio',
auto: 'Auto',
},
}),
],
customType: {
mpd: function playMpd(video, url, art) {
if (dashjs.supportsMediaSource()) {
if (art.dash)
art.dash.destroy()
const dash = dashjs.MediaPlayer().create()
dash.initialize(video, url, art.option.autoplay)
art.dash = dash
art.on('destroy', () => dash.destroy())
}
else {
art.notice.show = 'Unsupported playback format: mpd'
}
},
},
})
===== dash.js =====
Example 2: Basic DASH playback with dash.js
This example demonstrates a minimal setup for playing a DASH stream using dash.js. It shows the customType API for defining a playback handler and the 'ready' event to access the dash.js instance.
// npm i dashjs
// import dashjs from 'dashjs';
function playMpd(video, url, art) {
if (dashjs.supportsMediaSource()) {
if (art.dash)
art.dash.destroy()
const dash = dashjs.MediaPlayer().create()
dash.initialize(video, url, art.option.autoplay)
art.dash = dash
art.on('destroy', () => dash.destroy())
}
else {
art.notice.show = 'Unsupported playback format: mpd'
}
}
const art = new Artplayer({
container: '.artplayer-app',
url: 'https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps.mpd',
type: 'mpd',
customType: {
mpd: playMpd,
},
})
art.on('ready', () => {
console.info(art.dash)
})
===== document.pip.js =====
Example 3: Document Picture-in-Picture plugin
This example shows how to use the artplayer-plugin-document-pip plugin to enable Document Picture-in-Picture mode. It demonstrates plugin configuration and listening for the custom 'document-pip' event.
// npm i artplayer-plugin-document-pip
// import artplayerPluginDocumentPip from 'artplayer-plugin-document-pip';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
plugins: [
artplayerPluginDocumentPip({
width: 480,
height: 270,
fallbackToVideoPiP: true,
placeholder: `Playing in Document Picture-in-Picture`,
}),
],
})
art.on('document-pip', (state) => {
console.log('Document Picture-in-Picture', state)
})
===== flv.js =====
Example 4: FLV playback with flv.js
This example demonstrates playing an FLV stream using the flv.js library. It shows the customType API and the 'ready' event to access the flv.js player instance.
// npm i flv.js
// import flvjs from 'flv.js';
function playFlv(video, url, art) {
if (flvjs.isSupported()) {
if (art.flv)
art.flv.destroy()
const flv = flvjs.createPlayer({ type: 'flv', url })
flv.attachMediaElement(video)
flv.load()
art.flv = flv
art.on('destroy', () => flv.destroy())
}
else {
art.notice.show = 'Unsupported playback format: flv'
}
}
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.flv',
type: 'flv',
customType: {
flv: playFlv,
},
})
art.on('ready', () => {
console.info(art.flv)
})
===== hls.control.js =====
Example 5: HLS playback with quality and audio controls
This example shows HLS playback using hls.js with the artplayer-plugin-hls-control plugin for quality and audio track selection. It demonstrates a comprehensive customType handler with fallback support for native HLS.
// npm i hls.js
// npm i artplayer-plugin-hls-control
// import Hls from 'hls.js';
// import artplayerPluginHlsControl from 'artplayer-plugin-hls-control';
const art = new Artplayer({
container: '.artplayer-app',
url: 'https://playertest.longtailvideo.com/adaptive/elephants_dream_v4/index.m3u8',
setting: true,
plugins: [
artplayerPluginHlsControl({
quality: {
// Show qualitys in control
control: true,
// Show qualitys in setting
setting: true,
// Get the quality name from level
getName: level => `${level.height}P`,
// I18n
title: 'Quality',
auto: 'Auto',
},
audio: {
// Show audios in control
control: true,
// Show audios in setting
setting: true,
// Get the audio name from track
getName: track => track.name,
// I18n
title: 'Audio',
auto: 'Auto',
},
}),
],
customType: {
m3u8: function playM3u8(video, url, art) {
if (Hls.isSupported()) {
if (art.hls)
art.hls.destroy()
const hls = new Hls()
hls.loadSource(url)
hls.attachMedia(video)
art.hls = hls
art.on('destroy', () => hls.destroy())
}
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = url
}
else {
art.notice.show = 'Unsupported playback format: m3u8'
}
},
},
})
===== hls.js =====
Example 6: Basic HLS playback with hls.js
This example shows a minimal setup for HLS playback using hls.js. It demonstrates the customType API and the 'ready' event to access the Hls instance.
// npm i hls.js
// import Hls from 'hls.js';
function playM3u8(video, url, art) {
if (Hls.isSupported()) {
if (art.hls)
art.hls.destroy()
const hls = new Hls()
hls.loadSource(url)
hls.attachMedia(video)
art.hls = hls
art.on('destroy', () => hls.destroy())
}
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = url
}
else {
art.notice.show = 'Unsupported playback format: m3u8'
}
}
const art = new Artplayer({
container: '.artplayer-app',
url: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8',
type: 'm3u8',
customType: {
m3u8: playM3u8,
},
})
art.on('ready', () => {
console.info(art.hls)
})
===== iframe.js =====
Example 7: Embedding ArtPlayer within an iframe using a tool
This example demonstrates how to embed and control an ArtPlayer instance inside an iframe using the artplayer-tool-iframe utility. It shows cross-document communication via postMessage for features like fullscreenWeb mode.
// npm i artplayer-tool-iframe
// import ArtplayerToolIframe from 'artplayer-tool-iframe';
const $iframe = document.createElement('iframe')
$iframe.allowFullscreen = true
$iframe.width = '100%'
$iframe.height = '100%'
const $container = document.querySelector('.artplayer-app')
$container.innerHTML = ''
$container.appendChild($iframe)
const iframe = new ArtplayerToolIframe({
iframe: $iframe,
url: '/iframe.html',
})
iframe.message(({ type, data }) => {
switch (type) {
case 'fullscreenWeb':
if (data) {
$iframe.classList.add('fullscreenWeb')
}
else {
$iframe.classList.remove('fullscreenWeb')
}
break
default:
break
}
})
iframe.commit(() => {
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreen: true,
fullscreenWeb: true,
})
art.on('fullscreenWeb', (state) => {
ArtplayerToolIframe.postMessage({
type: 'fullscreenWeb',
data: state,
})
})
})
===== index.js =====
Example 8: Placeholder file
This appears to be a placeholder or index file with no code, likely indicating the start of the examples or a file to be populated.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
poster: '/assets/sample/poster.jpg',
volume: 0.5,
isLive: false,
muted: false,
autoplay: false,
pip: true,
autoSize: true,
autoMini: true,
screenshot: true,
setting: true,
loop: true,
flip: true,
playbackRate: true,
aspectRatio: true,
fullscreen: true,
fullscreenWeb: true,
subtitleOffset: true,
miniProgressBar: true,
mutex: true,
backdrop: true,
playsInline: true,
autoPlayback: true,
airplay: true,
theme: '#23ade5',
lang: navigator.language.toLowerCase(),
moreVideoAttr: {
crossOrigin: 'anonymous',
},
settings: [
{
width: 200,
html: 'Subtitle',
tooltip: 'Bilingual',
icon: '
',
click() {
window.open('https://aimu.app')
console.info('You clicked on the custom layer')
},
style: {
position: 'absolute',
top: '20px',
right: '20px',
opacity: '.9',
},
},
],
quality: [
{
default: true,
html: 'SD 480P',
url: '/assets/sample/video.mp4?q=480',
},
{
html: 'HD 720P',
url: '/assets/sample/video.mp4?q=720',
},
],
thumbnails: {
url: '/assets/sample/thumbnails.png',
number: 60,
column: 10,
scale: 0.85,
},
subtitle: {
url: '/assets/sample/subtitle.srt',
type: 'srt',
style: {
color: '#fe9200',
fontSize: '20px',
},
encoding: 'utf-8',
},
highlight: [
{
time: 15,
text: 'One more chance',
},
{
time: 30,
text: '谁でもいいはずなのに',
},
{
time: 45,
text: '夏の想い出がまわる',
},
{
time: 60,
text: 'こんなとこにあるはずもないのに',
},
{
time: 75,
text: '终わり',
},
],
controls: [
{
position: 'right',
html: 'Control',
index: 1,
tooltip: 'Control Tooltip',
style: {
marginRight: '20px',
},
click() {
console.info('You clicked on the custom control')
},
},
],
icons: {
loading: '
',
state: '
`,
click() {
art.notice.show = '你点击了自定义层'
},
style: {
position: 'absolute',
top: '10px',
right: '10px',
opacity: '.9',
},
},
],
icons: {
loading: '
',
state: '