Files
ArtPlayer/docs/llms.txt
T
2025-11-29 22:33:12 +08:00

8333 lines
195 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
===== Documentation Summary =====
Advanced Properties
The Advanced Properties here 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.
Control the panel's visibility via art.info.show. The triggered event is named 'info' (see the event documentation for details).
Run 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
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.
Run 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.
Run 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
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.
Run 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
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.
Run 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.
Run 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.
Run 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.
Run Code
console.info(Artplayer.version);
env
Returns the environment variables of the player.
Run Code
console.info(Artplayer.env);
build
Returns the build time of the player.
Run Code
console.info(Artplayer.build);
config
Returns the default configuration for videos.
Run Code
console.info(Artplayer.config);
utils
Returns the collection of utility functions for the player.
Run Code
console.info(Artplayer.utils);
For all utility functions, please refer to: artplayer/types/utils.d.ts
scheme
Returns the validation schema for player options.
Run Code
console.info(Artplayer.scheme);
Emitter
Returns the constructor function for the event emitter.
Run Code
console.info(Artplayer.Emitter);
validator
Returns the validation function for options.
Run Code
console.info(Artplayer.validator);
kindOf
Returns the utility function for type detection.
Run Code
console.info(Artplayer.kindOf);
html
Returns the html string required by the player.
Run Code
console.info(Artplayer.html);
option
Returns the default options for the player.
Run 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:
Run 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:
Run 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:
Run Code
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.emit('focus');
Remove an event listener:
Run 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
Triggered when the player is ready for the first time.
Run Code
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info('ready');
});
restart
Triggered when the player switches URL and becomes playable.
Run 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
Triggered when the player is paused.
Run Code
ArtPlayer Event Documentation
The following events can be used with ArtPlayer to handle various player interactions and state changes.
Pause Event
Triggered when the player is paused.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('pause', () => {
console.info('pause');
});
Play Event
Triggered when the player starts playing.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('play', () => {
console.info('play');
});
Hotkey Event
Triggered when a hotkey is pressed on the player. The event object contains details about the key pressed.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('hotkey', (event) => {
console.info('hotkey', event);
});
Destroy Event
Triggered when the player is destroyed. This example shows how to destroy the player when it's ready.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.destroy();
});
art.on('destroy', () => {
console.info('destroy');
});
Focus Event
Triggered when the player gains focus.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('focus', (event) => {
console.info('focus', event);
});
Blur Event
Triggered when the player loses focus.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('blur', (event) => {
console.info('blur', event);
});
Double Click Event
Triggered when the player is double-clicked.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('dblclick', (event) => {
console.info('dblclick', event);
});
Click Event
Triggered when the player is clicked.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('click', (event) => {
console.info('click', event);
});
Error Event
Triggered when an error occurs while loading the video. The example uses a non-existent video file to demonstrate.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/404.mp4',
});
art.on('error', (error, reconnectTime) => {
console.info(error, reconnectTime);
});
Hover Event
Triggered when the mouse enters or leaves the player. The state parameter indicates whether the mouse is entering or leaving.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('hover', (state, event) => {
console.info('hover', state, event);
});
Mouse Move Event
Triggered when the mouse moves over the player.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('mousemove', (event) => {
console.info('mousemove', event);
});
Resize Event
Triggered when the player's dimensions change.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('resize', () => {
console.info('resize');
});
View Event
Triggered when the player enters or leaves the viewport.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('view', (state) => {
console.info('view', state);
});
Lock Event
Triggered when the lock state changes on mobile devices. Requires the lock option to be enabled.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lock: true,
});
art.on('lock', (state) => {
console.info('lock', state);
});
Aspect Ratio Event
Triggered when the player's aspect ratio changes. Requires both aspectRatio and setting options to be enabled.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
aspectRatio: true,
setting: true,
});
art.on('aspectRatio', (aspectRatio) => {
console.info('aspectRatio', aspectRatio);
});
Auto Height Event
Triggered when the player automatically adjusts its height. The autoHeight method must be called.
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);
});
Auto Size Event
Triggered when the player automatically adjusts its size. Requires the autoSize option to be enabled.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoSize: true,
});
art.on('autoSize', () => {
console.info('autoSize');
});
Flip Event
Triggered when the player is flipped. Requires both flip and setting options to be enabled.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
flip: true,
setting: true,
});
art.on('flip', (flip) => {
console.info('flip', flip);
});
Fullscreen Event
Triggered when the player enters or exits window fullscreen mode. Requires the fullscreen option to be enabled.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreen: true,
});
art.on('fullscreen', (state) => {
console.info('fullscreen', state);
});
Fullscreen Error Event
Triggered when a window fullscreen error occurs. This example attempts to enable fullscreen programmatically.
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);
});
Fullscreen Web Event
Triggered when the player enters or exits web fullscreen mode. Requires the fullscreenWeb option to be enabled.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreenWeb: true,
});
art.on('fullscreenWeb', (state) => {
console.info('fullscreenWeb', state);
});
Mini Event
Triggered when the player enters or exits mini mode. The mini property must be set to true.
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);
});
Picture-in-Picture Event
Triggered when the player enters or exits picture-in-picture mode. Requires the pip option to be enabled.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
pip: true,
});
art.on('pip', (state) => {
console.info('pip', state);
});
Screenshot Event
Triggered when the player captures a screenshot. Requires the screenshot option to be enabled.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
screenshot: true,
});
art.on('screenshot', (dataUri) => {
console.info('screenshot', dataUri);
});
Seek Event
Triggered when the player performs a time seek.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('seek', (currentTime) => {
console.info('seek', currentTime);
});
Subtitle Offset Event
Triggered when subtitle offset changes in the player. Requires subtitleOffset and setting options to be enabled, plus a subtitle URL.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitleOffset: true,
subtitle: {
url: '/assets/sample/subtitle.srt',
},
setting: true,
});
subtitleOffset
This event is triggered when the subtitle offset changes.
art.on('subtitleOffset', (offset) => {
console.info('subtitleOffset', offset);
});
subtitleBeforeUpdate
Triggered before subtitles are updated.
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);
});
subtitleAfterUpdate
Triggered after subtitles are updated.
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);
});
subtitleLoad
Triggered when subtitles are loaded.
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);
});
info
Triggered when the info panel is shown or hidden.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('info', (state) => {
console.log(state);
});
layer
Triggered when custom layers are shown or hidden.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('layer', (state) => {
console.log(state);
});
loading
Triggered when the loader is shown or hidden.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('loading', (state) => {
console.log(state);
});
mask
Triggered when the mask layer is shown or hidden.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('mask', (state) => {
console.log(state);
});
subtitle
Triggered when the subtitle layer is shown or hidden.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('subtitle', (state) => {
console.log(state);
});
contextmenu
Triggered when the context menu is shown or hidden.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('contextmenu', (state) => {
console.log(state);
});
control
Triggered when the controls are shown or hidden.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('control', (state) => {
console.log(state);
});
setting
Triggered when the settings panel is shown or hidden.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
});
art.on('setting', (state) => {
console.log(state);
});
muted
Triggered when the mute state changes.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('muted', (state) => {
console.log(state);
});
keydown
Listens for keydown events from the document.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('keydown', (event) => {
console.log(event.code);
});
Video Events
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.
Artplayer.DEBUG = true;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
STYLE
Returns the player style text.
console.log(Artplayer.STYLE);
CONTEXTMENU
Whether to enable the context menu. Default is on.
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.
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.
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.
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.
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,
});
To configure the height of setting menu items, set the SETTING_ITEM_HEIGHT property. The default value is 40 pixels.
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 controls the throttle time for resize events in milliseconds. The default is 200.
Artplayer.RESIZE_TIME = 500;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('resize', () => {
console.log('resize');
});
SCROLL_TIME sets the throttle time for scroll events in milliseconds. The default is 200.
Artplayer.SCROLL_TIME = 500;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('scroll', () => {
console.log('scroll');
});
SCROLL_GAP defines the boundary tolerance distance for view events in pixels. The default is 50.
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 specifies the maximum record count for auto-playback. The default is 10.
Artplayer.AUTO_PLAYBACK_MAX = 20;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoPlayback: true,
});
AUTO_PLAYBACK_MIN sets the minimum record duration for auto-playback in seconds. The default is 5.
Artplayer.AUTO_PLAYBACK_MIN = 10;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoPlayback: true,
});
AUTO_PLAYBACK_TIMEOUT controls the hide delay duration for auto-playback in milliseconds. The default is 3000.
Artplayer.AUTO_PLAYBACK_TIMEOUT = 5000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoPlayback: true,
});
RECONNECT_TIME_MAX defines the maximum number of automatic reconnection attempts. The default is 5.
Artplayer.RECONNECT_TIME_MAX = 10;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/404.mp4',
});
RECONNECT_SLEEP_TIME sets the delay time for automatic reconnection in milliseconds. The default is 1000.
Artplayer.RECONNECT_SLEEP_TIME = 3000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/404.mp4',
});
CONTROL_HIDE_TIME determines the delay time for auto-hiding the bottom control bar in milliseconds. The default is 3000.
Artplayer.CONTROL_HIDE_TIME = 5000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
DBCLICK_TIME sets the delay time for double-click events in milliseconds. The default is 300.
Artplayer.DBCLICK_TIME = 500;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('dblclick', () => {
console.log('dblclick');
});
DBCLICK_FULLSCREEN controls whether double-click toggles fullscreen on desktop. The default is true.
Artplayer.DBCLICK_FULLSCREEN = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
MOBILE_DBCLICK_PLAY determines whether double-click toggles play/pause on mobile devices. The default is true.
Artplayer.MOBILE_DBCLICK_PLAY = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
MOBILE_CLICK_PLAY controls whether single-click toggles play/pause on mobile devices. The default is false.
Artplayer.MOBILE_CLICK_PLAY = true;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
AUTO_ORIENTATION_TIME sets the delay time for automatic screen rotation on mobile devices in milliseconds. The default is 200.
Artplayer.AUTO_ORIENTATION_TIME = 500;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoOrientation: true,
});
INFO_LOOP_TIME defines the refresh interval for the information panel in milliseconds. The default is 1000.
Artplayer.INFO_LOOP_TIME = 2000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.info.show = true;
FAST_FORWARD_VALUE sets the speed multiplier for fast-forward during long-press on mobile devices. The default is 3.
Artplayer.FAST_FORWARD_VALUE = 5;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fastForward: true,
});
FAST_FORWARD_TIME controls the delay time for activating fast-forward during long-press on mobile devices in milliseconds. The default is 1000.
Artplayer.FAST_FORWARD_TIME = 2000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fastForward: true,
});
TOUCH_MOVE_RATIO sets the speed multiplier for seeking when swiping left/right on mobile devices. The default is 0.5.
Artplayer.TOUCH_MOVE_RATIO = 1;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
VOLUME_STEP defines the volume adjustment step for keyboard shortcuts. The default is 0.1.
Artplayer.VOLUME_STEP = 0.2;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
SEEK_STEP sets the seeking step in seconds for keyboard shortcuts. The default is 5.
Artplayer.SEEK_STEP = 10;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
PLAYBACK_RATE contains the built-in list of playback rates. The default is [0.5, 0.75, 1, 1.25, 1.5, 2].
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 contains the built-in list of video aspect ratios. The default is ['default', '4:3', '16:9'].
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 contains the built-in list of video flip modes. The default is ['normal', 'horizontal', 'vertical'].
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.
ArtPlayer Documentation
FULLSCREEN_WEB_IN_BODY
This setting determines whether fullscreen mode places the player within the body element. The default value is false.
Example code:
Artplayer.FULLSCREEN_WEB_IN_BODY = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreenWeb: true,
});
LOG_VERSION
Controls whether the player version is printed to console. The default is true.
Example code:
Artplayer.LOG_VERSION = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
USE_RAF
Enables or disables requestAnimationFrame usage. Defaults to false. Primarily used for smoother progress bar animations.
Example code:
Artplayer.USE_RAF = true;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
miniProgressBar: true,
});
REMOVE_SRC_WHEN_DESTROY
Determines if video source is removed and load() is called when destroying the player. Defaults to true. This helps reduce resource usage in single-page applications with frequent player creation/destruction. Set to false if you want to preserve video element state while only removing the UI.
Example code:
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 understand the player's properties, methods, and events, creating plugins is straightforward.
You can load plugins during player 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);
});
You can also add plugins 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);
});
Here's an example plugin that shows an image ad when video is paused:
function adsPlugin(option) {
return (art) => {
art.layers.add({
name: 'ads',
html: `<img style="width: 100px" src="${option.url}">`,
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 mounted on the player instance that are commonly used.
play
Type: Function
Starts video playback.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
art.on('ready', () => {
art.play();
});
pause
Type: Function
Pauses video playback.
Example code:
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 states.
Example code:
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 after destruction. Defaults to true.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.destroy();
});
reset
Type: Function
Resets the video element by removing current source and calling load(). Useful for manually releasing media resources or reinitializing video tags in single-page applications.
Note: The global configuration Artplayer.REMOVE_SRC_WHEN_DESTROY automatically executes similar logic when destroy() is called.
Example code:
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, specified in seconds.
Example code:
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 specified number of seconds.
Example code:
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 specified number of seconds.
Example code:
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 and gets the video volume. Accepts values between 0 and 1.
Example code:
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 and gets the video URL.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
ArtPlayer Documentation
Ready Event Example
The following code demonstrates how to set the video URL when the player is ready:
art.on('ready', () => {
art.url = '/assets/sample/video.mp4?t=0';
});
Switch Property
Type: Setter
Parameter: String
Sets the video URL. Similar to art.url when setting, but performs some optimization operations.
Example showing how to switch video source after 3 seconds:
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);
});
SwitchUrl Function
Type: Function
Parameter: String
Sets the video URL. Similar to art.url when setting, but performs some optimization operations.
Example showing how to switch video source using the function method:
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 resolves when the new URL is playable and rejects when the new URL fails to load.
SwitchQuality Function
Type: Function
Parameter: String
Sets the video quality URL. Similar to art.switchUrl, but retains the previous playback progress.
Example showing quality switching:
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);
});
Muted Property
Type: Setter/Getter
Parameter: Boolean
Sets and gets whether the video is muted.
Example showing how to check and set muted state:
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);
});
CurrentTime Property
Type: Setter/Getter
Parameter: Number
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 showing how to get and set current time:
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);
});
Duration Property
Type: Getter
Gets the duration of the video.
Example showing how to get video duration:
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.
Screenshot Function
Type: Function
Downloads a screenshot of the current video frame. An optional parameter specifies the screenshot filename.
Example showing how to take a screenshot:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.screenshot('your-name');
});
GetDataURL Function
Type: Function
Gets the base64 URL of a screenshot of the current video frame. Returns a Promise.
Example showing how to get screenshot as data URL:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', async () => {
const url = await art.getDataURL();
console.info(url)
});
GetBlobUrl Function
Type: Function
Gets the blob URL of a screenshot of the current video frame. Returns a Promise.
Example showing how to get screenshot as blob URL:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', async () => {
const url = await art.getBlobUrl();
console.info(url);
});
Fullscreen Property
Type: Setter/Getter
Parameter: Boolean
Sets and gets the player's window fullscreen state.
Example showing fullscreen toggle in controls:
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.
FullscreenWeb Property
Type: Setter/Getter
Parameter: Boolean
Sets and gets the player's web page fullscreen state.
Example showing web fullscreen usage:
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);
});
Pip Property
Type: Setter/Getter
Parameter: Boolean
Sets and gets the player's Picture-in-Picture mode.
Example showing PIP toggle in controls:
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.
Poster Property
Type: Setter/Getter
Parameter: String
Sets and gets the video poster. The poster effect is only visible before video playback starts.
Example showing poster usage:
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);
});
Mini Property
Type: Setter/Getter
Parameter: Boolean
Sets and gets the player's mini mode.
Example showing mini mode activation:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.mini = true;
});
Playing Property
Type: Getter
Parameter: Boolean
Gets whether the video is currently playing.
Example showing how to check playing status:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
art.on('ready', () => {
console.info(art.playing);
});
State Property
Type: Setter/Getter
Parameter: String
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 showing state usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.state); // Default: standard
art.state = 'mini';
});
AutoSize Function
Type: Function
Sets whether the video adapts its size automatically.
Example showing autoSize usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.autoSize();
});
Rect Property
Type: Getter
Gets the player's dimensions and coordinate information.
Example showing rect usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.rect);
});
To initialize an ArtPlayer instance, create a new object with the container and video URL specified. The following example demonstrates setting up the player and logging its dimensions and position once it's ready.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(JSON.stringify(art.rect));
});
Note: The dimension and coordinate information is obtained via getBoundingClientRect.
Properties: bottom, top, left, right, x, y, width, height
Type: Getter
These properties provide shortcut access to the rect object. bottom, top, left, right, x, and y correspond to the fields of the same name in DOMRect. width and height represent the player's current visible width and height.
Example code:
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);
});
Property: flip
Type: Setter/Getter
Parameter: String
Sets and gets the player flip state. Supported values are normal, horizontal, and vertical.
Example code:
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);
});
Property: playbackRate
Type: Setter/Getter
Parameter: Number
Sets and gets the player's playback rate.
Example code:
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);
});
Property: aspectRatio
Type: Setter/Getter
Parameter: String
Sets and gets the player's aspect ratio.
Example code:
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);
});
Property: autoHeight
Type: Function
When the container only has a defined width, this property can automatically calculate and set the video height.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.autoHeight();
});
art.on('resize', () => {
art.autoHeight();
});
Note: This property is useful when your container has only a defined width but an unknown height. It automatically calculates the video height, but you need to determine the appropriate timing to set this property.
Property: attr
Type: Function
Parameter: String
Dynamically gets and sets attributes of the video element.
Example code:
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'));
});
Property: type
Type: Setter/Getter
Parameter: String
Dynamically gets and sets the video type.
Example code:
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);
});
Property: theme
Type: Setter/Getter
Parameter: String
Dynamically gets and sets the player's theme color.
Example code:
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);
});
Property: airplay
Type: Function
Initiates AirPlay.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
position: 'right',
html: 'AirPlay',
click: function () {
art.airplay();
},
},
],
});
Property: loaded
Type: Getter
The proportion of the video that has been buffered, ranging from 0 to 1. Often used with the video:timeupdate event.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('video:timeupdate', () => {
console.info(art.loaded);
});
Property: loadedTime
Type: Getter
The amount of media that has been buffered, in seconds. Typically used alongside loaded to display detailed buffering progress.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('video:timeupdate', () => {
console.info(art.loadedTime);
});
Property: played
Type: Getter
The proportion of the video that has been played, ranging from 0 to 1. Often used with the video:timeupdate event.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('video:timeupdate', () => {
console.info(art.played);
});
Property: proxy
Type: Function
A proxy function for DOM events, essentially proxying addEventListener and removeEventListener. When using proxy to handle events, the event is automatically removed when the player is destroyed.
Example code:
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);
});
Note: If you need DOM events to exist only for the duration of the player's lifecycle, it is strongly recommended to use this function to avoid memory leaks.
Property: query
Type: Function
A DOM query function, similar to document.querySelector, but the search is scoped to the current player instance, preventing errors from duplicate class names.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.query('.art-video'));
Property: video
Type: Element
Quickly returns the player's video element.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.video);
Property: cssVar
Type: Function
Dynamically gets or sets CSS variables.
Example code:
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'));
});
Property: quality
Type: Setter
Parameter: Array
Dynamically sets the list of available quality levels.
Example code:
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);
});
Property: thumbnails
Type: Setter/Getter
Parameter: Object
Dynamically set thumbnails.
Example code:
Initializing ArtPlayer with thumbnails
Here is an example of initializing ArtPlayer with thumbnail support. The thumbnails configuration is set when 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,
};
});
Subtitle Offset
The subtitleOffset property allows you to dynamically adjust subtitle timing. It can be both set and retrieved.
Type: Setter/Getter
Parameter: Number
This example shows how to set a subtitle offset of 1 second:
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 Options
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
Creating Context Menu Items
You can add custom 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']);
Adding Context Menu Items After Initialization
You can also add context menu items 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']);
Removing Context Menu Items
This example shows how to remove a context menu item after a delay:
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);
});
Updating Context Menu Items
You can update existing context menu items:
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 Options
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
Creating Controls
This example shows how to create custom controls during player 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: '<span style="color:red">subtitle 01</span>',
},
{
html: '<span style="color:yellow">subtitle 02</span>',
},
],
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 Controls After Initialization
You can add controls to an existing player instance:
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']);
Removing Controls
This example demonstrates how to remove a control after a delay:
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 Controls
You can update existing controls with new properties:
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',
},
],
}
]
});
Here is the reorganized documentation for learning ArtPlayer:
Controls Update Example
This example shows how to update a control after the player is ready. After a 3-second delay, it updates a button control with new properties including position and selector options.
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);
});
LAYER COMPONENT
Layer Configuration Options
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
You can create layers during player initialization. This example creates a layer with an image that has 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: `<img style="width: 100px" src="${img}">`,
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
You can also add layers after player initialization 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: `<img style="width: 100px" src="${img}">`,
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 name after a 3-second delay.
var img = '/assets/sample/layer.png';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
layers: [
{
name: 'potser',
html: `<img style="width: 100px" src="${img}">`,
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 demonstrates updating layer properties after initialization, including changing the HTML content and style positioning.
var img = '/assets/sample/layer.png';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
layers: [
{
name: 'potser',
html: `<img style="width: 100px" src="${img}">`,
style: {
position: 'absolute',
top: '50px',
right: '50px',
},
},
],
});
art.on('ready', () => {
setTimeout(() => {
// Update the layer by name
art.layers.update({
name: 'potser',
html: `<img style="width: 200px" src="${img}">`,
style: {
position: 'absolute',
top: '50px',
left: '50px',
},
});
}, 3000);
});
SETTINGS PANEL
Built-in Settings
To enable the settings panel, set setting to true. The panel includes four built-in items: 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
Button settings configuration options:
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
Example of creating a custom button in the settings panel:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
settings: [
{
html: 'Button',
icon: '<img width="22" height="22" src="/assets/img/state.svg">',
tooltip: 'tooltip',
onClick(item, $dom, event) {
console.info(item, $dom, event);
return 'new tooltip'
}
},
],
});
Creating Selection List Settings
Selection list configuration options:
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
Example of creating selection lists for subtitle and quality settings:
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: '<span style="color:red">Subtitle 01</span>',
url: '/assets/sample/subtitle.srt?id=1',
},
{
html: '<span style="color:yellow">Subtitle 02</span>',
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 settings panel also supports nested list structures for more complex configuration options.
ArtPlayer Documentation
Installation and Usage
Installation
You can install ArtPlayer using npm, yarn, pnpm, or via script tag.
npm installation:
npm install artplayer
yarn installation:
yarn add artplayer
pnpm installation:
pnpm add artplayer
Script tag installation:
<script src="path/to/artplayer.js"></script>
CDN
You can also use ArtPlayer via CDN:
jsdelivr.net CDN:
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js
unpkg.com CDN:
https://unpkg.com/artplayer/dist/artplayer.js
Usage
Basic HTML implementation example:
<html>
<head>
<title>ArtPlayer Demo</title>
<meta charset="UTF-8" />
<style>
.artplayer-app {
width: 400px;
height: 300px;
}
</style>
</head>
<body>
<div class="artplayer-app"></div>
<script src="path/to/artplayer.js"></script>
<script>
const art = new Artplayer({
container: '.artplayer-app',
url: 'path/to/video.mp4',
});
</script>
</body>
</html>
Important note: The player's dimensions depend on the size of its container, so your container must have defined dimensions.
For more usage examples, visit:
/packages/artplayer-template
Vue.js Integration
ArtPlayer Vue component:
<template>
<div ref="$container" />
</template>
<script setup>
import Artplayer from 'artplayer'
import { onBeforeUnmount, onMounted, ref, shallowRef } from 'vue'
const props = defineProps({
option: {
type: Object,
required: true,
},
})
const emit = defineEmits(['getInstance'])
const art = shallowRef(null)
const $container = ref(null)
onMounted(() => {
art.value = new Artplayer({
...props.option,
container: $container.value,
})
emit('getInstance', art.value)
})
onBeforeUnmount(() => {
art.value.destroy(false)
})
</script>
Vue implementation example:
<template>
<Artplayer :option="option" :style="style" @get-instance="getInstance" />
</template>
<script setup>
import { reactive } from 'vue'
import Artplayer from './Artplayer.vue'
const option = reactive({
url: 'path/to/video.mp4',
})
const style = reactive({
width: '600px',
height: '400px',
margin: '60px auto 0',
})
function getInstance(art) {
console.log(art)
}
</script>
Important note: Artplayer is not reactive.
Settings Configuration
Multi-level Settings Example
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
settings: [
{
html: 'Multi-level',
selector: [
{
html: 'Setting 01',
width: 150,
selector: [
{
html: 'Setting 01 - 01',
},
{
html: 'Setting 01 - 02',
},
],
onSelect: function (item, $dom, event) {
console.info(item, $dom, event);
return item.html;
},
},
{
html: 'Setting 02',
width: 150,
selector: [
{
html: 'Setting 02 - 01',
},
{
html: 'Setting 02 - 02',
},
],
onSelect: function (item, $dom, event) {
console.info(item, $dom, event);
return item.html;
},
},
],
},
],
});
Toggle Button Settings
Properties for toggle button:
Property: html, Type: String, Element, Description: DOM element of the item
Property: icon, Type: String, Element, Description: Icon of the item
Property: switch, Type: Boolean, Description: Default state of the button
Property: onSwitch, Type: Function, Description: Button toggle event
Property: tooltip, Type: String, Description: Tooltip text
Toggle button implementation:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
settings: [
{
html: 'PIP Mode',
tooltip: 'Close',
icon: '<img width="22" height="22" src="/assets/img/state.svg">',
switch: false,
onSwitch: function (item, $dom, event) {
console.info(item, $dom, event);
const nextState = !item.switch;
art.pip = nextState;
item.tooltip = nextState ? 'Open' : 'Close';
return nextState;
},
},
],
});
Range Slider Settings
Properties for range slider:
Property: html, Type: String, Element, Description: DOM element of the item
Property: icon, Type: String, Element, Description: Icon of the item
Property: range, Type: Array, Description: Default state array
Property: onRange, Type: Function, Description: Event triggered on completion
Property: onChange, Type: Function, Description: Event triggered on change
Property: tooltip, Type: String, Description: Tooltip text
Range array structure:
const range = [5, 1, 10, 1];
const value = range[0];
const min = range[1];
const max = range[2];
const step = range[3];
Range slider implementation:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
settings: [
{
html: 'Slider',
tooltip: '5x',
icon: '<img width="22" height="22" src="/assets/img/state.svg">',
range: [5, 1, 10, 1],
onChange: function (item, $dom, event) {
console.info(item, $dom, event);
return item.range[0] + 'x';
},
},
],
});
Adding Settings Dynamically
You can add settings after initialization:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
});
art.setting.show = true;
art.setting.add({
html: 'Slider',
tooltip: '5x',
icon: '<img width="22" height="22" src="/assets/img/state.svg">',
range: [5, 1, 10, 1],
});
Removing Settings
Settings can be removed by name:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
flip: true,
settings: [
{
name: 'slider',
html: 'Slider',
tooltip: '5x',
icon: '<img width="22" height="22" src="/assets/img/state.svg">',
range: [5, 1, 10, 1],
},
],
});
art.setting.show = true;
art.on('ready', () => {
setTimeout(() => {
// Delete the setting by name
art.setting.remove('slider');
}, 3000);
});
Updating Settings
Existing settings can be updated:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
settings: [
{
name: 'slider',
html: 'Slider',
tooltip: '5x',
icon: '<img width="22" height="22" src="/assets/img/state.svg">',
range: [5, 1, 10, 1],
},
],
});
art.setting.show = true;
art.on('ready', () => {
setTimeout(() => {
// Update the setting by name
art.setting.update({
name: 'slider',
html: 'PIP Mode',
tooltip: 'Close',
icon: '<img width="22" height="22" src="/assets/img/state.svg">',
switch: false,
});
}, 3000);
});
ArtPlayer Documentation
Vue.js Integration
Note: Directly modifying the option object in Vue.js will not update the player.
React.js Integration
Here is a React component implementation for ArtPlayer:
import Artplayer from 'artplayer'
import { useEffect, useRef } from 'react'
export default function Player({ option, getInstance, ...rest }) {
const $container = useRef()
useEffect(() => {
const art = new Artplayer({
...option,
container: $container.current,
})
if (typeof getInstance === 'function') {
getInstance(art)
}
return () => art.destroy(false)
}, [])
return <div ref={$container} {...rest}></div>
}
Example usage in a React application:
import Artplayer from './Artplayer.jsx'
function App() {
return (
<div>
<Artplayer
option={{
url: 'path/to/video.mp4',
}}
style={{
width: '600px',
height: '400px',
margin: '60px auto 0',
}}
getInstance={art => console.log(art)}
/>
</div>
)
}
export default App
Important: Directly modifying the option object in React.js will not update the player.
TypeScript Support
The artplayer.d.ts type definitions are automatically imported when importing Artplayer.
Vue.js with TypeScript:
<script setup>
import Artplayer from 'artplayer';
const art = shallowRef<Artplayer>(null);
art.value = new Artplayer();
</script>
React.js with TypeScript:
import Artplayer from 'artplayer';
const art = useRef<Artplayer>(null);
art.current = new Artplayer();
You can also use the Option type for better type safety:
import Artplayer, { type Option } from 'artplayer';
const option: Option = {
container: '.artplayer-app',
url: './assets/sample/video.mp4',
};
option.volume = 0.5;
const art = new Artplayer(option);
For complete TypeScript definitions, refer to: packages/artplayer/types
JavaScript Type Hints
If your JavaScript files lose TypeScript type hints, you can manually import types using JSDoc comments.
For variables:
/**
* @type {import("artplayer")}
*/
let art = null;
For function parameters:
/**
* @param {import("artplayer")} art
*/
function getInstance(art) {
//
}
For object properties:
export default {
data() {
return {
/**
* @type {import("artplayer")}
*/
art: null,
}
}
}
For option objects:
/**
* @type {import("artplayer/types/option").Option}
*/
const option = {
container: '.artplayer-app',
url: './assets/sample/video.mp4',
};
option.volume = 0.5;
const art8 = new Artplayer(option);
Legacy Browser Support
The standard production build artplayer.js supports only the latest Chrome version. For legacy browser support, use artplayer.legacy.js which supports IE 11 and above.
import Artplayer from 'artplayer/legacy'
CDN URLs for legacy version:
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.legacy.js
https://unpkg.com/artplayer/dist/artplayer.legacy.js
To support even older browsers, modify the build configuration and build it yourself. Refer to scripts/build.js and the browserslist documentation.
ECMAScript Module Support
Starting from version 5.2.6, ArtPlayer provides ESM versions with .mjs extension.
Example HTML using ESM with import maps:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ArtPlayer ESM with Import Map</title>
<style>
#player {
width: 640px;
height: 360px;
margin: 50px auto;
border: 1px solid #ccc;
}
</style>
<script type="importmap">
{
"imports": {
"artplayer": "https://unpkg.com/artplayer/dist/artplayer.esm.js"
}
}
</script>
</head>
<body>
<div id="player"></div>
<script type="module">
import Artplayer from 'artplayer';
const art = new Artplayer({
container: '#player',
url: '/assets/sample/video.mp4',
});
</script>
</body>
</html>
Custom User Agent
To adjust player UI by changing user agent detection, use globalThis.CUSTOM_USER_AGENT (available from version 5.2.4).
<html>
<head>
<title>ArtPlayer Demo</title>
<meta charset="UTF-8" />
<style>
.artplayer-app {
width: 400px;
height: 300px;
}
</style>
</head>
<body>
<div class="artplayer-app"></div>
<script>globalThis.CUSTOM_USER_AGENT = 'iphone'</script>
<script src="path/to/artplayer.js"></script>
<script>
const art = new Artplayer({
container: '.artplayer-app',
url: 'path/to/video.mp4',
});
</script>
</body>
</html>
Important: You must set CUSTOM_USER_AGENT before importing the ArtPlayer dependency.
Language Settings (i18n)
Important: Starting from version 5.1.0, only Simplified Chinese and English are included in the core bundle. Other languages must be imported manually.
When a language cannot be matched, English will be displayed by default.
Default Languages
The default included languages are English (en) and Simplified Chinese (zh-cn).
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lang: 'zh-cn', // or 'en'
});
Importing Additional Languages
Language files are available in artplayer/src/i18n/*.js before bundling and artplayer/dist/i18n/*.js after bundling.
Using import:
import id from 'artplayer/i18n/id';
import zhTw from 'artplayer/i18n/zh-tw';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
i18n: {
id: id,
'zh-tw': zhTw,
},
lang: 'zh-tw',
});
Using script tags:
<script src="artplayer/dist/i18n/id.js"></script>
<script src="artplayer/dist/i18n/zh-tw.js"></script>
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
i18n: {
id: window['artplayer-i18n-id'],
'zh-tw': window['artplayer-i18n-zh-tw'],
},
lang: 'zh-tw',
});
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'
},
},
});
Modifying Existing Languages
import zhTw from 'artplayer/i18n/zh-tw';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
i18n: {
// Change the default language
'zh-cn': {
Play: 'Your Play'
},
// Change the imported language
'zh-tw': {
...zhTw,
Play: 'Your Play'
},
},
});
Basic Options
container Option
Type: String, Element
Default: #artplayer
The DOM container where the player is mounted.
To initialize ArtPlayer, the container option is required. You can specify it using a CSS selector or a DOM element.
var art = new Artplayer({
container: '.artplayer-app',
// container: document.querySelector('.artplayer-app'),
url: '/assets/sample/video.mp4',
});
You may need to set the size of the container element. Here are two common approaches:
Using fixed width and height:
.artplayer-app {
width: 400px;
height: 300px;
}
Or using aspect ratio:
.artplayer-app {
aspect-ratio: 16/9;
}
Note: Among all options, only container is required.
URL Option
Type: String
Default: ''
The video source URL.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
If the URL is not available immediately, you can set it asynchronously:
var art = new Artplayer({
container: '.artplayer-app',
});
setTimeout(() => {
art.url = '/assets/sample/video.mp4';
}, 1000);
Note: By default, three video file formats are supported: .mp4, .ogg, .webm. To play other formats like .m3u8 or .flv, please refer to the Third-party Libraries section.
ID Option
Type: String
Default: ''
The unique identifier for the player, currently used for playback resumption with autoplayback.
var art = new Artplayer({
id: 'your-url-id',
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
onReady Option
Type: Function
Default: undefined
A callback function triggered when the player is successfully initialized and the video is ready to play.
var art = new Artplayer(
{
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
},
function onReady(art) {
this.play()
},
);
This is equivalent to using the ready event:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
art.on('ready', () => {
art.play();
});
Note: Inside the callback function, this refers to the player instance. However, if an arrow function is used, this will not point to the player instance.
Poster Option
Type: String
Default: ''
The video poster image, displayed when the player is initialized but not yet playing.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
poster: '/assets/sample/poster.jpg',
});
Theme Option
Type: String
Default: '#f00'
The player's theme color, used for the progress bar and highlighted elements.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
theme: '#ffad00',
});
Volume Option
Type: Number
Default: 0.7
The default volume of the player.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
volume: 0.5,
});
Note: The player caches the last volume level and will use this cached value upon next initialization.
isLive Option
Type: Boolean
Default: false
Enable live streaming mode, which hides the progress bar and playback time.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
isLive: true,
});
Muted Option
Type: Boolean
Default: false
Whether to mute by default.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
Autoplay Option
Type: Boolean
Default: false
Whether to autoplay.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoplay: true,
muted: true,
});
Note: If you want the video to autoplay immediately upon page load, muted must be set to true. For more information, please read Autoplay Policy Changes.
AutoSize Option
Type: Boolean
Default: false
Automatically adjusts the player size to hide black bars, similar to object-fit: cover in CSS.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoSize: true,
});
AutoMini Option
Type: Boolean
Default: false
Automatically enters mini player mode when the player scrolls out of the browser viewport.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoMini: true,
});
Loop Option
Type: Boolean
Default: false
Whether to enable video looping.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
loop: true,
});
Flip Option
Type: Boolean
Default: false
Whether to display the video flip functionality. Appears in the Settings Panel and Context Menu.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
flip: true,
setting: true,
});
PlaybackRate Option
Type: Boolean
Default: false
Whether to display the video playback rate functionality. Appears in the Settings Panel and Context Menu.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
playbackRate: true,
setting: true,
});
AspectRatio Option
Type: Boolean
Default: false
Whether to display the video aspect ratio functionality. Appears in the Settings Panel and Context Menu.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
aspectRatio: true,
setting: true,
});
Screenshot Option
Type: Boolean
Default: false
Whether to display the Video Screenshot functionality in the bottom control bar.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
screenshot: true,
});
Note: Due to browser security mechanisms, screenshot capture may fail if the video source URL is cross-origin with the website.
Setting Option
Type: Boolean
Default: false
Whether to display the toggle button for the Settings Panel in the bottom control bar.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
});
Hotkey Option
Type: Boolean
Default: true
Whether to enable hotkeys.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
hotkey: true,
});
Hotkeys for ArtPlayer
The following hotkeys are available for controlling the player:
Up arrow: Increase volume
Down arrow: Decrease volume
Left arrow: Seek forward
Right arrow: Seek backward
Spacebar: Toggle play/pause
Note: These hotkeys only take effect after the player gains focus (e.g., by clicking on the player).
Picture-in-Picture Option
Type: Boolean
Default: false
Whether to display the Picture-in-Picture toggle button in the bottom control bar.
Example configuration:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
pip: true,
});
Mutex Option
Type: Boolean
Default: true
If multiple players exist simultaneously on the page, whether only one player is allowed to play at a time.
Example configuration:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
mutex: true,
});
Backdrop Option
Type: Boolean
Default: true
Whether to enable the backdrop blur effect for the player UI. When enabled, overlays such as the settings panel, context menu, and volume bar will apply a backdrop-filter frosted glass effect for a more transparent appearance. However, this may cause performance or compatibility issues on some low-performance devices or older browsers.
Example configuration (disabling the effect):
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
backdrop: false,
});
Fullscreen Option
Type: Boolean
Default: false
Whether to display the player Window Fullscreen button in the bottom control bar.
Example configuration:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreen: true,
});
Fullscreen Web Option
Type: Boolean
Default: false
Whether to display the player Webpage Fullscreen button in the bottom control bar.
Example configuration:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreenWeb: true,
});
Subtitle Offset Option
Type: Boolean
Default: false
Subtitle timing offset, range within [-5s, 5s]. Appears in the Settings Panel.
Example configuration:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitleOffset: true,
subtitle: {
url: '/assets/sample/subtitle.srt',
},
setting: true,
});
Mini Progress Bar Option
Type: Boolean
Default: false
Mini progress bar that appears only when the player loses focus and is playing.
Example configuration:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
miniProgressBar: true,
});
Use SSR Option
Type: Boolean
Default: false
Whether to use SSR mount mode. Useful if you want to pre-render the player's required HTML before mounting.
You can access the player's required HTML via Artplayer.html.
Example configuration:
var $container = document.querySelector('.artplayer-app');
$container.innerHTML = Artplayer.html;
var art = new Artplayer({
container: $container,
url: '/assets/sample/video.mp4',
useSSR: true,
});
Plays Inline Option
Type: Boolean
Default: true
Whether to use playsInline mode on mobile devices.
Example configuration:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
playsInline: true,
});
Layers Option
Type: Array
Default: []
Initialize custom layers.
Example configuration:
var img = '/assets/sample/layer.png';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
layers: [
{
name: 'potser',
html: `<img style="width: 100px" src="${img}">`,
style: {
position: 'absolute',
top: '20px',
right: '20px',
opacity: '.9',
},
click: function (...args) {
console.info('click', args);
art.layers.show = false;
},
mounted: function (...args) {
console.info('mounted', args);
},
},
],
});
For Component Configuration, please refer to: /component/layers.html
Settings Option
Type: Array
Default: []
Initialize custom settings panel.
Example configuration:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
settings: [
{
html: 'setting01',
selector: [
{
html: 'setting01-01',
},
{
html: 'setting01-02',
},
],
onSelect: function (...args) {
console.info(args);
},
},
{
html: 'setting02',
selector: [
{
html: 'setting02-01',
},
{
html: 'setting02-02',
},
],
onSelect: function (...args) {
console.info(args);
},
},
],
});
For Settings Panel configuration, please refer to: /component/setting.html
Context Menu Option
Type: Array
Default: []
Initialize custom context menu.
Example configuration:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
contextmenu: [
{
html: 'your-menu',
click: function (...args) {
console.info('click', args);
art.contextmenu.show = false;
},
},
],
});
For Component Configuration, please refer to: /component/contextmenu.html
Controls Option
Type: Array
Default: []
Initialize custom bottom control bar.
Example configuration:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
position: 'left',
html: 'your-control',
tooltip: 'Your Control',
style: {
color: 'green',
},
click: function (...args) {
console.info('click', args);
},
},
],
});
For Component Configuration, please refer to: /component/controls.html
Quality Option
Type: Array
Default: []
Whether to display the Quality Selection list in the bottom control bar.
Quality option properties:
Property: default, Type: Boolean, Description: Default quality
Property: html, Type: String, Description: Quality name
Property: url, Type: String, Description: Quality URL
Example configuration:
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',
},
],
});
Highlight Option
Type: Array
Default: []
Display Highlight Information on the progress bar.
Here is the reorganized documentation for the ArtPlayer AI model:
HIGHLIGHT
Property: time
Type: Number
Description: Highlight time (in seconds)
Property: text
Type: String
Description: Highlight text
Example configuration showing how to set up video highlights at specific timestamps:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
highlight: [
{
time: 60,
text: 'One more chance',
},
{
time: 120,
text: '谁でもいいはずなのに',
},
{
time: 180,
text: '夏の想い出がまわる',
},
{
time: 240,
text: 'こんなとこにあるはずもないのに',
},
{
time: 300,
text: '--终わり--',
},
],
});
PLUGINS
Type: Array
Default: []
Initialize custom plugins. Plugins allow you to extend ArtPlayer functionality with custom features.
Example of creating and using a custom plugin:
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],
});
THUMBNAILS
Type: Object
Default: {}
Set preview thumbnails on the progress bar.
Property: url
Type: String
Description: Thumbnail image URL
Property: number
Type: Number
Description: Number of thumbnails
Property: column
Type: Number
Description: Number of thumbnail columns
Property: width
Type: Number
Description: Thumbnail width
Property: height
Type: Number
Description: Thumbnail height
Property: scale
Type: Number
Description: Thumbnail scale
Example configuration for setting up thumbnails:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
thumbnails: {
url: '/assets/sample/thumbnails.png',
number: 60,
column: 10,
},
});
Note: You can generate thumbnails online using artplayer-tool-thumbnail.
SUBTITLE
Type: Object
Default: {}
Set the video subtitle. Supported subtitle formats: vtt, srt, ass.
Property: name
Type: String
Description: Subtitle name
Property: url
Type: String
Description: Subtitle URL
Property: type
Type: String
Description: Subtitle type, options: vtt, srt, ass
Property: style
Type: Object
Description: Subtitle style
Property: encoding
Type: String
Description: Subtitle encoding, default: utf-8
Property: escape
Type: Boolean
Description: Whether to escape html tags, default: true
Property: onVttLoad
Type: Function
Description: Function for modifying vtt text
Example configuration for setting up subtitles with custom styling:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitle: {
url: '/assets/sample/subtitle.srt',
type: 'srt',
encoding: 'utf-8',
escape: true,
style: {
color: '#03A9F4',
'font-size': '30px',
},
},
});
MORE VIDEO ATTR
Type: Object
Default: {'controls': false, 'preload': 'metadata'} (In Safari, it automatically adjusts to preload: 'auto' for better loading experience)
More video attributes. These attributes will be directly written into the video element.
Example showing how to set inline playback attributes:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
moreVideoAttr: {
'webkit-playsinline': true,
playsInline: true,
},
});
ICONS
Type: Object
Default: {}
Used to replace default icons, supports both Html strings and HTMLElement.
Example showing how to customize loading and state icons:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
icons: {
loading: '<img src="/assets/img/ploading.gif">',
state: '<img src="/assets/img/state.png">',
},
});
Note: See artplayer/types/icons.d.ts for all available icon definitions.
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 showing how to explicitly specify the video type:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.m3u8',
type: 'm3u8',
});
Note: The player can only parse suffixes like /assets/sample/video.m3u8 but cannot parse suffixes like /assets/sample/video?type=m3u8. Therefore, 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
- art: The current instance
Example showing how to set up custom type handling:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.m3u8',
customType: {
m3u8: function (video, url, art) {
//
},
},
});
LANG
Type: String
Default: navigator.language.toLowerCase()
The default display language. Currently supported: en, zh-cn.
Example showing how to set the language to English:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lang: 'en',
});
Note: See /start/i18n.html for more language settings.
I18N
Type: Object
Default: {}
Custom i18n configuration. This configuration will be deeply merged with the built-in i18n.
Example showing how to add 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 showing how to modify existing languages:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
i18n: {
'zh-cn': {
Play: 'Your Play'
},
'zh-tw': {
Play: 'Your Play'
},
},
});
Note: See /start/i18n.html for more language settings.
LOCK
Type: Boolean
Default: false
Whether to display a lock button on mobile devices to hide the bottom control bar.
Example showing how to enable 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 showing how to disable 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 showing how to enable fast forward:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fastForward: true,
});
To use ArtPlayer, initialize it with a container and video URL. Here is a basic example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fastForward: true,
});
autoPlayback
Type: Boolean
Default: false
This option enables 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 url as the key to cache playback progress. If the same video has different URLs, use the id to set a unique key for accurate progress tracking.
autoOrientation
Type: Boolean
Default: false
When enabled, this rotates the player during fullscreen mode on mobile devices based on video dimensions and viewport size.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoOrientation: true,
});
airplay
Type: Boolean
Default: false
This option shows the AirPlay button, but note that it is only supported in some browsers.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
airplay: true,
});
cssVar
Type: Object
Default: {}
Use this to modify built-in CSS variables for customizing the player's appearance.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
cssVar: {
//
},
});
For a list of available CSS variables, refer to: artplayer/types/cssVar.d.ts
proxy
Type: function
Default: undefined
This function can return a third-party HTMLCanvasElement or HTMLVideoElement, such as proxying an existing video DOM element.
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 handles advertising functionality within ArtPlayer.
The Option interface defines ad configuration:
interface Option {
/**
* 广告源文本,支持视频链接、图片链接、HTML文本
*/
source: string
/**
* 知名广告的类型:'video' | 'image' | 'html'
*/
type: 'video' | 'image' | 'html'
/**
* 广告必看的时长,单位为秒
*/
playDuration?: number
/**
* 广告总的时长,单位为秒
*/
totalDuration?: number
/**
* 视频广告是否默认静音
*/
muted?: boolean
}
The Ads interface provides ad control methods:
interface Ads {
name: 'artplayerPluginAds'
/**
* 跳过广告
*/
skip: () => void
/**
* 暂停广告
*/
pause: () => void
/**
* 播放广告
*/
play: () => void
}
Plugin declaration:
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 ambient lighting effects around the video player.
Configuration options for the ambilight effect:
interface Option {
blur?: string
opacity?: number
frequency?: number
zIndex?: number
duration?: number
}
Result interface with control methods:
interface Result {
name: 'artplayerPluginAmbilight'
start: () => void
stop: () => void
}
Plugin declaration:
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.
AudioChunk interface for audio data:
interface AudioChunk {
pcm: ArrayBuffer
wav: ArrayBuffer
}
ASR plugin configuration options:
interface AsrPluginOption {
length?: number
interval?: number
sampleRate?: number
autoHideTimeout?: number
onAudioChunk?: (chunk: AudioChunk) => void | Promise<void>
}
ASR plugin instance with control methods:
interface AsrPluginInstance {
name: 'artplayerPluginAsr'
stop: () => void
hide: () => void
append: (subtitle: string) => void
}
Plugin declaration:
declare function artplayerPluginAsr(option?: AsrPluginOption): (art: Artplayer) => AsrPluginInstance
export default artplayerPluginAsr
export = artplayerPluginAsr
export as namespace artplayerPluginAsr;
artplayer-plugin-auto-thumbnail.d.ts
This plugin automatically generates video thumbnails.
Configuration options for thumbnail generation:
interface Option {
url?: string
width?: number
number?: number
scale?: number
}
Result interface:
interface Result {
name: 'artplayerPluginAutoThumbnail'
}
Plugin declaration:
declare const artplayerPluginAutoThumbnail: (option: Option) => (art: Artplayer) => Result
export default artplayerPluginAutoThumbnail
export = artplayerPluginAutoThumbnail
export as namespace artplayerPluginAutoThumbnail;
artplayer-plugin-chapter.d.ts
This plugin provides chapter navigation for videos.
Chapters type definition:
type Chapters = {
start: number
end: number
title: string
}[]
Chapter plugin configuration:
interface Option {
chapters?: Chapters
}
Result interface with update method:
interface Result {
name: 'artplayerPluginChapter'
update: (option: Option) => void
}
Plugin declaration:
declare const artplayerPluginChapter: (option: Option) => (art: Artplayer) => Result
export default artplayerPluginChapter
export = artplayerPluginChapter
export as namespace artplayerPluginChapter;
artplayer-plugin-chromecast.d.ts
This plugin enables Chromecast functionality.
Chromecast configuration options:
interface Option {
url?: string
sdk?: string
icon?: string
mimeType?: string
}
Chromecast interface:
interface Chromecast {
name: 'artplayerPluginChromecast'
}
Plugin declaration:
declare const artplayerPluginChromecast: (option: Option) => (art: Artplayer) => Chromecast
export default artplayerPluginChromecast
export = artplayerPluginChromecast
export as namespace artplayerPluginChromecast;
artplayer-plugin-danmuku-mask.d.ts
This plugin provides masking functionality for danmaku (bullet comments).
Configuration options for danmaku masking:
interface Option {
solutionPath?: string
modelSelection?: number
smoothSegmentation?: boolean
minDetectionConfidence?: number
minTrackingConfidence?: number
selfieMode?: boolean
drawContour?: boolean
foregroundThreshold?: number
opacity?: number
maskBlurAmount?: number
}
Result interface with async control methods:
interface Result {
name: 'artplayerPluginDanmukuMask'
start: () => Promise<void>
stop: () => void
}
Plugin declaration:
declare const artplayerPluginDanmukuMask: (option?: Option) => (art: Artplayer) => Result
export default artplayerPluginDanmukuMask
export = artplayerPluginDanmukuMask
export as namespace artplayerPluginDanmukuMask;
artplayer-plugin-danmuku.d.ts
This plugin provides comprehensive danmaku (bullet comment) functionality.
Type definitions for danmaku modes and data:
export type Mode = 0 | 1 | 2
export type Danmuku
= | Danmu[]
| string // URL
| (() => Promise<Danmu[]>)
| Promise<Danmu[]>
Slider configuration interface:
export interface Slider {
min?: number
max?: number
steps?: {
name?: string
value?: number | string
show?: boolean
}[]
}
Individual danmaku item definition:
export interface Danmu {
/**
* 弹幕文本
*/
text: string
/**
* 弹幕发送模式: 0: 滚动,1: 顶部,2: 底部
*/
mode?: Mode
/**
* 弹幕颜色
*/
color?: string
/**
* 弹幕出现的时间,单位为秒
*/
time?: number
/**
* 弹幕是否有描边, 默认为 false
*/
border?: boolean
/**
* 弹幕自定义样式
*/
style?: Partial<CSSStyleDeclaration>
}
Comprehensive danmaku configuration options:
export interface Option {
/**
* 弹幕数据: 函数,数组,Promise,URL
*/
danmuku: Danmuku
/**
* 弹幕持续时间,范围在[1 ~ 10]
*/
speed?: number
/**
* 弹幕上下边距,支持像素数字和百分比
*/
margin?: [number | `${number}%`, number | `${number}%`]
/**
* 弹幕透明度,范围在[0 ~ 1]
*/
opacity?: number
/**
* 默认弹幕颜色,可以被单独弹幕项覆盖
*/
color?: string
/**
* 弹幕模式: 0: 滚动,1: 顶部,2: 底部
*/
mode?: Mode
/**
* 弹幕可见的模式
*/
modes?: Mode[]
/**
* 弹幕字体大小,支持像素数字和百分比
*/
fontSize?: number | `${number}%`
/**
* 弹幕是否防重叠
*/
antiOverlap?: boolean
/**
* 是否同步播放速度
*/
synchronousPlayback?: boolean
/**
* 弹幕发射器挂载点, 默认为播放器控制栏中部
*/
mount?: HTMLDivElement | string
/**
* 是否开启弹幕热度图
*/
heatmap?:
| boolean
| {
xMin?: number
xMax?: number
yMin?: number
yMax?: number
scale?: number
opacity?: number
minHeight?: number
sampling?: number
smoothing?: number
flattening?: number
}
/**
* 当播放器宽度小于此值时,弹幕发射器置于播放器底部
*/
width?: number
/**
* 热力图数据
*/
points?: { time: number, value: number }[]
/**
* 弹幕载入前的过滤器,只支持返回布尔值
*/
filter?: (danmu: Danmu) => boolean
/**
* 弹幕发送前的过滤器,支持返回 Promise
*/
beforeEmit?: (danmu: Danmu) => boolean | Promise<boolean>
/**
* 弹幕显示前的过滤器,支持返回 Promise
*/
beforeVisible?: (danmu: Danmu) => boolean | Promise<boolean>
/**
* 弹幕是否可见
*/
visible?: boolean
/**
* 是否开启弹幕发射器
*/
emitter?: boolean
/**
* 弹幕输入框最大长度, 范围在[1 ~ 1000]
*/
maxLength?: number
/**
* 输入框锁定时间,范围在[1 ~ 60]
*/
lockTime?: number
/**
* 弹幕主题,只在自定义挂载时生效
*/
theme?: 'light' | 'dark'
/**
* 不透明度配置项
*/
OPACITY?: Slider
/**
* 弹幕速度配置项
*/
SPEED?: Slider
/**
* 显示区域配置项
*/
MARGIN?: Slider
/**
* 弹幕字号配置项
*/
FONT_SIZE?: Slider
/**
* 颜色列表配置项
*/
COLOR?: string[]
}
Danmaku plugin result with extensive control methods:
export interface Result {
name: 'artplayerPluginDanmuku'
/**
* 发送一条实时弹幕
*/
emit: (danmu: Danmu) => Result
/**
* 重载弹幕源,或者切换新弹幕
*/
load: (danmuku?: Danmuku) => Promise<Result>
/**
* 实时改变弹幕配置
*/
config: (option: Option) => Result
/**
* 隐藏弹幕层
*/
hide: () => Result
/**
* 显示弹幕层
*/
show: () => Result
/**
* 挂载弹幕输入框
*/
mount: (el?: HTMLDivElement | string) => void
/**
* 重置弹幕
*/
reset: () => Result
/**
* 弹幕配置
*/
option: Option
/**
* 是否隐藏弹幕层
*/
isHide: boolean
/**
* 是否弹幕层停止状态
*/
isStop: boolean
}
Plugin declaration:
declare const artplayerPluginDanmuku: (option: Option) => (art: Artplayer) => Result
export default artplayerPluginDanmuku
export = artplayerPluginDanmuku
export as namespace artplayerPluginDanmuku;
artplayer-plugin-dash-control.d.ts
This plugin provides DASH streaming quality and audio control.
Configuration interface for DASH controls:
interface Config {
control?: boolean
setting?: boolean
title?: string
auto?: string
getName?: (level: object) => string
}
Plugin declaration with quality and audio configuration:
declare const artplayerPluginDashControl: (option: { quality?: Config, audio?: Config }) => (art: Artplayer) => {
name: 'artplayerPluginDashControl'
update: () => void
}
export default artplayerPluginDashControl
export = artplayerPluginDashControl
export as namespace artplayerPluginDashControl;
artplayer-plugin-document-pip.d.ts
This plugin enables Document Picture-in-Picture (PiP) functionality.
Document PiP configuration options:
interface Option {
width?: number
height?: number
placeholder?: string
fallbackToVideoPiP?: boolean
}
Result interface with PiP control methods and status properties:
interface Result {
name: 'artplayerPluginDocumentPip'
isSupported: boolean
isActive: boolean
open: () => void
close: () => void
toggle: () => void
}
ARTPLAYER TYPE DECLARATION FILES ANALYSIS
===== artplayer-plugin-document-pip.d.ts =====
// Plugin for document-level Picture-in-Picture functionality
declare const artplayerPluginDocumentPip: (option: Option) => (art: Artplayer) => Result
export default artplayerPluginDocumentPip
export = artplayerPluginDocumentPip
export as namespace artplayerPluginDocumentPip;
===== artplayer-plugin-hls-control.d.ts =====
// Configuration interface for HLS quality and audio controls
interface Config {
control?: boolean // Enable control element
setting?: boolean // Enable settings menu
title?: string // Display title
auto?: string // Auto selection label
getName?: (level: object) => string // Custom name formatter for quality levels
}
// HLS quality and audio control plugin
declare const artplayerPluginHlsControl: (option: { quality?: Config, audio?: Config }) => (art: Artplayer) => {
name: 'artplayerPluginHlsControl'
update: () => void // Method to update control states
}
export default artplayerPluginHlsControl
export = artplayerPluginHlsControl
export as namespace artplayerPluginHlsControl;
===== artplayer-plugin-iframe.d.ts =====
// Message structure for iframe communication
interface Message {
type: string // Message type identifier
data: any // Message payload
id?: number // Optional message ID for request-response pattern
}
// Iframe communication plugin for cross-origin player control
declare class ArtplayerPluginIframe {
constructor(option: { iframe: HTMLIFrameElement, url: string })
// Static properties and methods
static iframe: boolean
static postMessage(message: Message): void
static onMessage(event: MessageEvent & { data: Message }): void
static inject(): void
// Instance properties
readonly promises: Record<number, { resove: (...args: any[]) => any, reject: (...args: any[]) => any }>
readonly injected: boolean // Whether iframe script is injected
readonly destroyed: boolean // Whether instance is destroyed
readonly $iframe: HTMLIFrameElement
readonly url: string
readonly messageCallback: (...args: any[]) => any
// Instance methods
onMessage(event: MessageEvent & { data: Message }): void
postMessage(message: Message): Promise<any> // Send message and await response
commit<T extends (...args: any[]) => any>(callback: T): Promise<ReturnType<T>> // Execute function in iframe context
message(callback: (...args: any[]) => any): void // Set message handler
destroy(): void // Cleanup resources
}
export default ArtplayerPluginIframe
export = artplayerPluginIframe
export as namespace artplayerPluginIframe;
===== artplayer-plugin-libass.d.ts =====
// ASS subtitle rendering plugin using libass
declare const artplayerPluginAss: (options: Options) => (art: Artplayer) => {
name: 'artplayerPluginLibass'
libass: SubtitlesOctopus // Underlying libass instance
visible: boolean // Subtitle visibility state
init: () => void // Initialize subtitle renderer
switch: (url: string) => void // Switch to different subtitle file
show: () => void // Show subtitles
hide: () => void // Hide subtitles
destroy: () => void // Cleanup resources
}
export default artplayerPluginAss
export = artplayerPluginLibass
export as namespace artplayerPluginLibass;
===== artplayer-plugin-multiple-subtitles.d.ts =====
// Plugin for managing multiple subtitle tracks
declare const artplayerPluginMultipleSubtitles: (option: {
subtitles: {
url?: string // Subtitle file URL
name?: string // Display name
type?: 'vtt' | 'srt' | 'ass' // Subtitle format
encoding?: string // Text encoding (default: utf-8)
onParser?: (...args: object[]) => object // Custom parser function
}[]
}) => (art: Artplayer) => {
name: 'multipleSubtitles'
}
export default artplayerPluginMultipleSubtitles
export = artplayerPluginMultipleSubtitles
export as namespace artplayerPluginMultipleSubtitles;
===== artplayer-plugin-vast.d.ts =====
// VAST (Video Ad Serving Template) plugin for IMA (Interactive Media Ads)
declare global {
interface Window {
artplayerPluginVast?: typeof artplayerPluginVast
}
}
// Function types for ad playback control
type PlayUrlFn = (url: string) => void
type PlayResFn = (res: string) => void
// VAST plugin execution context
interface VastPluginContext {
art: Artplayer // Artplayer instance
ima: any // Google IMA instance (type any due to external dependency)
imaPlayer: Player // IMA player instance
playUrl: PlayUrlFn // Function to play ad by URL
playRes: PlayResFn // Function to play ad by response
container: HTMLDivElement | null // Ad container element
}
// VAST plugin option function type
export type ArtplayerPluginVastOption = (params: VastPluginContext) => void | Promise<void>
// VAST plugin instance interface
export interface ArtplayerPluginVastInstance {
name: 'artplayerPluginVast'
destroy?: () => void // Optional cleanup method
}
// VAST plugin main function
declare function artplayerPluginVast(
option: ArtplayerPluginVastOption,
): (art: Artplayer) => ArtplayerPluginVastInstance
export default artplayerPluginVast
export = artplayerPluginVast
export as namespace artplayerPluginVast;
===== artplayer-plugin-vtt-thumbnail.d.ts =====
// VTT-based thumbnail preview plugin for seek bar
declare const artplayerPluginVttThumbnail: (option: { vtt?: string, style?: Partial<CSSStyleDeclaration> }) => (
art: Artplayer,
) => {
name: 'artplayerPluginVttThumbnail'
}
export default artplayerPluginVttThumbnail
export = artplayerPluginVttThumbnail
export as namespace artplayerPluginVttThumbnail;
===== artplayer.d.ts =====
// Core Artplayer utility functions
export interface Utils {
// User agent detection
userAgent: string
isMobile: boolean
isSafari: boolean
isIOS: boolean
isIOS13: boolean
// DOM manipulation utilities
query: (selector: string, parent?: HTMLElement) => HTMLElement
queryAll: (selector: string, parent?: HTMLElement) => HTMLElement[]
addClass: (target: HTMLElement, className: string) => void
removeClass: (target: HTMLElement, className: string) => void
hasClass: (target: HTMLElement, className: string) => boolean
append: (target: HTMLElement, child: HTMLElement) => HTMLElement
remove: (target: HTMLElement) => void
replaceElement: (newChild: HTMLElement, oldChild: HTMLElement) => HTMLElement
siblings: (target: HTMLElement) => HTMLElement[]
inverseClass: (target: HTMLElement, className: string) => void
createElement: <K extends keyof HTMLElementTagNameMap>(tag: K) => HTMLElementTagNameMap[K]
setStyle: <T extends keyof CSSStyleDeclaration>(
element: HTMLElement,
key: T,
value: CSSStyleDeclaration[T],
) => HTMLElement
setStyles: (element: HTMLElement, styles: Partial<CSSStyleDeclaration>) => HTMLElement
getStyle: <K extends keyof CSSStyleDeclaration>(
element: HTMLElement,
key: K,
numberType?: boolean,
) => boolean extends true ? number : string
setStyleText: (element: HTMLElement, text: string) => void
getRect: (el: HTMLElement) => { top: number, left: number, width: number, height: number }
tooltip: (target: HTMLElement, msg: string, pos?: string) => void
isInViewport: (target: HTMLElement, offset?: number) => boolean
includeFromEvent: (event: Event, target: HTMLElement) => boolean
// Subtitle format conversion utilities
srtToVtt: (srtText: string) => string
vttToBlob: (vttText: string) => string
assToVtt: (assText: string) => string
// File and network utilities
getExt: (url: string) => string
download: (url: string, name: string) => void
loadImg: (url: string, scale?: number) => Promise<HTMLImageElement>
// Error handling and object utilities
errorHandle: <T extends boolean>(condition: T, msg: string) => T extends true ? T : never
def: (obj: object, name: string, value: unknown) => void
has: (obj: object, name: PropertyKey) => boolean
get: (obj: object, name: PropertyKey) => PropertyDescriptor | undefined
mergeDeep: <T extends object[]>(...args: T) => T[number]
// Timing and performance utilities
sleep: (ms: number) => Promise<void>
debounce: <F extends (...args: any[]) => any>(func: F, wait: number, context?: object) => (...args: Parameters<F>) => ReturnType<F>
throttle: <F extends (...args: any[]) => any>(func: F, wait: number) => (...args: Parameters<F>) => ReturnType<F>
// Math and string utilities
clamp: (num: number, a: number, b: number) => number
secondToTime: (second: number) => string
escape: (str: string) => string
capitalize: (str: string) => string
// UI utilities
getIcon: (key: string, html: string | HTMLElement) => HTMLElement
supportsFlex: () => boolean
}
// Player template structure - references to DOM elements
export interface Template {
readonly $container: HTMLDivElement
readonly $player: HTMLDivElement
readonly $video: HTMLVideoElement
readonly $track: HTMLTrackElement
readonly $poster: HTMLDivElement
readonly $subtitle: HTMLDivElement
readonly $danmuku: HTMLDivElement
readonly $bottom: HTMLDivElement
readonly $progress: HTMLDivElement
readonly $controls: HTMLDivElement
readonly $controlsLeft: HTMLDivElement
readonly $controlsRight: HTMLDivElement
readonly $layer: HTMLDivElement
readonly $loading: HTMLDivElement
readonly $notice: HTMLDivElement
readonly $noticeInner: HTMLDivElement
readonly $mask: HTMLDivElement
readonly $state: HTMLDivElement
readonly $setting: HTMLDivElement
readonly $info: HTMLDivElement
readonly $infoPanel: HTMLDivElement
readonly $infoClose: HTMLDivElement
readonly $contextmenu: HTMLDivElement
readonly $mini: HTMLDivElement
}
// Subtitle configuration interface
export interface Subtitle {
/**
* The subtitle url
*/
url?: string
/**
* The subtitle name
*/
name?: string
/**
* The subtitle type
*/
type?: 'vtt' | 'srt' | 'ass' | (string & Record<never, never>)
/**
* The subtitle style object
*/
style?: Partial<CSSStyleDeclaration>
/**
* The subtitle encoding, default utf-8
*/
encoding?: string
Here are the TypeScript declaration files for ArtPlayer's API, presented as plain text with explanatory notes where helpful.
The SettingOption type combines base properties with additional ones from the Setting type, excluding 'html', 'icon', and 'tooltip' which are redefined.
type Props<T> = {
html: string
icon: string
tooltip: string
$item: HTMLDivElement
$icon: HTMLDivElement
$html: HTMLDivElement
$tooltip: HTMLDivElement
$switch: HTMLDivElement
$range: HTMLInputElement
$parent: Setting
$parents: Setting[]
$option: Setting[]
$events: Array<(...args: unknown[]) => unknown>
$formatted: boolean
} & Omit<T, 'html' | 'icon' | 'tooltip'>
export type SettingOption = Props<Setting>
The Setting interface defines the structure for customizable player settings, including display elements and interaction handlers.
export interface Setting {
/**
* Html string or html element of setting name
*/
html: string | HTMLElement
/**
* Html string or html element of setting icon
*/
icon?: string | HTMLElement
/**
* The width of setting
*/
width?: number
/**
* The tooltip of setting
*/
tooltip?: string | HTMLElement
/**
* Whether the default is selected
*/
default?: boolean
/**
* Custom selector list
*/
selector?: Setting[]
/**
* When the setting was mounted
*/
mounted?: (this: Artplayer, panel: HTMLDivElement, item: Setting) => void
/**
* When selector item click
*/
onSelect?: (this: Artplayer, item: SettingOption, element: HTMLDivElement, event: Event) => void
/**
* Custom switch item
*/
switch?: boolean
/**
* When switch item click
*/
onSwitch?: (this: Artplayer, item: SettingOption, element: HTMLDivElement, event: Event) => void
/**
* Custom range item
*/
range?: [value?: number, min?: number, max?: number, step?: number]
/**
* When range item change
*/
onRange?: (this: Artplayer, item: SettingOption, element: HTMLDivElement, event: Event) => void
/**
* When range item change in real time
*/
onChange?: (this: Artplayer, item: SettingOption, element: HTMLDivElement, event: Event) => void
/**
* When range item change in real time
*/
onClick?: (this: Artplayer, item: SettingOption, element: HTMLDivElement, event: Event) => void
/**
* Allow custom properties
*/
[key: string]: any
}
The Quality interface defines video quality options with display and URL properties.
export interface Quality {
/**
* Whether the default is selected
*/
default?: boolean
/**
* Html string of quality
*/
html: string | HTMLElement
/**
* Video quality url
*/
url: string
}
These type definitions represent various player states and configurations with both predefined and custom values.
export type AspectRatio = 'default' | '4:3' | '16:9' | (`${number}:${number}` & Record<never, never>)
export type PlaybackRate = 0.5 | 0.75 | 1.0 | 1.25 | 1.5 | 1.75 | 2.0 | (number & Record<never, never>)
export type Flip = 'normal' | 'horizontal' | 'vertical' | (string & Record<never, never>)
export type State = 'standard' | 'mini' | 'pip' | 'fullscreen' | 'fullscreenWeb'
The Player class provides the main API for controlling video playback, managing player state, and accessing media properties.
export declare class Player {
get aspectRatio(): AspectRatio
set aspectRatio(ratio: AspectRatio)
get state(): State
set state(state: State)
get type(): CustomType
set type(name: CustomType)
get playbackRate(): PlaybackRate
set playbackRate(rate: PlaybackRate)
get currentTime(): number
set currentTime(time: number)
get duration(): number
get played(): number
get playing(): boolean
get flip(): Flip
set flip(state: Flip)
get fullscreen(): boolean
set fullscreen(state: boolean)
get fullscreenWeb(): boolean
set fullscreenWeb(state: boolean)
get loaded(): number
get loadedTime(): number
get mini(): boolean
set mini(state: boolean)
get pip(): boolean
set pip(state: boolean)
get poster(): string
set poster(url: string)
get rect(): DOMRect
get bottom(): number
get height(): number
get left(): number
get right(): number
get top(): number
get width(): number
get x(): number
get y(): number
set seek(time: number)
get seek(): number
set forward(time: number)
get forward(): number
set backward(time: number)
get backward(): number
get url(): string
set url(url: string)
get volume(): number
set volume(percentage: number)
get muted(): boolean
set muted(state: boolean)
get title(): string
set title(title: string)
get theme(): string
set theme(theme: string)
get subtitleOffset(): number
set subtitleOffset(time: number)
get switch(): string
set switch(url: string)
get quality(): Quality[]
set quality(quality: Quality[])
get thumbnails(): Thumbnails
set thumbnails(thumbnails: Thumbnails)
pause(): void
play(): Promise<void>
toggle(): void
attr(key: string, value?: unknown): unknown
cssVar<T extends keyof CssVar>(key: T, value?: CssVar[T]): CssVar[T]
switchUrl(url: string): Promise<void>
switchQuality(url: string): Promise<void>
getDataURL(): Promise<string>
getBlobUrl(): Promise<string>
screenshot(name?: string): Promise<string>
airplay(): void
autoSize(): void
autoHeight(): void
}
CustomType defines supported video formats with extensibility for custom types.
export type CustomType
= | 'flv'
| 'm3u8'
| 'hls'
| 'ts'
| 'mpd'
| 'torrent'
| (string & Record<never, never>)
The Thumbnails interface configures video thumbnail previews for seeking.
export interface Thumbnails {
/**
* The thumbnail image url
*/
url: string
/**
* The thumbnail item number
*/
number?: number
/**
* The thumbnail column size
*/
column?: number
/**
* The thumbnail width
*/
width?: number
/**
* The thumbnail height
*/
height?: number
/**
* The thumbnail scale
*/
scale?: number
}
The Option interface defines the complete configuration for initializing an ArtPlayer instance.
export interface Option {
/**
* The player id
*/
id?: string
/**
* The container mounted by the player
*/
container: string | HTMLDivElement
/**
* Video url
*/
url: string
/**
* Video poster image url
*/
poster?: string
/**
* Video url type
*/
type?: CustomType
/**
* Player color theme
*/
theme?: string
/**
* Player language
*/
lang?: keyof I18n
/**
* Player default volume
*/
volume?: number
/**
* Whether live broadcast mode
*/
isLive?: boolean
/**
* Whether video muted
*/
muted?: boolean
/**
* Whether video auto play
*/
autoplay?: boolean
/**
* Whether player auto resize
*/
autoSize?: boolean
/**
* Whether player auto run mini mode
*/
autoMini?: boolean
/**
* Whether video auto loop
*/
loop?: boolean
/**
* Whether show video flip button
*/
flip?: boolean
/**
* Whether show video playback rate button
*/
playbackRate?: boolean
/**
* Whether show video aspect ratio button
*/
aspectRatio?: boolean
/**
* Whether show video screenshot button
*/
screenshot?: boolean
/**
* Whether show video setting button
*/
setting?: boolean
/**
* Whether to enable player hotkey
*/
hotkey?: boolean
/**
* Whether show video pip button
*/
pip?: boolean
/**
* Do you want to run only one player at a time
*/
mutex?: boolean
/**
* Whether use backdrop in UI
*/
backdrop?: boolean
/**
* Whether show video window fullscreen button
*/
fullscreen?: boolean
/**
* Whether show video web fullscreen button
*/
fullscreenWeb?: boolean
/**
* Whether to enable player subtitle offset
*/
subtitleOffset?: boolean
/**
* Whether to enable player mini progress bar
*/
miniProgressBar?: boolean
/**
* Whether use SSR function
*/
useSSR?: boolean
/**
* Whether use playsInline in mobile
*/
playsInline?: boolean
/**
* Whether use lock in mobile
*/
lock?: boolean
/**
* Whether use gesture in mobile
*/
gesture?: boolean
/**
* Whether use fast forward in mobile
*/
fastForward?: boolean
/**
* Whether use auto playback
*/
autoPlayback?: boolean
/**
* Whether use auto orientation in mobile
*/
autoOrientation?: boolean
/**
* Whether use airplay
*/
airplay?: boolean
/**
* Custom video proxy
*/
proxy?: (this: Artplayer, art: Artplayer) => HTMLCanvasElement | HTMLVideoElement
/**
* Custom plugin list
*/
plugins?: ((this: Artplayer, art: Artplayer) => unknown)[]
}
Here are the TypeScript declaration files for ArtPlayer's API, presented as plain text with explanatory notes where helpful.
CUSTOMIZATION OPTIONS
These properties allow you to customize various aspects of the ArtPlayer interface and functionality.
/**
* Custom layer list
*/
layers?: ComponentOption[]
/**
* Custom contextmenu list
*/
contextmenu?: ComponentOption[]
/**
* Custom control list
*/
controls?: ComponentOption[]
/**
* Custom setting list
*/
settings?: Setting[]
/**
* Custom video quality list
*/
quality?: Quality[]
/**
* Custom highlight list
*/
highlight?: {
/**
* The highlight time
*/
time: number
/**
* The highlight text
*/
text: string
}[]
/**
* Custom thumbnail
*/
thumbnails?: Thumbnails
/**
* Custom subtitle option
*/
subtitle?: Subtitle
/**
* Other video attribute
*/
moreVideoAttr?: Partial<Readonly<{
[K in keyof HTMLVideoElement as HTMLVideoElement[K] extends (...args: unknown[]) => unknown
? never
: K]: HTMLVideoElement[K]
}>>
Note: moreVideoAttr allows setting additional HTML video element attributes while excluding methods.
/**
* Custom i18n
*/
i18n?: I18n
/**
* Custom default icons
*/
icons?: {
[key in keyof Icons]?: HTMLElement | string
}
/**
* Custom css variables
*/
cssVar?: Partial<CssVar>
/**
* Custom video type function
*/
customType?: Partial<
Record<
CustomType,
(this: Artplayer, video: HTMLVideoElement, url: string, art: Artplayer) => unknown
>
>
ICONS INTERFACE
Defines all available icons in ArtPlayer as HTMLDivElements.
export interface Icons {
readonly loading: HTMLDivElement
readonly state: HTMLDivElement
readonly play: HTMLDivElement
readonly pause: HTMLDivElement
readonly check: HTMLDivElement
readonly volume: HTMLDivElement
readonly volumeClose: HTMLDivElement
readonly screenshot: HTMLDivElement
readonly setting: HTMLDivElement
readonly pip: HTMLDivElement
readonly arrowLeft: HTMLDivElement
readonly arrowRight: HTMLDivElement
readonly playbackRate: HTMLDivElement
readonly aspectRatio: HTMLDivElement
readonly config: HTMLDivElement
readonly lock: HTMLDivElement
readonly flip: HTMLDivElement
readonly unlock: HTMLDivElement
readonly fullscreenOff: HTMLDivElement
readonly fullscreenOn: HTMLDivElement
readonly fullscreenWebOff: HTMLDivElement
readonly fullscreenWebOn: HTMLDivElement
readonly switchOn: HTMLDivElement
readonly switchOff: HTMLDivElement
readonly error: HTMLDivElement
readonly close: HTMLDivElement
readonly airplay: HTMLDivElement
readonly [key: string]: HTMLDivElement
}
I18N INTERNATIONALIZATION
Defines supported languages and translatable text keys.
type I18nKeys
= | 'en'
| 'zh-cn'
| 'zh-tw'
| 'pl'
| 'cs'
| 'es'
| 'fa'
| 'fr'
| 'id'
| 'ru'
| 'tr'
| 'ar'
| 'vi'
| (string & Record<never, never>)
interface I18nValue {
'Video Info': string
'Close': string
'Video Load Failed': string
'Volume': string
'Play': string
'Pause': string
'Rate': string
'Mute': string
'Video Flip': string
'Horizontal': string
'Vertical': string
'Reconnect': string
'Show Setting': string
'Hide Setting': string
'Screenshot': string
'Play Speed': string
'Aspect Ratio': string
'Default': string
'Normal': string
'Open': string
'Switch Video': string
'Switch Subtitle': string
'Fullscreen': string
'Exit Fullscreen': string
'Web Fullscreen': string
'Exit Web Fullscreen': string
'Mini Player': string
'PIP Mode': string
'Exit PIP Mode': string
'PIP Not Supported': string
'Fullscreen Not Supported': string
'Subtitle Offset': string
'Last Seen': string
'Jump Play': string
'AirPlay': string
'AirPlay Not Available': string
}
export type I18n = Partial<Record<I18nKeys, Partial<I18nValue>>>
I18N MODULE DECLARATION
For importing language files from the artplayer/i18n directory.
declare module 'artplayer/i18n/*' {
const lang: Partial<I18nValue>
// @ts-expect-error TS2666
export default lang
}
PROGRESS BAR TYPES
export type Bar = 'loaded' | 'played' | 'hover'
EVENTS INTERFACE
Defines all events that ArtPlayer can emit, categorized by source.
export interface Events {
// Document events
'document:click': [event: Event]
'document:mouseup': [event: Event]
'document:keydown': [event: Event]
'document:touchend': [event: Event]
'document:touchmove': [event: Event]
'document:mousemove': [event: Event]
'document:pointerup': [event: Event]
'document:contextmenu': [event: Event]
'document:pointermove': [event: Event]
'document:visibilitychange': [event: Event]
'document:webkitfullscreenchange': [event: Event]
// Window events
'window:resize': [event: Event]
'window:scroll': [event: Event]
'window:orientationchange': [event: Event]
// Video element events
'video:canplay': [event: Event]
'video:canplaythrough': [event: Event]
'video:complete': [event: Event]
'video:durationchange': [event: Event]
'video:emptied': [event: Event]
'video:ended': [event: Event]
'video:error': [error: Error]
'video:loadeddata': [event: Event]
'video:loadedmetadata': [event: Event]
'video:pause': [event: Event]
'video:play': [event: Event]
'video:playing': [event: Event]
'video:progress': [event: Event]
'video:ratechange': [event: Event]
'video:seeked': [event: Event]
'video:seeking': [event: Event]
'video:stalled': [event: Event]
'video:suspend': [event: Event]
'video:timeupdate': [event: Event]
'video:volumechange': [event: Event]
'video:waiting': [event: Event]
// UI state events
'info': [state: boolean]
'layer': [state: boolean]
'loading': [state: boolean]
'mask': [state: boolean]
'subtitle': [state: boolean]
'contextmenu': [state: boolean]
'control': [state: boolean]
'setting': [state: boolean]
'hotkey': [event: Event]
// Player lifecycle events
'destroy': []
// Subtitle events
'subtitleOffset': [offset: number]
'subtitleBeforeUpdate': [cue: VTTCue]
'subtitleAfterUpdate': [cue: VTTCue]
'subtitleLoad': [cues: VTTCue[], option: Subtitle]
// User interaction events
'focus': [event: Event]
'blur': [event: Event]
'dblclick': [event: Event]
'click': [event: Event]
'hover': [state: boolean, event: Event]
'mousemove': [event: Event]
// Player state events
'resize': []
'view': [state: boolean]
'lock': [state: boolean]
'aspectRatio': [aspectRatio: AspectRatio]
'autoHeight': [height: number]
'autoSize': []
'ready': []
// Player functionality events
'error': [error: Error, reconnectTime: number]
'flip': [flip: Flip]
'fullscreen': [state: boolean]
'fullscreenError': [event: Event]
'fullscreenWeb': [state: boolean]
'mini': [state: boolean]
'pause': []
'pip': [state: boolean]
'play': []
'screenshot': [dataUri: string]
'seek': [currentTime: number]
'restart': [url: string]
'muted': [state: boolean]
'setBar': [type: Bar, percentage: number, event?: Event | undefined]
'keydown': [event: KeyboardEvent]
}
CSS VARIABLES INTERFACE
Defines all customizable CSS variables for styling the player.
export interface CssVar {
'--art-theme': string
'--art-font-color': string
'--art-background-color': string
'--art-text-shadow-color': string
'--art-transition-duration': string
'--art-padding': string
'--art-border-radius': string
'--art-progress-height': string
'--art-progress-color': string
'--art-progress-top-gap': string
'--art-hover-color': string
'--art-loaded-color': string
'--art-state-size': string
'--art-state-opacity': number
'--art-bottom-height': string
'--art-bottom-offset': string
'--art-bottom-gap': string
'--art-highlight-width': string
'--art-highlight-color': string
'--art-control-height': string
'--art-control-opacity': number
'--art-control-icon-size': string
'--art-control-icon-scale': number
'--art-volume-height': string
'--art-volume-handle-size': string
'--art-lock-size': string
'--art-indicator-scale': number
'--art-indicator-size': string
'--art-fullscreen-web-index': 9999
'--art-settings-icon-size': string
'--art-settings-max-height': string
'--art-selector-max-height': string
'--art-contextmenus-min-width': string
'--art-subtitle-font-size': string
'--art-subtitle-gap': string
'--art-subtitle-bottom': string
'--art-subtitle-border': string
'--art-widget-background': string
'--art-tip-background': string
'--art-scrollbar-size': string
'--art-scrollbar-background': string
'--art-scrollbar-background-hover': string
'--art-mini-progress-height': string
}
Here are the TypeScript declaration files for ArtPlayer with developer explanations:
CONFIG INTERFACE
The Config interface defines the core HTML5 video API properties, methods, events, and prototypes that ArtPlayer supports.
export interface Config {
properties: [
'audioTracks',
'autoplay',
'buffered',
'controller',
'controls',
'crossOrigin',
'currentSrc',
'currentTime',
'defaultMuted',
'defaultPlaybackRate',
'duration',
'ended',
'error',
'loop',
'mediaGroup',
'muted',
'networkState',
'paused',
'playbackRate',
'played',
'preload',
'readyState',
'seekable',
'seeking',
'src',
'startDate',
'textTracks',
'videoTracks',
'volume',
]
methods: ['addTextTrack', 'canPlayType', 'load', 'play', 'pause']
events: [
'abort',
'canplay',
'canplaythrough',
'durationchange',
'emptied',
'ended',
'error',
'loadeddata',
'loadedmetadata',
'loadstart',
'pause',
'play',
'playing',
'progress',
'ratechange',
'seeked',
'seeking',
'stalled',
'suspend',
'timeupdate',
'volumechange',
'waiting',
]
prototypes: [
'width',
'height',
'videoWidth',
'videoHeight',
'poster',
'webkitDecodedFrameCount',
'webkitDroppedFrameCount',
'playsInline',
'webkitSupportsFullscreen',
'webkitDisplayingFullscreen',
'onenterpictureinpicture',
'onleavepictureinpicture',
'disablePictureInPicture',
'cancelVideoFrameCallback',
'requestVideoFrameCallback',
'getVideoPlaybackQuality',
'requestPictureInPicture',
'webkitEnterFullScreen',
'webkitEnterFullscreen',
'webkitExitFullScreen',
'webkitExitFullscreen',
]
}
SELECTOR INTERFACE
Used for custom dropdown selectors in controls, allowing HTML content and custom properties.
export interface Selector {
/**
* Whether the default is selected
*/
default?: boolean
/**
* Html string of selector
*/
html: string | HTMLElement
/**
* Allow custom properties
*/
[key: string]: any
}
COMPONENT INTERFACE
Represents UI components that can be added to the player controls with lifecycle methods.
export interface Component {
/**
* Component self-increasing id
*/
readonly id: number
/**
* Component parent name
*/
readonly name: string | undefined
/**
* Component parent element
*/
readonly $parent: HTMLElement | undefined
/**
* Whether to show component parent
*/
get show(): boolean
/**
* Whether to show component parent
*/
set show(state: boolean)
/**
* Toggle the component parent
*/
toggle: () => void
/**
* Dynamic add a component
*/
add: (option: ComponentOption) => HTMLElement
/**
* Dynamic remove a component by name
*/
remove: (name: string) => void
/**
* Dynamic update a component
*/
update: (option: ComponentOption) => HTMLElement
}
COMPONENT OPTION INTERFACE
Configuration options for creating custom components with events, styling, and positioning.
export interface ComponentOption {
/**
* Html string or html element of component
*/
html?: string | HTMLElement
/**
* Whether to disable component
*/
disable?: boolean
/**
* Unique name for component
*/
name?: string
/**
* Component sort index
*/
index?: number
/**
* Component style object
*/
style?: Partial<CSSStyleDeclaration>
/**
* Component click event
*/
click?: (this: Artplayer, component: Component, event: Event) => void
/**
* When the component was mounted
*/
mounted?: (this: Artplayer, element: HTMLElement) => void
/**
* When the component was before unmount
*/
beforeUnmount?: (this: Artplayer, element: HTMLElement) => void
/**
* Component tooltip, use in controls
*/
tooltip?: string
/**
* Component position, use in controls
*/
position?: 'top' | 'left' | 'right' | (string & Record<never, never>)
/**
* Custom selector list, use in controls
*/
selector?: Selector[]
/**
* When selector item click, use in controls
*/
onSelect?: (this: Artplayer, selector: Selector, element: HTMLElement, event: Event) => void
}
TYPE EXPORTS
These types are defined elsewhere but exported for external use.
export type {
Config,
Events,
I18n,
Icons,
Option,
Player,
Setting,
SettingOption,
Subtitle,
Template,
Utils,
}
ART PLAYER CLASS
The main ArtPlayer class that extends the base Player with extensive configuration and plugin support.
export default class Artplayer extends Player {
constructor(option: Option, readyCallback?: (this: Artplayer, art: Artplayer) => unknown)
STATIC PROPERTIES
Global static properties shared across all ArtPlayer instances.
static readonly instances: Artplayer[]
static readonly version: string
static readonly env: string
static readonly build: string
static readonly config: Config
static readonly utils: Utils
static readonly scheme: Record<keyof Option, unknown>
static readonly Emitter: new (...args: unknown[]) => unknown
static readonly validator: <T extends object>(option: T, scheme: object) => T
static readonly kindOf: (item: unknown) => string
static readonly html: Artplayer['template']['html']
static readonly option: Option
CONSTANTS
Configuration constants that control player behavior and timing.
static STYLE: string
static DEBUG: boolean
static CONTEXTMENU: boolean
static NOTICE_TIME: number
static SETTING_WIDTH: number
static SETTING_ITEM_WIDTH: number
static SETTING_ITEM_HEIGHT: number
static RESIZE_TIME: number
static SCROLL_TIME: number
static SCROLL_GAP: number
static AUTO_PLAYBACK_MAX: number
static AUTO_PLAYBACK_MIN: number
static AUTO_PLAYBACK_TIMEOUT: number
static RECONNECT_TIME_MAX: number
static RECONNECT_SLEEP_TIME: number
static CONTROL_HIDE_TIME: number
static DBCLICK_TIME: number
static DBCLICK_FULLSCREEN: boolean
static MOBILE_DBCLICK_PLAY: boolean
static MOBILE_CLICK_PLAY: boolean
static AUTO_ORIENTATION_TIME: number
static INFO_LOOP_TIME: number
static FAST_FORWARD_VALUE: number
static FAST_FORWARD_TIME: number
static TOUCH_MOVE_RATIO: number
static VOLUME_STEP: number
static SEEK_STEP: number
static PLAYBACK_RATE: number[]
static ASPECT_RATIO: string[]
static FLIP: string[]
static FULLSCREEN_WEB_IN_BODY: boolean
static LOG_VERSION: boolean
static USE_RAF: boolean
static REMOVE_SRC_WHEN_DESTROY: boolean
INSTANCE PROPERTIES
Read-only properties for individual player instances.
readonly id: number
readonly option: Option
readonly isLock: boolean
readonly isReady: boolean
readonly isFocus: boolean
readonly isInput: boolean
readonly isRotate: boolean
readonly isDestroy: boolean
PLUGIN SUPPORT
Optional properties for various video format plugins.
flv?: unknown
m3u8?: unknown
hls?: unknown
ts?: unknown
mpd?: unknown
torrent?: unknown
EVENT SYSTEM
Typed event system for handling player events with generic and string-based overloads.
on<T extends keyof Events>(name: T, fn: (...args: Events[T]) => unknown, ctx?: object): this
on(name: string, fn: (...args: unknown[]) => unknown, ctx?: object): this
once<T extends keyof Events>(name: T, fn: (...args: Events[T]) => unknown, ctx?: object): this
once(name: string, fn: (...args: unknown[]) => unknown, ctx?: object): this
emit<T extends keyof Events>(name: T, ...args: Events[T]): this
emit(name: string, ...args: unknown[]): this
off<T extends keyof Events>(name: T, callback?: (...args: Events[T]) => unknown): this
off(name: string, callback?: (...args: unknown[]) => unknown): this
CONVENIENCE PROPERTIES
Shortcut properties for commonly accessed functionality.
query: Artplayer['template']['query']
proxy: Artplayer['events']['proxy']
video: Artplayer['template']['$video']
INTERNAL EVENT STORAGE
Internal structure for storing event listeners.
e: { [K in keyof Events]?: { fn: (...args: Events[K]) => unknown, ctx: unknown }[] }
DESTRUCTION METHOD
Clean up the player instance and optionally remove HTML from DOM.
destroy(removeHtml?: boolean): void
TEMPLATE SYSTEM
Handles the player's HTML structure and DOM queries.
readonly template: {
get html(): string
query: (str: string) => HTMLElement
} & Template
EVENT MANAGEMENT
Comprehensive event handling system with proxy, hover, and global event binding.
readonly events: {
proxy: <KW extends keyof WindowEventMap, KH extends keyof HTMLElementEventMap>(
element: HTMLDivElement | Document | Window,
eventName: KW | KH,
handler: (event: WindowEventMap[KW] | HTMLElementEventMap[KH] | Event) => void,
options?: boolean | AddEventListenerOptions,
) => () => void
hover: (element: HTMLElement, mouseenter?: (event: Event) => any, mouseleave?: (event: Event) => any) => void
remove: (event: Event) => void
bindGlobalEvents: (source?: { window?: Window, document?: Document }) => void
}
STORAGE SYSTEM
Persistent storage for player settings and user preferences.
readonly storage: {
name: string
settings: Record<string, unknown>
get: (key: string) => unknown
set: (key: string, value: unknown) => void
del: (key: string) => boolean
clear: () => void
}
ICON MANAGEMENT
Handles player icons and UI symbols.
readonly icons: Icons
INTERNATIONALIZATION (I18N)
Multi-language support system for player UI text.
readonly i18n: {
readonly languages: I18n
get: (key: string) => string
update: (language: Partial<I18n>) => void
}
NOTIFICATION SYSTEM
Temporary message display system for user feedback.
readonly notice: {
timer: number
set show(msg: string)
}
Below is the plain text output of the TypeScript declaration file for ArtPlayer's API, with added explanations for clarity.
// ArtPlayer class definition containing core player components and methods
class Artplayer {
// Layers component: a record of named HTML elements combined with Component functionality for UI layers
readonly layers: Record<string, HTMLElement> & Component
// Controls component: manages player control elements (e.g., play, pause buttons) as HTML elements with Component features
readonly controls: Record<string, HTMLElement> & Component
// Contextmenu component: handles right-click context menu items as HTML elements with Component behavior
readonly contextmenu: Record<string, HTMLElement> & Component
// Subtitle component: provides subtitle management, including URL handling, text track access, and styling
readonly subtitle: {
// Gets the current subtitle URL
get url(): string
// Sets the subtitle URL to load new subtitles
set url(url: string)
// Retrieves the active TextTrack object for subtitles
get textTrack(): TextTrack
// Returns an array of currently active VTTCue objects (visible subtitle cues)
get activeCues(): VTTCue[]
// Returns all VTTCue objects in the subtitle track
get cues(): VTTCue[]
// Applies CSS styles to subtitles; can set a single property or multiple via a partial style object
style: (name: string | Partial<CSSStyleDeclaration>, value?: string) => void
// Switches to a new subtitle URL with optional configuration, returning a promise that resolves to the URL
switch: (url: string, option?: Subtitle) => Promise<string>
} & Component
// Info component: displays player information (e.g., title, duration) as a Component
readonly info: Component
// Loading component: shows loading indicators or states during media buffering
readonly loading: Component
// Hotkey component: manages keyboard shortcuts with methods to add or remove key event listeners
readonly hotkey: {
// Record of key names to arrays of callback functions triggered on key events
keys: Record<string, ((event: Event) => any)[]>
// Adds a hotkey listener for a specific key, with a callback that has Artplayer context
add: (key: string, callback: (this: Artplayer, event: Event) => any) => Artplayer['hotkey']
// Removes a specific callback for a key event
remove: (key: string, callback: (event: Event) => any) => Artplayer['hotkey']
}
// Mask component: typically used for overlays like error messages or custom UI masks
readonly mask: Component
// Setting component: handles player settings menu, including options management and UI updates
readonly setting: {
// Array of setting options available in the player
option: SettingOption[]
// Updates the styling of the settings menu, optionally adjusting width
updateStyle: (width?: number) => void
// Finds a setting option by its name
find: (name: string) => SettingOption
// Adds a new setting to the menu
add: (setting: Setting) => SettingOption[]
// Updates existing settings with new values
update: (settings: Setting) => SettingOption[]
// Removes a setting by name
remove: (name: string) => SettingOption[]
} & Component
// Plugins component: allows extending player functionality with custom plugins
readonly plugins: {
// Adds a plugin function that receives the Artplayer instance; can be synchronous or asynchronous
add: (
plugin: (this: Artplayer, art: Artplayer) => unknown | Promise<unknown>,
) => Promise<Artplayer['plugins']> | Artplayer['plugins']
} & Record<string, unknown> // Also acts as a record for storing plugin instances by name
}
// Exports Artplayer for use in modules and as a global namespace in non-module contexts
export = Artplayer
export as namespace Artplayer;
===== Examples Summary =====
ads.js example code:
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoSize: true,
fullscreen: true,
fullscreenWeb: true,
plugins: [
artplayerPluginAds({
// html广告,假如是视频广告则忽略该值
html: '<img src="/assets/sample/poster.jpg">',
// 视频广告的地址
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)
})
This example demonstrates the ads plugin for ArtPlayer, showing how to configure and display advertisements before video playback. It uses the artplayerPluginAds API to set up both HTML and video ads with configurable duration, skip options, and internationalization. The code also shows event handling for ad clicks and skips.
ambilight.js example code:
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,
}),
],
})
This example demonstrates the ambilight plugin for ArtPlayer, which creates ambient lighting effects around the video player. It uses the artplayerPluginAmbilight API with configurable blur, opacity, frequency, and duration parameters to customize the lighting effect.
asr.js example code:
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)
This example demonstrates automatic speech recognition (ASR) integration with ArtPlayer using the artplayerPluginAsr plugin. It shows real-time audio processing and WebSocket communication with an ASR service to generate live subtitles. The plugin captures audio chunks and sends them to a speech recognition API.
auto.thumbnail.js example code:
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
plugins: [
artplayerPluginAutoThumbnail({
//
}),
],
})
This example demonstrates the auto-thumbnail plugin for ArtPlayer, which automatically generates video thumbnails for the progress bar. It uses the artplayerPluginAutoThumbnail API with default configuration to create thumbnail previews.
canvas.js example code:
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(),
})
This example demonstrates the canvas proxy plugin for ArtPlayer, which enables advanced video manipulation and effects using HTML5 Canvas. It uses the artplayerProxyCanvas API along with comprehensive player configuration including thumbnails, playback controls, and various display features.
chapter.js example code:
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: '终わり' },
],
}),
],
})
This example demonstrates the chapter plugin for ArtPlayer, which adds chapter navigation to videos. It uses the artplayerPluginChapter API to define video segments with start/end times and titles, enabling users to jump between different sections of the video.
chromecast.js example code:
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
}),
],
})
This example demonstrates the Chromecast plugin for ArtPlayer, enabling video casting to Chromecast devices. It uses the artplayerPluginChromecast API with optional SDK and MIME type configuration for casting functionality.
danmuku.js example code:
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)
})
},
}),
],
})
This example demonstrates the danmuku (bullet comments) plugin for ArtPlayer, showing comprehensive configuration for displaying user comments over video playback. It uses the artplayerPluginDanmuku API with extensive customization options for appearance, behavior, filtering, and real-time comment submission.
danmuku.mask.js example code:
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',
}),
artplayerPluginDanmukuMask({
solutionPath: '/assets/@mediapipe/selfie_segmentation',
}),
],
})
This example demonstrates the combination of danmuku and danmuku mask plugins for ArtPlayer. It uses both artplayerPluginDanmuku and artplayerPluginDanmukuMask APIs to create bullet comments with person segmentation masking, where comments appear behind detected human figures in the video using MediaPipe selfie segmentation.
dash.control.js example code:
// npm i dashjs
// npm i artplayer-plugin-dash-control
// import dashjs from 'dashjs';
// import artplayerPluginDashControl from 'artplayer-plugin-dash-control';
This example demonstrates the DASH (Dynamic Adaptive Streaming over HTTP) control plugin for ArtPlayer. It shows the import statements for integrating dash.js with the artplayerPluginDashControl API to enable adaptive bitrate streaming with DASH protocol support.
Example 1: ArtPlayer with DASH plugin and custom type handler
This example shows how to initialize ArtPlayer with DASH streaming support using dash.js library and the artplayerPluginDashControl plugin for quality and audio track selection.
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.js integration
This example demonstrates a standalone DASH.js implementation with ArtPlayer, showing how to handle MPD format streams with custom type definition.
// 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 artplayerPluginDocumentPip plugin to enable Document Picture-in-Picture functionality with custom dimensions and fallback options.
// 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.js integration
This example demonstrates FLV format playback using flv.js library with custom type handler for FLV streams.
// 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 with quality and audio control plugin
This example shows HLS streaming with artplayerPluginHlsControl plugin for quality selection and audio track management, including native HLS fallback for Safari.
// 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.js integration
This example shows a standalone HLS.js implementation with ArtPlayer for handling M3U8 streams with browser compatibility checks.
// 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: Iframe plugin for embedded ArtPlayer instances
This example demonstrates how to use ArtplayerPluginIframe to embed ArtPlayer within an iframe and handle cross-frame communication for fullscreen functionality.
// npm i artplayer-plugin-iframe
// import ArtplayerPluginIframe from 'artplayer-plugin-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 ArtplayerPluginIframe({
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) => {
ArtplayerPluginIframe.postMessage({
type: 'fullscreenWeb',
data: state,
})
})
})
===== index.js =====
Example 8: Basic ArtPlayer initialization
This example shows a minimal ArtPlayer setup with default configuration for basic video playback.
// Basic ArtPlayer initialization code would go here
// This serves as a placeholder for the main index.js file
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: '<img width="22" height="22" src="/assets/img/subtitle.svg">',
selector: [
{
html: 'Display',
tooltip: 'Show',
switch: true,
onSwitch(item) {
item.tooltip = item.switch ? 'Hide' : 'Show'
art.subtitle.show = !item.switch
return !item.switch
},
},
{
default: true,
html: 'Bilingual',
url: '/assets/sample/subtitle.srt',
},
{
html: 'Chinese',
url: '/assets/sample/subtitle.cn.srt',
},
{
html: 'Japanese',
url: '/assets/sample/subtitle.jp.srt',
},
],
onSelect(item) {
art.subtitle.switch(item.url, {
name: item.html,
})
return item.html
},
},
{
html: 'Switcher',
icon: '<img width="22" height="22" src="/assets/img/state.svg">',
tooltip: 'OFF',
switch: false,
onSwitch(item) {
item.tooltip = item.switch ? 'OFF' : 'ON'
console.info('You clicked on the custom switch', item.switch)
return !item.switch
},
},
{
html: 'Slider',
icon: '<img width="22" height="22" src="/assets/img/state.svg">',
tooltip: '5x',
range: [5, 1, 10, 0.1],
onRange(item) {
return `${item.range[0]}x`
},
},
{
html: 'Button',
icon: '<img width="22" height="22" src="/assets/img/state.svg">',
tooltip: 'tooltip',
onClick() {
return 'Button clicked'
},
},
],
contextmenu: [
{
html: 'Custom menu',
click(contextmenu) {
console.info('You clicked on the custom menu')
contextmenu.show = false
},
},
],
layers: [
{
html: '<img width="100" src="/assets/sample/layer.png">',
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: '<img src="/assets/img/ploading.gif">',
state: '<img width="150" height="150" src="/assets/img/state.svg">',
indicator: '<img width="16" height="16" src="/assets/img/indicator.svg">',
},
})
// This example demonstrates a comprehensive ArtPlayer configuration with multiple features including custom settings, context menu, layers, quality switching, thumbnails, subtitles, highlights, and custom controls.
===== libass.js =====
// npm i artplayer-plugin-libass
// import artplayerPluginLibass from 'artplayer-plugin-libass';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreenWeb: true,
subtitle: {
url: '/assets/sample/style-test.ass',
},
plugins: [
artplayerPluginLibass({
// debug: true,
workerUrl: 'https://unpkg.com/libass-wasm@4.1.0/dist/js/subtitles-octopus-worker.js',
// wasmUrl: 'https://unpkg.com/libass-wasm@4.1.0/dist/js/subtitles-octopus-worker.wasm',
fallbackFont: '/assets/misc/SourceHanSansCN-Bold.woff2',
}),
],
})
// init
art.on('artplayerPluginLibass:init', (adapter) => {
console.info('artplayerPluginLibass:init', adapter)
})
// subtitle switch
art.on('artplayerPluginLibass:switch', (url) => {
console.info('artplayerPluginLibass:switch', url)
})
// subtitle visible
art.on('artplayerPluginLibass:visible', (visible) => {
console.info('artplayerPluginLibass:visible', visible)
})
// subtitle timeOffset
art.on('artplayerPluginLibass:timeOffset', (timeOffset) => {
console.info('artplayerPluginLibass:timeOffset', timeOffset)
})
// destroy
art.on('artplayerPluginLibass:destroy', () => {
console.info('artplayerPluginLibass:destroy')
})
// This example shows how to integrate the libass plugin for advanced ASS subtitle support with WebAssembly rendering and event handling for subtitle operations.
===== mobile.js =====
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
poster: '/assets/sample/poster.jpg',
autoSize: true,
loop: true,
mutex: true,
setting: true,
flip: true,
lock: true,
fastForward: true,
playbackRate: true,
aspectRatio: true,
theme: '#ff0057',
fullscreen: true,
fullscreenWeb: true,
miniProgressBar: true,
autoOrientation: true,
airplay: true,
moreVideoAttr: {
'x5-video-player-type': 'h5',
'x5-video-player-fullscreen': false,
'x5-video-orientation': 'portraint',
'preload': 'metadata',
},
thumbnails: {
url: '/assets/sample/thumbnails.png',
number: 60,
column: 10,
scale: 0.6,
},
subtitle: {
name: '中日双语',
url: '/assets/sample/subtitle.srt',
style: {
color: '#48aff0',
fontSize: '16px',
},
},
layers: [
{
html: `<img width="50" src="/assets/sample/layer.png">`,
click() {
art.notice.show = '你点击了自定义层'
},
style: {
position: 'absolute',
top: '10px',
right: '10px',
opacity: '.9',
},
},
],
icons: {
loading: '<img src="/assets/img/ploading.gif">',
state: '<img width="150" height="150" src="/assets/img/state.svg">',
indicator: '<img width="16" height="16" src="/assets/img/indicator.svg">',
},
settings: [
{
width: 200,
html: '切换字幕',
tooltip: '双语',
icon: '<img width="22" height="22" src="/assets/img/subtitle.svg">',
selector: [
{
html: '开关',
switch: true,
tooltip: '显示',
onSwitch(item) {
item.tooltip = item.switch ? '隐藏' : '显示'
art.subtitle.show = !item.switch
return !item.switch
},
},
{
default: true,
html: '双语',
url: '/assets/sample/subtitle.srt',
},
{
html: '中文',
url: '/assets/sample/subtitle.cn.srt',
},
{
html: '日文',
url: '/assets/sample/subtitle.jp.srt',
},
],
onSelect(item) {
art.subtitle.switch(item.url, {
name: item.html,
})
return item.html
},
},
],
})
// This example demonstrates mobile-optimized ArtPlayer configuration with Chinese localization, mobile-specific video attributes for QQ browser, and responsive design features.
===== mpegts.js =====
// npm i mpegts
// import mpegts from 'mpegts';
function playFlv(video, url, art) {
if (mpegts.isSupported()) {
if (art.flv)
art.flv.destroy()
const flv = mpegts.createPlayer({
type: 'flv',
url,
})
flv.attachMediaElement(video)
flv.load()
flv.play()
}
// This example shows how to integrate mpegts.js for FLV video playback support, including proper cleanup of previous FLV instances and media element attachment.
custom.flv.js
This example demonstrates how to add custom FLV playback support using the flv.js library. It shows the customType API to register a custom video type handler.
function playFlv(video, url, art) {
if (flvjs.isSupported()) {
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)
})
===== multiple.subtitles.js =====
This example shows how to use the multiple subtitles plugin to display multiple subtitle tracks with custom styling and settings controls.
// npm i artplayer-plugin-multiple-subtitles
// import artplayerPluginMultipleSubtitles from 'artplayer-plugin-multiple-subtitles';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
plugins: [
artplayerPluginMultipleSubtitles({
subtitles: [
{
name: 'chinese',
url: '/assets/sample/subtitle.cn.srt',
},
{
name: 'japanese',
url: '/assets/sample/subtitle.jp.srt',
},
],
}),
],
settings: [
{
width: 200,
html: 'Subtitle',
tooltip: 'Double',
icon: '<img width="22" height="22" src="/assets/img/subtitle.svg">',
selector: [
{
html: 'Display',
tooltip: 'Show',
switch: true,
onSwitch(item) {
item.tooltip = item.switch ? 'Hide' : 'Show'
// 显示/隐藏字幕
// Show/hide subtitles
art.subtitle.show = !item.switch
return !item.switch
},
},
{
html: 'Reverse',
tooltip: 'Off',
switch: false,
onSwitch(item) {
item.tooltip = item.switch ? 'Off' : 'On'
// 修改字幕顺序
// Change the order of subtitles
if (item.switch) {
art.plugins.multipleSubtitles.tracks(['chinese', 'japanese'])
}
else {
art.plugins.multipleSubtitles.tracks(['japanese', 'chinese'])
}
return !item.switch
},
},
{
default: true,
html: 'Double',
name: 'double',
},
{
html: 'Chinese',
name: 'chinese',
},
{
html: 'Japanese',
name: 'japanese',
},
],
onSelect(item) {
if (item.name === 'double') {
// 重置字幕
// Reset subtitles
art.plugins.multipleSubtitles.reset()
}
else {
// 显示单个字幕
// Show single subtitle
art.plugins.multipleSubtitles.tracks([item.name])
}
return item.html
},
},
],
})
// 自定义你自己的样式,请勿复制以下代码
// Customize your own style, please do not copy the following code
const style = `
.art-subtitle-chinese {
color: red;
font-size: 18px;
}
.art-subtitle-japanese {
color: yellow;
font-size: 12px;
}
`
const $style = document.getElementById('artplayer-subtitle-style')
if ($style) {
$style.textContent = style
}
else {
const $style = document.createElement('style')
$style.id = 'artplayer-subtitle-style'
$style.textContent = style
document.head.appendChild($style)
}
===== setting.test.js =====
This example demonstrates comprehensive settings configuration including subtitle controls, custom switches, sliders, and dynamic settings manipulation through the settings API.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
flip: true,
playbackRate: true,
aspectRatio: true,
subtitleOffset: true,
settings: [
{
width: 200,
html: 'Subtitle',
name: 'subtitle',
tooltip: 'Bilingual',
icon: '<img width="22" height="22" src="/assets/img/subtitle.svg">',
selector: [
{
html: 'Display',
tooltip: 'Show',
switch: true,
onSwitch(item) {
item.tooltip = item.switch ? 'Hide' : 'Show'
art.subtitle.show = !item.switch
return !item.switch
},
},
{
default: true,
html: 'Bilingual',
url: '/assets/sample/subtitle.srt',
},
{
html: 'Chinese',
url: '/assets/sample/subtitle.cn.srt',
},
{
html: 'Japanese',
url: '/assets/sample/subtitle.jp.srt',
},
],
onSelect(item) {
art.subtitle.switch(item.url, {
name: item.html,
})
return item.html
},
mounted(...args) {
console.info(args)
},
},
{
html: 'Switcher',
icon: '<img width="22" height="22" src="/assets/img/state.svg">',
tooltip: 'OFF',
switch: false,
onSwitch(item) {
item.tooltip = item.switch ? 'OFF' : 'ON'
console.info('You clicked on the custom switch', item.switch)
return !item.switch
},
mounted(...args) {
console.info(args)
},
},
{
html: 'Slider',
icon: '<img width="22" height="22" src="/assets/img/state.svg">',
tooltip: '5x',
range: [5, 1, 10, 0.1],
onRange(item) {
return `${item.range[0]}x`
},
mounted(...args) {
console.info(args)
},
},
],
}, async () => {
const { sleep } = Artplayer.utils
art.setting.show = true
console.log(art.setting.builtin)
console.log(art.setting.find('aspect-ratio'))
console.log(art.setting.find('aspect-ratio2'))
await sleep(1000)
art.setting.resize()
await sleep(1000)
art.setting.inactivate(art.setting.find('subtitle'))
art.setting.remove('aspect-ratio')
try {
art.setting.remove('aspect-ratio2')
}
catch (error) {
console.log(error.message)
}
await sleep(1000)
art.setting.update({
name: 'subtitle-offset',
html: 'new offset',
range: [5, -11, 11, 1],
})
await sleep(1000)
art.setting.find('subtitle-offset').range = [0, -0, 10, 1]
await sleep(1000)
art.setting.update({
name: 'subtitle-offset2',
html: 'new offset 2',
range: [5, -11, 11, 1],
onChange(item) {
return `${item.range[0]}s`
},
})
await sleep(1000)
art.setting.update({
name: 'flip',
html: 'new flip',
tooltip: 'OFF',
switch: false,
})
await sleep(1000)
art.setting.find('flip').switch = true
await sleep(1000)
art.setting.update({
name: 'flip2',
html: 'new flip2',
tooltip: 'OFF',
switch: true,
})
await sleep(1000)
try {
art.setting.add({
name: 'flip2',
html: 'new flip2',
tooltip: 'OFF',
switch: true,
})
}
catch (error) {
console.log(error.message)
}
})
===== thumbnail.js =====
This example demonstrates the thumbnail plugin which shows video preview thumbnails when hovering over the progress bar.
// npm i artplayer-plugin-thumbnail
// import artplayerPluginThumbnail from 'artplayer-plugin-thumbnail';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
plugins: [
artplayerPluginThumbnail({
width: 160,
number: 100,
scale: 1,
}),
],
})
===== vast.js =====
This example shows how to integrate VAST advertising using Google's IMA SDK through the vast plugin.
// Depends on:
// https://glomex.github.io/vast-ima-player/
// https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side
// Google's IMA SDK are blocked by your Ad blocker.
// Please Turn Off Your Ad Blocker.
// npm i artplayer-plugin-vast
// import artplayerPluginVast from 'artplayer-plugin-vast';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreen: true,
fullscreenWeb: true,
plugins: [
artplayerPluginVast(({ playUrl, imaPlayer, ima }) => {
// Play the ad when the video is played
art.once('play', () => {
playUrl('https://artplayer.org/assets/vast/linear-ad.xml')
})
}),
],
})
===== vtt.thumbnail.js =====
This example demonstrates VTT-based thumbnail previews using the vtt-thumbnail plugin with WebVTT format thumbnail files.
// npm i artplayer-plugin-vtt-thumbnail
// import artplayerPluginVttThumbnail from 'artplayer-plugin-vtt-thumbnail';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/bbb-video.mp4',
plugins: [
artplayerPluginVttThumbnail({
vtt: '/assets/sample/bbb-thumbnails.vtt',
}),
],
})
===== webtorrent.js =====
This example shows WebTorrent integration for streaming torrent-based video content (implementation code not shown).
// npm i webtorrent
// import WebTorrent from 'webtorrent';
Full example code:
async function playTorrent(video, url, art) {
if (WebTorrent.WEBRTC_SUPPORT) {
if (art.torrent)
art.torrent.destroy()
art.torrent = new WebTorrent()
await navigator.serviceWorker.register('/webtorrent.sw.min.js')
art.torrent.loadWorker(navigator.serviceWorker.controller)
art.torrent.add(url, (torrent) => {
const file = torrent.files.find((file) => {
return file.name.endsWith('.mp4')
})
file.streamTo(video)
})
art.on('destroy', () => art.torrent.destroy())
}
else {
art.notice.show = 'Unsupported playback format: torrent'
}
}
const art = new Artplayer({
container: '.artplayer-app',
url: 'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent',
type: 'torrent',
customType: {
torrent: playTorrent,
},
})
art.on('ready', () => {
console.info(art.torrent)
})
This example demonstrates WebTorrent integration with ArtPlayer, showing how to stream torrent content directly in the video player. The playTorrent function checks for WebRTC support, initializes WebTorrent, registers a service worker, and streams MP4 files from torrents to the video element. The ArtPlayer configuration uses a magnet URI as the video source and defines a custom 'torrent' type that calls the playTorrent function. The example also shows proper cleanup by destroying the torrent instance when the player is destroyed, and demonstrates using the 'ready' event to access the torrent instance.