Files
Harvey Zhao 3adff76edf feat: Enhance DeepSeek API integration with retries and timeout handling
- Updated API key environment variable from DEEPL_API_KEY to DEEPSEEK_API_KEY
- Increased maximum text chunk length from 5000 to 8000 characters
- Implemented request timeout and retry logic for API calls
- Added handling for rate limiting responses (HTTP 429)
- Improved error handling for API responses
2026-03-08 13:00:57 +08:00

8967 lines
226 KiB
Plaintext
Raw Permalink 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 refer to the secondary properties attached to the instance, which are less commonly used.
option
The player's options.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.option);
Note: If you directly modify this option object, the player will not respond immediately.
template
Manages all DOM elements of the player.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.template);
console.info(art.template.$video);
Note: To easily distinguish between DOM elements and regular objects, all DOM elements within the player are named with a $ prefix.
This is the definition of all DOM elements: artplayer/types/template.d.ts
events
Manages all DOM events for the player. It essentially proxies addEventListener and removeEventListener. When using the following methods to handle events, the event will be automatically destroyed when the player is destroyed.
The proxy method is used to proxy DOM events.
The hover method is used to proxy custom hover events.
var container = document.querySelector('.artplayer-app');
var art = new Artplayer({
container: container,
url: '/assets/sample/video.mp4',
});
art.events.proxy(container, 'click', event => {
console.info('click', event);
});
art.events.hover(container, (event) => {
console.info('mouseenter', event);
}, (event) => {
console.info('mouseleave', event);
});
Note: If you need DOM events that only exist during the player's lifecycle, it is strongly recommended to use these functions to avoid memory leaks.
storage
Manages the player's local storage.
The name property is used to set the cache key.
The set method is used to set a cache value.
The get method is used to get a cache value.
The del method is used to delete a cache value.
The clear method is used to clear all cache.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.storage.set('test', { foo: 'bar' });
const test = art.storage.get('test');
console.info(test);
art.storage.del('test');
art.storage.clear();
Note: By default, all player instances share the same localStorage, and the default key is artplayer_settings.
If you want different players to use different localStorage, you can modify art.storage.name.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.storage.name = 'your-storage-key';
art.storage.set('test', { foo: 'bar' });
icons
Manages all svg icons for the player.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.icons.loading);
This is the definition of all icons: artplayer/types/icons.d.ts
i18n
Manages the player's i18n.
The get method is used to get an i18n value.
The update method is used to update the i18n object.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.i18n.get('Play'));
art.i18n.update({
'zh-cn': {
Play: 'Your Play'
}
});
Note: Using art.i18n.update can only update the i18n after instantiation. If you want to update the i18n before instantiation, please use the i18n option in the basic options.
notice
Manages the player's notifications. It only has a show property for displaying notifications.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.notice.show = 'Video Ready To Play';
})
Note: If you want to hide the notice immediately: art.notice.show = '';
layers
Manages the player's layers.
The add method is used to dynamically add a layer.
The remove method is used to dynamically remove a layer.
The update method is used to dynamically update a layer.
The show property is used to set whether all layers are visible.
The toggle method is used to toggle the visibility of all layers.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.layers.add({
html: 'Some Text',
});
setTimeout(() => {
art.layers.show = false;
}, 1000);
});
Refer to the following address for Component Configuration: /component/layers.html
controls
Manages the player's controls.
The add method is used to dynamically add a control.
The remove method is used to dynamically remove a control.
The update method is used to dynamically update controls.
The show property is used to set whether to display all controls.
The toggle method is used to toggle the display of all controls.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.controls.add({
html: 'Some Text',
position: 'left',
});
setTimeout(() => {
art.controls.show = false;
}, 1000);
});
For Component Configuration, please refer to: /component/controls.html
contextmenu
Manages the player's context menu.
The add method is used to dynamically add menu items.
The remove method is used to dynamically remove menu items.
The update method is used to dynamically update menu items.
The show property is used to set whether to display all menu items.
The toggle method is used to toggle the display of all menu items.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.contextmenu.add({
html: 'Some Text',
});
art.contextmenu.show = true;
setTimeout(() => {
art.contextmenu.show = false;
}, 1000);
});
For Component Configuration, please refer to: /component/contextmenu.html
subtitle
Manages the player's subtitle functionality.
The url property sets and returns the current subtitle URL.
The style method sets the style of the current subtitle.
The switch method sets the current subtitle URL and options.
textTrack gets the current text track.
activeCues gets the list of currently active cues.
cues gets the overall list of cues.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.subtitle.url = '/assets/sample/subtitle.srt'
art.subtitle.style({
color: 'red',
});
});
info
Manages the player's information panel, commonly used to view the current status of the player and video, such as version number, resolution, duration, etc.
ArtPlayer Documentation
Info Panel
Control the panel's visibility via art.info.show. The triggered event is named info (see the event documentation for details).
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.info.show = true;
setTimeout(() => {
art.info.show = false;
}, 3000);
});
Loading Layer
Manages the player's loading layer. The show property is used to set whether to display the loading layer. The toggle property is used to toggle the display of the loading layer.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.loading.show = true;
setTimeout(() => {
art.loading.show = false;
}, 1000);
});
Hotkey
Manages the player's hotkey functionality. The add method is used to add hotkeys. The remove method is used to remove hotkeys.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
function hotkeyEvent(event) {
console.info('click', event);
}
art.on('ready', () => {
art.hotkey.add(32, hotkeyEvent);
setTimeout(() => {
art.hotkey.remove(32, hotkeyEvent);
}, 5000);
});
Note: These hotkeys only take effect after the player gains focus (e.g., after clicking on the player).
Mask Layer
Manages the player's mask layer. The show property is used to set whether to display the mask layer. The toggle property is used to toggle the display of the mask layer.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.mask.show = false;
setTimeout(() => {
art.mask.show = true;
}, 1000);
});
Setting Panel
Manages the player's settings panel. The add method is used to dynamically add settings items. The remove method is used to dynamically remove settings items. The update method is used to dynamically update settings items. The show property is used to set whether to display all settings items. The toggle method is used to toggle the display of all settings items.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
flip: true,
playbackRate: true,
aspectRatio: true,
subtitleOffset: true,
});
art.on('ready', () => {
art.setting.show = true;
setTimeout(() => {
art.setting.show = false;
}, 1000);
});
For the Settings Panel, please refer to: /component/setting.html
Plugins
Manages the player's plugin functionality, with only the add method for dynamically adding plugins.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
function myPlugin(art) {
console.info(art);
return {
name: 'myPlugin',
something: 'something',
doSomething: function () {
console.info('doSomething');
},
};
}
art.on('ready', () => {
art.plugins.add(myPlugin);
});
Static Properties
Static Properties refer to the top-level properties mounted on the constructor function, which are very rarely used.
Instances
Returns an array of all player instances. This property can be useful when you need to manage multiple player instances simultaneously.
Example code:
console.info([...Artplayer.instances]);
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info([...Artplayer.instances]);
Version
Returns the version information of the player.
Example code:
console.info(Artplayer.version);
Env
Returns the environment variables of the player.
Example code:
console.info(Artplayer.env);
Build
Returns the build time of the player.
Example code:
console.info(Artplayer.build);
Config
Returns the default configuration for videos.
Example code:
console.info(Artplayer.config);
Utils
Returns the collection of utility functions for the player.
Example code:
console.info(Artplayer.utils);
For all utility functions, please refer to the following address: artplayer/types/utils.d.ts
Scheme
Returns the validation schema for player options.
Example code:
console.info(Artplayer.scheme);
Emitter
Returns the constructor function for the event emitter.
Example code:
console.info(Artplayer.Emitter);
Validator
Returns the validation function for options.
Example code:
console.info(Artplayer.validator);
KindOf
Returns the utility function for type detection.
Example code:
console.info(Artplayer.kindOf);
Html
Returns the html string required by the player.
Example code:
console.info(Artplayer.html);
Option
Returns the default options for the player.
Example code:
console.info(Artplayer.option);
Instance Events
Player events are divided into two types: native events (prefixed with video:) and custom events.
Listen to an event:
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('video:canplay', () => {
console.info('video:canplay');
});
Listen to an event only once:
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.once('video:canplay', () => {
console.info('video:canplay');
});
Manually trigger an event:
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.emit('focus');
Remove an event listener:
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
const onReady = () => {
console.info('ready');
art.off('ready', onReady);
}
art.on('ready', onReady);
For a complete list of events, please refer to: artplayer/types/events.d.ts
Ready Event
Triggered when the player is ready for the first time.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info('ready');
});
Restart Event
Triggered when the player switches URL and becomes playable.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.url = '/assets/sample/video.mp4'
});
art.on('restart', (url) => {
console.info('restart', url);
});
Pause Event
Triggered when the player is paused.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('pause', () => {
console.info('pause');
});
ArtPlayer Event Documentation
The following events are available in ArtPlayer. Each event can be bound using the `art.on()` method. The basic player setup is consistent across examples.
Event: pause
Triggered when the player pauses.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('pause', () => {
console.info('pause');
});
Event: play
Triggered when the player starts playing.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('play', () => {
console.info('play');
});
Event: hotkey
Triggered when a hotkey is pressed on the player. The event object contains details about the key press.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('hotkey', (event) => {
console.info('hotkey', event);
});
Event: destroy
Triggered when the player instance is destroyed. This example shows destroying the player in the ready event handler.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.destroy();
});
art.on('destroy', () => {
console.info('destroy');
});
Event: focus
Triggered when the player element gains focus.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('focus', (event) => {
console.info('focus', event);
});
Event: blur
Triggered when the player element loses focus.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('blur', (event) => {
console.info('blur', event);
});
Event: dblclick
Triggered when the player is double-clicked.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('dblclick', (event) => {
console.info('dblclick', event);
});
Event: click
Triggered when the player is clicked.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('click', (event) => {
console.info('click', event);
});
Event: error
Triggered when an error occurs while loading the video. The callback provides the error and a reconnectTime parameter.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/404.mp4',
});
art.on('error', (error, reconnectTime) => {
console.info(error, reconnectTime);
});
Event: hover
Triggered when the mouse enters or leaves the player area. The state parameter indicates 'enter' or 'leave'.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('hover', (state, event) => {
console.info('hover', state, event);
});
Event: mousemove
Triggered when the mouse moves over the player.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('mousemove', (event) => {
console.info('mousemove', event);
});
Event: resize
Triggered when the player's container dimensions change.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('resize', () => {
console.info('resize');
});
Event: view
Triggered when the player enters or leaves the browser viewport. The state parameter indicates the visibility.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('view', (state) => {
console.info('view', state);
});
Event: lock
Triggered when the screen lock state changes, primarily on mobile devices. Requires the lock option to be enabled.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lock: true,
});
art.on('lock', (state) => {
console.info('lock', state);
});
Event: aspectRatio
Triggered when the player's aspect ratio changes. Requires the aspectRatio and setting options to be enabled.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
aspectRatio: true,
setting: true,
});
art.on('aspectRatio', (aspectRatio) => {
console.info('aspectRatio', aspectRatio);
});
Event: autoHeight
Triggered when the player automatically adjusts its height, typically after calling the art.autoHeight() method.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.autoHeight();
});
art.on('autoHeight', (height) => {
console.info('autoHeight', height);
});
Event: autoSize
Triggered when the player automatically adjusts its size. Requires the autoSize option to be enabled.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoSize: true,
});
art.on('autoSize', () => {
console.info('autoSize');
});
Event: flip
Triggered when the video flip state changes. Requires the flip and setting options to be enabled.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
flip: true,
setting: true,
});
art.on('flip', (flip) => {
console.info('flip', flip);
});
Event: fullscreen
Triggered when the player enters or exits traditional window fullscreen mode. Requires the fullscreen option.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreen: true,
});
art.on('fullscreen', (state) => {
console.info('fullscreen', state);
});
Event: fullscreenError
Triggered when an error occurs while attempting to enter window fullscreen mode.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.fullscreen = true;
});
art.on('fullscreenError', (event) => {
console.info('fullscreenError', event);
});
Event: fullscreenWeb
Triggered when the player enters or exits web fullscreen mode (fullscreen within the browser). Requires the fullscreenWeb option.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreenWeb: true,
});
art.on('fullscreenWeb', (state) => {
console.info('fullscreenWeb', state);
});
Event: mini
Triggered when the player enters or exits mini-player mode.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.mini = true;
});
art.on('mini', (state) => {
console.info('mini', state);
});
Event: pip
Triggered when the player enters or exits picture-in-picture mode. Requires the pip option.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
pip: true,
});
art.on('pip', (state) => {
console.info('pip', state);
});
Event: screenshot
Triggered when a screenshot is captured. Requires the screenshot option. The callback receives the image as a Data URI.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
screenshot: true,
});
art.on('screenshot', (dataUri) => {
console.info('screenshot', dataUri);
});
Event: seek
Triggered when the playback time is sought, either by dragging the progress bar or calling a method.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('seek', (currentTime) => {
console.info('seek', currentTime);
});
Event: subtitleOffset
Triggered when the subtitle synchronization offset is changed. Requires the subtitleOffset option and a subtitle track.
Example code:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitleOffset: true,
subtitle: {
url: '/assets/sample/subtitle.srt',
},
setting: true,
});
ArtPlayer Event: subtitleOffset
Triggered when the subtitle offset changes.
Example usage:
art.on('subtitleOffset', (offset) => {
console.info('subtitleOffset', offset);
});
ArtPlayer Event: subtitleBeforeUpdate
Triggered before subtitles are updated.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitle: {
url: '/assets/sample/subtitle.srt',
},
});
art.on('subtitleBeforeUpdate', (cues) => {
console.info('subtitleBeforeUpdate', cues);
});
ArtPlayer Event: subtitleAfterUpdate
Triggered after subtitles are updated.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitle: {
url: '/assets/sample/subtitle.srt',
},
});
art.on('subtitleAfterUpdate', (cues) => {
console.info('subtitleAfterUpdate', cues);
});
ArtPlayer Event: subtitleLoad
Triggered when subtitles are loaded.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitle: {
url: '/assets/sample/subtitle.srt',
},
});
art.on('subtitleLoad', (option, cues) => {
console.info('subtitleLoad', cues, option);
});
ArtPlayer Event: info
Triggered when the info panel is shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('info', (state) => {
console.log(state);
});
ArtPlayer Event: layer
Triggered when custom layers are shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('layer', (state) => {
console.log(state);
});
ArtPlayer Event: loading
Triggered when the loader is shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('loading', (state) => {
console.log(state);
});
ArtPlayer Event: mask
Triggered when the mask layer is shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('mask', (state) => {
console.log(state);
});
ArtPlayer Event: subtitle
Triggered when the subtitle layer is shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('subtitle', (state) => {
console.log(state);
});
ArtPlayer Event: contextmenu
Triggered when the context menu is shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('contextmenu', (state) => {
console.log(state);
});
ArtPlayer Event: control
Triggered when the controls are shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('control', (state) => {
console.log(state);
});
ArtPlayer Event: setting
Triggered when the settings panel is shown or hidden.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
});
art.on('setting', (state) => {
console.log(state);
});
ArtPlayer Event: muted
Triggered when the mute state changes.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('muted', (state) => {
console.log(state);
});
ArtPlayer Event: keydown
Listens for keydown events from the document.
Example usage:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('keydown', (event) => {
console.log(event.code);
});
Video Element Events
The following are standard HTML5 video events that ArtPlayer can listen to.
video:canplay - The browser can start playing the media, but estimates there isn't enough data to play through to the end without having to stop for further buffering.
video:canplaythrough - The browser estimates it can play the media through to the end without stopping to buffer content.
video:complete - OfflineAudioContext rendering is complete.
video:durationchange - Triggered when the value of the duration property changes.
video:emptied - The media has become empty; for example, this event is sent when the media has already been loaded (or partially loaded), and the load() method is called to reload it.
video:ended - Playback has stopped because the media has reached its end point.
video:error - An error occurred while fetching media data, or the resource type is not a supported media format.
video:loadeddata - The first frame of the media has finished loading.
video:loadedmetadata - Metadata has been loaded.
video:pause - Playback has been paused.
video:play - Playback has begun.
video:playing - Playback is ready to start after having been paused or delayed due to lack of data.
video:progress - Periodically triggered while the browser is loading the resource.
video:ratechange - The playback rate has changed.
video:seeked - A seek operation has completed.
video:seeking - A seek operation has begun.
video:stalled - The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
video:suspend - Media data loading has been suspended.
video:timeupdate - The time indicated by the currentTime attribute has been updated.
video:volumechange - The volume has changed.
video:waiting - Playback has stopped due to temporary lack of data.
Global Properties
These global properties refer to the top-level properties mounted on the constructor. The property names are all in uppercase. They are subject to change in the future and are generally not used.
DEBUG - Whether to enable debug mode, which can print all built-in events of the video. Default is off.
Example usage:
Artplayer.DEBUG = true;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
STYLE - Returns the player style text.
Example usage:
console.log(Artplayer.STYLE);
CONTEXTMENU - Whether to enable the context menu. Default is on.
Example usage:
Artplayer.CONTEXTMENU = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
NOTICE_TIME - The display duration for notification messages, in milliseconds. Default is 2000.
Example usage:
Artplayer.NOTICE_TIME = 5000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
SETTING_WIDTH - The default width of the settings panel, in pixels. Default is 250.
Example usage:
Artplayer.SETTING_WIDTH = 300;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
loop: true,
flip: true,
playbackRate: true,
aspectRatio: true,
});
SETTING_ITEM_WIDTH - The default width of settings items in the settings panel, in pixels. Default is 200.
Example usage:
Artplayer.SETTING_ITEM_WIDTH = 300;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
loop: true,
flip: true,
playbackRate: true,
aspectRatio: true,
});
SETTING_ITEM_HEIGHT - The default height of settings items in the settings panel, in pixels. Default is 35.
Example usage:
Artplayer.SETTING_ITEM_HEIGHT = 300;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
loop: true,
flip: true,
playbackRate: true,
aspectRatio: true,
});
ArtPlayer provides several static properties that allow you to customize its behavior. These can be set before creating a new player instance.
SETTING_ITEM_HEIGHT
The height of each item in the settings panel, in pixels. The default is 40.
Example of setting a custom height and initializing a player with various settings enabled:
Artplayer.SETTING_ITEM_HEIGHT = 40;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
loop: true,
flip: true,
playbackRate: true,
aspectRatio: true,
});
RESIZE_TIME
The throttle time for the resize event, in milliseconds. The default is 200.
Example of setting a custom throttle time and listening for the resize event:
Artplayer.RESIZE_TIME = 500;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('resize', () => {
console.log('resize');
});
SCROLL_TIME
The throttle time for the scroll event, in milliseconds. The default is 200.
Example of setting a custom throttle time and listening for the scroll event:
Artplayer.SCROLL_TIME = 500;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('scroll', () => {
console.log('scroll');
});
SCROLL_GAP
The boundary tolerance distance for the view event, in pixels. The default is 50.
Example of setting a custom gap and listening for the scroll event:
Artplayer.SCROLL_GAP = 100;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('scroll', () => {
console.log('scroll');
});
AUTO_PLAYBACK_MAX
The maximum record count for the auto-playback feature. The default is 10.
Example of setting a custom maximum and enabling auto-playback:
Artplayer.AUTO_PLAYBACK_MAX = 20;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoPlayback: true,
});
AUTO_PLAYBACK_MIN
The minimum record duration for the auto-playback feature, in seconds. The default is 5.
Example of setting a custom minimum duration and enabling auto-playback:
Artplayer.AUTO_PLAYBACK_MIN = 10;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoPlayback: true,
});
AUTO_PLAYBACK_TIMEOUT
The hide delay duration for the auto-playback feature, in milliseconds. The default is 3000.
Example of setting a custom timeout and enabling auto-playback:
Artplayer.AUTO_PLAYBACK_TIMEOUT = 5000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoPlayback: true,
});
RECONNECT_TIME_MAX
The maximum number of automatic reconnection attempts when a connection error occurs. The default is 5.
Example of setting a custom maximum reconnection count:
Artplayer.RECONNECT_TIME_MAX = 10;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/404.mp4',
});
RECONNECT_SLEEP_TIME
The delay time for automatic reconnection when a connection error occurs, in milliseconds. The default is 1000.
Example of setting a custom reconnection delay:
Artplayer.RECONNECT_SLEEP_TIME = 3000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/404.mp4',
});
CONTROL_HIDE_TIME
The delay time in milliseconds for auto-hiding the bottom control bar. The default is 3000.
Example of setting a custom control hide delay:
Artplayer.CONTROL_HIDE_TIME = 5000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
DBCLICK_TIME
The delay time in milliseconds for double-click events. The default is 300.
Example of setting a custom double-click delay and listening for the event:
Artplayer.DBCLICK_TIME = 500;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('dblclick', () => {
console.log('dblclick');
});
DBCLICK_FULLSCREEN
On desktop, determines whether double-click toggles fullscreen mode. The default is true.
Example of disabling double-click fullscreen:
Artplayer.DBCLICK_FULLSCREEN = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
MOBILE_DBCLICK_PLAY
On mobile devices, determines whether double-click toggles play/pause. The default is true.
Example of disabling double-click play/pause on mobile:
Artplayer.MOBILE_DBCLICK_PLAY = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
MOBILE_CLICK_PLAY
On mobile devices, determines whether single-click toggles play/pause. The default is false.
Example of enabling single-click play/pause on mobile:
Artplayer.MOBILE_CLICK_PLAY = true;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
AUTO_ORIENTATION_TIME
On mobile devices, the delay time in milliseconds for automatic screen rotation. The default is 200.
Example of setting a custom orientation delay and enabling auto-orientation:
Artplayer.AUTO_ORIENTATION_TIME = 500;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoOrientation: true,
});
INFO_LOOP_TIME
The refresh interval in milliseconds for the information panel. The default is 1000.
Example of setting a custom refresh interval and showing the info panel:
Artplayer.INFO_LOOP_TIME = 2000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.info.show = true;
FAST_FORWARD_VALUE
On mobile devices, the speed multiplier for fast-forward during long-press. The default is 3.
Example of setting a custom fast-forward speed and enabling the feature:
Artplayer.FAST_FORWARD_VALUE = 5;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fastForward: true,
});
FAST_FORWARD_TIME
On mobile devices, the delay time in milliseconds for activating fast-forward during long-press. The default is 1000.
Example of setting a custom activation delay and enabling fast-forward:
Artplayer.FAST_FORWARD_TIME = 2000;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fastForward: true,
});
TOUCH_MOVE_RATIO
On mobile devices, the speed multiplier for seeking when swiping left/right. The default is 0.5.
Example of setting a custom seek sensitivity:
Artplayer.TOUCH_MOVE_RATIO = 1;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
VOLUME_STEP
The volume adjustment step for keyboard shortcuts. The default is 0.1.
Example of setting a custom volume step:
Artplayer.VOLUME_STEP = 0.2;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
SEEK_STEP
The seeking step in seconds for keyboard shortcuts. The default is 5.
Example of setting a custom seek step:
Artplayer.SEEK_STEP = 10;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
PLAYBACK_RATE
The built-in list of playback rates. The default is [0.5, 0.75, 1, 1.25, 1.5, 2].
Example of setting a custom playback rate list and enabling the feature in settings:
Artplayer.PLAYBACK_RATE = [0.5, 1, 2, 3, 4, 5];
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
playbackRate: true,
});
art.contextmenu.show = true;
art.setting.show = true;
ASPECT_RATIO
The built-in list of video aspect ratios. The default is ['default', '4:3', '16:9'].
Example of setting a custom aspect ratio list and enabling the feature in settings:
Artplayer.ASPECT_RATIO = ['default', '1:1', '2:1', '4:3', '6:5'];
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
aspectRatio: true,
});
art.contextmenu.show = true;
art.setting.show = true;
FLIP
The built-in list of video flip modes. The default is ['normal', 'horizontal', 'vertical'].
Example of setting a custom flip mode list and enabling the feature in settings:
Artplayer.FLIP = ['normal', 'horizontal'];
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
flip: true,
});
art.contextmenu.show = true;
art.setting.show = true;
FULLSCREEN_WEB_IN_BODY
Determines whether to mount the player under the body element during web fullscreen mode. The default is true.
Example of setting this property:
Artplayer.FULLSCREEN_WEB_IN_BODY = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
ArtPlayer Global Configuration
FULLSCREEN_WEB_IN_BODY
This setting determines whether fullscreen mode is applied to the entire web page body. By default, it is set to false.
Example:
Artplayer.FULLSCREEN_WEB_IN_BODY = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreenWeb: true,
});
LOG_VERSION
Sets whether to print the player version in the console. The default value is true.
Example:
Artplayer.LOG_VERSION = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
USE_RAF
Sets whether to use requestAnimationFrame for smoother animations, such as the progress bar. The default value is false.
Example:
Artplayer.USE_RAF = true;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
miniProgressBar: true,
});
REMOVE_SRC_WHEN_DESTROY
Determines whether to remove the video's src attribute and call load() to release media resources when the player is destroyed. The default is true. Set this to false if you want to preserve the video element's state and only remove the UI.
Example:
Artplayer.REMOVE_SRC_WHEN_DESTROY = false;
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
// Only destroys the UI, does not actively clear src
art.destroy();
Writing Plugins
Once you are familiar with the player's properties, methods, and events, writing plugins is straightforward. You can load plugins during player instantiation or add them afterward.
Loading a plugin during instantiation:
function myPlugin(art) {
console.info(art);
return {
name: 'myPlugin',
something: 'something',
doSomething: function () {
console.info('doSomething');
},
};
}
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
plugins: [myPlugin],
});
art.on('ready', () => {
console.info(art.plugins.myPlugin);
});
Loading a plugin after instantiation:
function myPlugin(art) {
console.info(art);
return {
name: 'myPlugin',
something: 'something',
doSomething: function () {
console.info('doSomething');
},
};
}
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.plugins.add(myPlugin);
art.on('ready', () => {
console.info(art.plugins.myPlugin);
});
Example Plugin: Displaying an Image Ad on Pause
This plugin shows an image ad when the video is paused and provides controls to hide or show it.
function adsPlugin(option) {
return (art) => {
art.layers.add({
name: 'ads',
html: `<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 available on the player instance.
play
Type: Function
Plays the video.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
art.on('ready', () => {
art.play();
});
pause
Type: Function
Pauses the video.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
art.on('ready', () => {
art.play();
setTimeout(() => {
art.pause();
}, 3000);
});
toggle
Type: Function
Toggles between play and pause.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
art.on('ready', () => {
art.toggle();
setTimeout(() => {
art.toggle();
}, 3000);
});
destroy
Type: Function
Parameter: Boolean
Destroys the player. Accepts a boolean parameter indicating whether to remove the player's HTML from the DOM after destruction. Defaults to true.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.destroy();
});
reset
Type: Function
Resets the player's video element by removing the current src and calling load(). Useful for manually releasing media resources or reinitializing the video tag in single-page applications. Note: The global configuration Artplayer.REMOVE_SRC_WHEN_DESTROY also triggers similar logic when destroy() is called.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
// Only reset the video, do not remove the interface
art.reset();
});
seek
Type: Setter
Parameter: Number
Seeks to a specific time in the video, in seconds.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.seek = 5;
});
forward
Type: Setter
Parameter: Number
Fast-forwards the video by a specified number of seconds.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.forward = 5;
});
backward
Type: Setter
Parameter: Number
Rewinds the video by a specified number of seconds.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.seek = 5;
setTimeout(() => {
art.backward = 2;
}, 3000);
});
volume
Type: Setter/Getter
Parameter: Number
Sets or gets the video volume. The value must be between 0 and 1.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.volume);
art.volume = 0.5;
console.info(art.volume);
});
url
Type: Setter/Getter
Parameter: String
Sets or gets the video URL.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
ArtPlayer Documentation
The following sections describe various properties and methods available on an ArtPlayer instance.
Setting the video URL directly.
Example:
art.on('ready', () => {
art.url = '/assets/sample/video.mp4?t=0';
});
Property: switch
Type: Setter
Parameter: String
Description: Sets the video URL. Similar to `art.url` when setting, but performs some optimization operations.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.seek = 10;
setTimeout(() => {
art.switch = '/assets/sample/video.mp4?t=0';
}, 3000);
});
Method: switchUrl
Type: Function
Parameter: String
Description: Sets the video URL. Similar to `art.url` when setting, but performs some optimization operations.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.seek = 10;
setTimeout(() => {
art.switchUrl('/assets/sample/video.mp4?t=0');
}, 3000);
});
Note: `art.switch` and `art.switchUrl` have the same functionality, but the `art.switchUrl` method returns a `Promise`. It `resolve`s when the new URL is playable and `reject`s when the new URL fails to load.
Method: switchQuality
Type: Function
Parameter: String
Description: Sets the video quality URL. Similar to `art.switchUrl`, but retains the previous playback progress.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.seek = 10;
setTimeout(() => {
art.switchQuality('/assets/sample/video.mp4?t=0');
}, 3000);
});
Property: muted
Type: Setter/Getter
Parameter: Boolean
Description: Sets and gets whether the video is muted.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.muted);
art.muted = true;
console.info(art.muted);
});
Property: currentTime
Type: Setter/Getter
Parameter: Number
Description: Sets and gets the current playback time of the video. Setting the time is similar to `seek`, but it does not trigger additional events.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.currentTime);
art.currentTime = 5;
console.info(art.currentTime);
});
Property: duration
Type: Getter
Description: Gets the duration of the video.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.duration);
});
Note: Some videos may not have a duration, such as live streams or videos that have not been fully decoded. In these cases, the obtained duration will be `0`.
Method: screenshot
Type: Function
Description: Downloads a screenshot of the current video frame. An optional parameter specifies the screenshot filename.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.screenshot('your-name');
});
Method: getDataURL
Type: Function
Description: Gets the `base64` URL of a screenshot of the current video frame. Returns a `Promise`.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', async () => {
const url = await art.getDataURL();
console.info(url)
});
Method: getBlobUrl
Type: Function
Description: Gets the `blob` URL of a screenshot of the current video frame. Returns a `Promise`.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', async () => {
const url = await art.getBlobUrl();
console.info(url);
});
Property: fullscreen
Type: Setter/Getter
Parameter: Boolean
Description: Sets and gets the player's window fullscreen state.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
position: 'right',
html: 'Fullscreen Switch',
click: function () {
art.fullscreen = !art.fullscreen;
},
},
],
});
Note: Due to browser security mechanisms, the page must have prior user interaction (e.g., the user has clicked on the page) before triggering window fullscreen.
Property: fullscreenWeb
Type: Setter/Getter
Parameter: Boolean
Description: Sets and gets the player's web page fullscreen state.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreenWeb: true,
});
art.on('ready', () => {
art.fullscreenWeb = true;
setTimeout(() => {
art.fullscreenWeb = false;
}, 3000);
});
Property: pip
Type: Setter/Getter
Parameter: Boolean
Description: Sets and gets the player's Picture-in-Picture mode.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
position: 'right',
html: 'PIP',
click: function () {
art.pip = !art.pip;
},
},
],
});
Note: Due to browser security mechanisms, the page must have prior user interaction (e.g., the user has clicked on the page) before triggering Picture-in-Picture.
Property: poster
Type: Setter/Getter
Parameter: String
Description: Sets and gets the video poster. The poster effect is only visible before video playback starts.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
poster: '/assets/sample/poster.jpg',
});
art.on('ready', () => {
console.info(art.poster);
art.poster = '/assets/sample/poster.jpg?t=0';
console.info(art.poster);
});
Property: mini
Type: Setter/Getter
Parameter: Boolean
Description: Sets and gets the player's mini mode.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.mini = true;
});
Property: playing
Type: Getter
Parameter: Boolean
Description: Gets whether the video is currently playing.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
art.on('ready', () => {
console.info(art.playing);
});
Property: state
Type: Setter/Getter
Parameter: String
Description: Gets or sets the player's current state. Supported values: `standard` (normal), `mini` (mini window), `pip` (picture-in-picture), `fullscreen` (fullscreen window), `fullscreenWeb` (webpage fullscreen).
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.state); // Default: standard
art.state = 'mini';
});
Method: autoSize
Type: Function
Description: Sets whether the video adapts its size automatically.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.autoSize();
});
Property: rect
Type: Getter
Description: Gets the player's dimensions and coordinate information.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
Here is the documentation reorganized into a clean, plain text format.
First, an example of how to access the player's rect property, which contains its dimensions and coordinates. The information is obtained via getBoundingClientRect.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(JSON.stringify(art.rect));
});
The following properties are getters that provide shortcut access to the rect object. bottom, top, left, right, x, and y correspond to the fields of the same name in a DOMRect. width and height represent the player's current visible width and height.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.width, art.height, art.left, art.top);
});
The flip property is both a setter and a getter. It controls the player's flip state and accepts a string parameter. Supported values are normal, horizontal, and vertical.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.flip);
art.flip = 'horizontal';
console.info(art.flip);
});
The playbackRate property is a setter and getter for the player's playback speed. It accepts a number parameter.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.playbackRate);
art.playbackRate = 2;
console.info(art.playbackRate);
});
The aspectRatio property is a setter and getter for the player's aspect ratio. It accepts a string parameter.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.aspectRatio);
art.aspectRatio = '16:9';
console.info(art.aspectRatio);
});
The autoHeight function is useful when your container has a defined width but an unknown height. It automatically calculates and sets the video height. You need to determine the appropriate timing to call this function.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.autoHeight();
});
art.on('resize', () => {
art.autoHeight();
});
The attr function dynamically gets and sets attributes of the video element. It accepts a string parameter for the attribute name.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.attr('playsInline'));
art.attr('playsInline', true);
console.info(art.attr('playsInline'));
});
The type property is a setter and getter for the video type. It accepts a string parameter.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.type);
art.type = 'm3u8';
console.info(art.type);
});
The theme property is a setter and getter for the player's theme color. It accepts a string parameter.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.info(art.theme);
art.theme = '#000';
console.info(art.theme);
});
The airplay function initiates AirPlay.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
position: 'right',
html: 'AirPlay',
click: function () {
art.airplay();
},
},
],
});
The loaded property is a getter that returns the proportion of the video that has been buffered, ranging from 0 to 1. It is often used with the video:timeupdate event.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('video:timeupdate', () => {
console.info(art.loaded);
});
The loadedTime property is a getter that returns the amount of media that has been buffered, in seconds. It is typically used alongside loaded to display detailed buffering progress.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('video:timeupdate', () => {
console.info(art.loadedTime);
});
The played property is a getter that returns the proportion of the video that has been played, ranging from 0 to 1. It is often used with the video:timeupdate event.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('video:timeupdate', () => {
console.info(art.played);
});
The proxy function is a proxy for DOM events, essentially handling addEventListener and removeEventListener. When using proxy to handle events, the event listener is automatically removed when the player is destroyed. This is strongly recommended to avoid memory leaks if you need DOM events to exist only for the duration of the player's lifecycle.
var container = document.querySelector('.artplayer-app');
var art = new Artplayer({
container: container,
url: '/assets/sample/video.mp4',
});
art.proxy(container, 'click', event => {
console.info(event);
});
The query function is a DOM query function similar to document.querySelector, but the search is scoped to the current player instance, preventing errors from duplicate class names.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.query('.art-video'));
The video property quickly returns the player's video element.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
console.info(art.video);
The cssVar function dynamically gets or sets CSS variables.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
console.log(art.cssVar('--art-theme'));
art.cssVar('--art-theme', 'green');
console.log(art.cssVar('--art-theme'));
});
The quality property is a setter that dynamically sets the list of available quality levels. It accepts an array parameter.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
quality: [
{
default: true,
html: 'SD 480P',
url: '/assets/sample/video.mp4',
},
{
html: 'HD 720P',
url: '/assets/sample/video.mp4',
},
],
});
art.on('ready', () => {
setTimeout(() => {
art.quality = [
{
default: true,
html: '1080P',
url: '/assets/sample/video.mp4',
},
{
html: '4K',
url: '/assets/sample/video.mp4',
},
];
}, 3000);
})
The thumbnails property is a setter and getter for dynamically setting thumbnails. It accepts an object parameter.
Example code for thumbnails would be placed here.
ArtPlayer Documentation
Thumbnails Example
This example shows how to set thumbnails for a video after the player is ready.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.on('ready', () => {
art.thumbnails = {
url: '/assets/sample/thumbnails.png',
number: 60,
column: 10,
};
});
subtitleOffset
Type: Setter/Getter
Parameter: Number
This property allows you to dynamically set the subtitle offset in seconds.
Example of setting a subtitle offset:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitle: {
url: '/assets/sample/subtitle.srt',
},
});
art.on('ready', () => {
art.subtitleOffset = 1;
});
Context Menu
Configuration
The contextmenu component can be configured with the following properties:
Property Type Description
disable Boolean Whether to disable the component
name String Unique component name for CSS class
index Number Component index for display priority
html String, Element Component DOM element
style Object Component style object
click Function Component click event
mounted Function Triggered after component mount
tooltip String Component tooltip text
Creation
You can create context menu items during player initialization.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
contextmenu: [
{
name: 'your-menu',
html: 'Your Menu',
click: function (...args) {
console.info(args);
art.contextmenu.show = false;
},
},
],
});
art.contextmenu.show = true;
// Get the Element of contextmenu by name
console.info(art.contextmenu['your-menu']);
Addition
You can add a context menu item after the player has been created.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.contextmenu.add({
name: 'your-menu',
html: 'Your Menu',
click: function (...args) {
console.info(args);
art.contextmenu.show = false;
},
});
art.contextmenu.show = true;
// Get the Element of contextmenu by name
console.info(art.contextmenu['your-menu']);
Removal
You can remove a context menu item by its name.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
contextmenu: [
{
name: 'your-menu',
html: 'Your Menu',
click: function (...args) {
console.info(args);
art.contextmenu.show = false;
},
},
],
});
art.contextmenu.show = true;
art.on('ready', () => {
setTimeout(() => {
// Delete the contextmenu by name
art.contextmenu.remove('your-menu')
}, 3000);
});
Update
You can update the properties of an existing context menu item.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
contextmenu: [
{
name: 'your-menu',
html: 'Your Menu',
click: function (...args) {
console.info(args);
art.contextmenu.show = false;
},
},
],
});
art.contextmenu.show = true;
art.on('ready', () => {
setTimeout(() => {
// Update the contextmenu by name
art.contextmenu.update({
name: 'your-menu',
html: 'Your New Menu',
})
}, 3000);
});
Controls
Configuration
Controls can be configured with the following properties:
Property Type Description
disable Boolean Whether to disable the control
name String Unique control name for CSS class identification
index Number Control index for display priority
html String, Element Control's DOM element
style Object Control style object
click Function Control click event handler
mounted Function Triggered after control is mounted
tooltip String Control tooltip text
position String 'left' or 'right' - controls display position
selector Array Array of selector list objects
onSelect Function Function triggered when selector item is clicked
Creation
You can define controls during the player's initialization.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
name: 'your-button',
index: 10,
position: 'left',
html: 'Your Button',
tooltip: 'Your Button',
style: {
color: 'red',
},
click: function (...args) {
console.info('click', args);
},
mounted: function (...args) {
console.info('mounted', args);
},
},
{
name: 'subtitle',
position: 'right',
html: 'Subtitle',
selector: [
{
default: true,
html: '<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
You can add a new control to the player after it has been created.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.controls.add({
name: 'button1',
index: 10,
position: 'left',
html: 'Your Button',
tooltip: 'Your Button',
style: {
color: 'red',
},
click: function (...args) {
console.info('click', args);
},
mounted: function (...args) {
console.info('mounted', args);
},
});
// Get the Element of control by name
console.info(art.controls['button1']);
Removal
You can remove a control by its name.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
name: 'button1',
index: 10,
position: 'right',
html: 'Your Button',
tooltip: 'Your Button',
style: {
color: 'red',
},
}
]
});
art.on('ready', () => {
setTimeout(() => {
// Delete the control by name
art.controls.remove('button1');
}, 3000);
});
Updating
You can update the properties of an existing control.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
controls: [
{
name: 'button1',
index: 10,
position: 'right',
html: 'Subtitle',
selector: [
{
default: true,
html: 'subtitle 01',
},
{
html: 'subtitle 02',
},
],
}
]
});
ArtPlayer Documentation: Controls Update Example
This example shows how to update a control after the player is ready. After a 3-second delay, it updates a control named 'button1', changing its position, HTML content, and adding a selector list.
art.on('ready', () => {
setTimeout(() => {
// Update the control by name
art.controls.update({
name: 'button1',
index: 10,
position: 'right',
html: 'New Subtitle',
selector: [
{
default: true,
html: 'new subtitle 01',
},
{
html: 'new subtitle 02',
},
],
});
}, 3000);
});
ArtPlayer Documentation: Layer Component
Layer Configuration
The following properties can be used when creating or updating a layer component.
Property Type Description
disable Boolean Whether to disable the component
name String Unique component name for CSS class
index Number Component index for display priority
html String, Element Component DOM element
style Object Component style object
click Function Component click event
mounted Function Triggered after component mount
tooltip String Component tooltip text
Layer Creation
This example shows how to add a layer during the initial Artplayer configuration. It creates a layer with an image, custom styling, and event handlers.
var img = '/assets/sample/layer.png';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
layers: [
{
name: 'potser',
html: `<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
This example shows how to add a layer after the Artplayer instance has been created, using the layers.add method.
var img = '/assets/sample/layer.png';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
art.layers.add({
name: 'potser',
html: `<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 its name after a delay, using the layers.remove method.
var img = '/assets/sample/layer.png';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
layers: [
{
name: 'potser',
html: `<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 shows how to update an existing layer's properties, such as its HTML content and style, using the layers.update method.
var img = '/assets/sample/layer.png';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
layers: [
{
name: 'potser',
html: `<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);
});
ArtPlayer Documentation: Settings Panel
Built-in Settings
To use the settings panel, set the 'setting' option to true. You can then enable specific built-in settings like flip, playbackRate, aspectRatio, and subtitleOffset.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
flip: true,
playbackRate: true,
aspectRatio: true,
subtitleOffset: true,
});
Creating Button Settings
A button in the settings panel can be configured with the following properties.
Property Type Description
html String, Element Element DOM
icon String, Element Element icon
onClick Function Element click event
width Number List width
tooltip String Tooltip text
This example creates a simple button setting with a custom icon and a click handler.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
settings: [
{
html: 'Button',
icon: '<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
A selection list in the settings panel can be configured with the following properties. The 'selector' array defines the list items.
Property Type Description
html String, Element Element DOM
icon String, Element Element icon
selector Array Element list
onSelect Function Element click event
width Number List width
tooltip String Tooltip text
This example creates two selection lists: one for subtitles and one for video quality. Each item in the selector can have a default state, custom HTML, and a data URL.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
settings: [
{
html: 'Subtitle',
width: 250,
tooltip: 'Subtitle 01',
selector: [
{
default: true,
html: '<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 documentation mentions the ability to create nested lists within the settings panel, but a specific code example was not provided in the source text.
ArtPlayer Documentation for AI Learning
This documentation covers the installation, usage, and configuration of ArtPlayer, with a focus on creating and managing settings.
Installation and Usage
You can install ArtPlayer via several package managers or include it directly via script tag.
Using npm:
npm install artplayer
Using yarn:
yarn add artplayer
Using pnpm:
pnpm add artplayer
Using a script tag in HTML:
<script src="path/to/artplayer.js"></script>
CDN Links
You can also load ArtPlayer from a CDN.
From jsdelivr.net:
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js
From unpkg.com:
https://unpkg.com/artplayer/dist/artplayer.js
Basic Usage Example
Here is a basic HTML example to get started with ArtPlayer.
<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 entirely on the size of its container element. You must define the width and height for your container.
For more detailed usage examples, you can visit the project's example directory.
Vue.js Integration Example
ArtPlayer can be integrated into a Vue.js application. Here is a component example.
First, create a reusable 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>
Then, use the component in your app.vue file:
<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: The Artplayer instance itself is not reactive. Manage its state through its own API methods.
Creating Settings
ArtPlayer allows you to add custom settings to its control panel. There are several types of settings you can create.
Creating a Multi-Level Selector Setting
This example shows how to create a setting with nested selectors.
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;
},
},
],
},
],
});
Creating a Toggle Button Setting
A toggle button setting has a switch that can be on or off. Here are its properties.
Property: html
Type: String, Element
Description: DOM element or text for the item.
Property: icon
Type: String, Element
Description: Icon for the item.
Property: switch
Type: Boolean
Description: The default state of the button (true for on, false for off).
Property: onSwitch
Type: Function
Description: The function called when the button is toggled.
Property: tooltip
Type: String
Description: The text shown when hovering over the button.
Here is an example of creating a toggle button for Picture-in-Picture (PIP) mode.
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;
},
},
],
});
Creating a Range Slider Setting
A range slider setting allows users to select a numeric value. Here are its properties.
Property: html
Type: String, Element
Description: DOM element or text for the item.
Property: icon
Type: String, Element
Description: Icon for the item.
Property: range
Type: Array
Description: An array defining the slider's state: [default_value, min_value, max_value, step].
Property: onRange
Type: Function
Description: Function triggered when the user finishes changing the slider.
Property: onChange
Type: Function
Description: Function triggered whenever the slider value changes.
Property: tooltip
Type: String
Description: The text shown when hovering over the slider.
The range array is structured as follows:
const range = [5, 1, 10, 1];
const value = range[0]; // The current/default value (5)
const min = range[1]; // The minimum value (1)
const max = range[2]; // The maximum value (10)
const step = range[3]; // The step increment (1)
Here is an example of creating a playback speed slider.
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 a Setting After Initialization
You can add a new setting to the player after it has been created using the `add` method.
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 a Setting
You can remove a setting by its unique `name` property using the `remove` method. In this example, the setting named 'slider' is removed after a 3-second delay.
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 a Setting
You can update the properties of an existing setting by its `name` using the `update` method. In this example, a slider setting is changed to a toggle button after 3 seconds.
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
React.js
Here is an example of using ArtPlayer in a React.js component.
Artplayer.jsx:
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>
}
app.jsx:
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 note: Artplayer is not reactive. Directly modifying the `option` prop in React.js will not update the player.
TypeScript
TypeScript definitions are automatically imported when you import Artplayer. Here are examples for different frameworks.
Vue.js:
<script setup>
import Artplayer from 'artplayer';
const art = shallowRef<Artplayer>(null);
art.value = new Artplayer();
</script>
React.js:
import Artplayer from 'artplayer';
const art = useRef<Artplayer>(null);
art.current = new Artplayer();
You can also import and use the Option type for better type safety.
Option:
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 the full TypeScript definitions, refer to the repository: packages/artplayer/types
JavaScript
If your JavaScript files lose TypeScript type hints, you can manually import the types using JSDoc comments.
For a variable:
/**
* @type {import("artplayer")}
*/
let art = null;
For a function parameter:
/**
* @param {import("artplayer")} art
*/
function getInstance(art) {
//
}
For a Vue.js component property:
export default {
data() {
return {
/**
* @type {import("artplayer")}
*/
art: null,
}
}
}
For the Option type:
/**
* @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 Browsers
The standard production build, artplayer.js, supports the latest version of Chrome. For compatibility with older browsers, use the legacy build.
Import the legacy version:
import Artplayer from 'artplayer/legacy'
You can also use it via a CDN:
From jsdelivr.net:
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.legacy.js
From unpkg.com:
https://unpkg.com/artplayer/dist/artplayer.legacy.js
The legacy build supports browsers as old as IE 11. If you need to support even older browsers, you can modify the build configuration and compile it yourself. Refer to the build script and the browserslist documentation for details.
ECMAScript Module
Starting from version 5.2.6, ArtPlayer and its plugins provide ESM versions with the .mjs extension.
Example using an import map in HTML:
<!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 userAgent
To manually adjust the player's UI for mobile detection, you can set a custom userAgent string. This feature is available from version 5.2.4.
Set the global variable `globalThis.CUSTOM_USER_AGENT` before importing the Artplayer script.
<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 the custom userAgent before loading the Artplayer library for it to take effect.
Language Settings
Important: From version 5.1.0, the core artplayer.js only includes Simplified Chinese (zh-cn) and English (en). Other languages must be imported manually. If a language is not matched, English will be displayed by default.
Default Languages
The default languages, 'en' and 'zh-cn', are built-in.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lang: 'zh-cn', // or 'en'
});
Importing Languages
Language files are available in the dist/i18n/ directory. You can import them as modules or via script tags.
Module import example:
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',
});
Script tag example:
<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
You can define a custom language directly in the options.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lang: 'your-lang',
i18n: {
'your-lang': {
Play: 'Your Play'
},
},
});
Modifying Languages
You can override the strings of any language, including the default ones.
import zhTw from 'artplayer/i18n/zh-tw';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
i18n: {
// Change the default 'zh-cn' language
'zh-cn': {
Play: 'Your Play'
},
// Change the imported 'zh-tw' language
'zh-tw': {
...zhTw,
Play: 'Your Play'
},
},
});
Basic Options
container
- Type: String, Element
- Default: #artplayer
The DOM container where the player is mounted.
To initialize an ArtPlayer instance, you must provide a container element. This can be a CSS selector string or a direct DOM element reference.
```js
var art = new Artplayer({
container: '.artplayer-app',
// container: document.querySelector('.artplayer-app'),
url: '/assets/sample/video.mp4',
});
```
You may need to define the size of the container element. You can set explicit width and height.
```css
.artplayer-app {
width: 400px;
height: 300px;
}
```
Alternatively, you can use the CSS aspect-ratio property.
```css
.artplayer-app {
aspect-ratio: 16/9;
}
```
Note: Among all configuration options, only the `container` is required.
URL
Type: String
Default: ''
This is the video source URL.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
```
If the video URL is not known at initialization time, you can set it asynchronously later.
```js
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
Type: String
Default: ''
A unique identifier for the player, currently used for the playback resumption feature (`autoplayback`).
```js
var art = new Artplayer({
id: 'your-url-id',
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
});
```
ONREADY
Type: Function
Default: undefined
You can pass a function as the second parameter to the constructor. This function is called once the player is fully initialized and the video is ready to play, similar to the 'ready' event.
```js
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 event listener method:
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
art.on('ready', () => {
art.play();
});
```
Note: Inside the `onReady` callback function, `this` refers to the player instance. However, if you use an arrow function, `this` will not be bound to the player instance.
POSTER
Type: String
Default: ''
The poster image URL, displayed when the player is initialized but before video playback begins.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
poster: '/assets/sample/poster.jpg',
});
```
THEME
Type: String
Default: '#f00'
The theme color for the player, used for elements like the progress bar and highlights.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
theme: '#ffad00',
});
```
VOLUME
Type: Number
Default: 0.7
The default volume level for the player.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
volume: 0.5,
});
```
Note: The player caches the last volume setting. On the next initialization (e.g., page refresh), it will use this cached value.
ISLIVE
Type: Boolean
Default: false
Enables live streaming mode, which hides the progress bar and playback time.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
isLive: true,
});
```
MUTED
Type: Boolean
Default: false
Determines if the player starts in a muted state.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
muted: true,
});
```
AUTOPLAY
Type: Boolean
Default: false
Determines if the video should start playing automatically.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoplay: true,
muted: true,
});
```
Note: For a video to autoplay immediately on page load, `muted` must be set to `true`. Please refer to browser autoplay policies for more details.
AUTOSIZE
Type: Boolean
Default: false
Automatically adjusts the player size to fill the container and hide black bars, similar to the CSS property `object-fit: cover;`.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoSize: true,
});
```
AUTOMINI
Type: Boolean
Default: false
Automatically switches to mini-player mode when the player scrolls out of the browser viewport.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoMini: true,
});
```
LOOP
Type: Boolean
Default: false
Enables looping of the video.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
loop: true,
});
```
FLIP
Type: Boolean
Default: false
Enables the video flip functionality, which appears in the Settings Panel and Context Menu.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
flip: true,
setting: true,
});
```
PLAYBACKRATE
Type: Boolean
Default: false
Enables the video playback rate functionality, which appears in the Settings Panel and Context Menu.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
playbackRate: true,
setting: true,
});
```
ASPECTRATIO
Type: Boolean
Default: false
Enables the video aspect ratio functionality, which appears in the Settings Panel and Context Menu.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
aspectRatio: true,
setting: true,
});
```
SCREENSHOT
Type: Boolean
Default: false
Adds a video screenshot button to the bottom control bar.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
screenshot: true,
});
```
Note: Due to browser security policies, screenshot capture may fail if the video is served from a different origin (cross-origin) than the website.
SETTING
Type: Boolean
Default: false
Adds a toggle button for the Settings Panel to the bottom control bar.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
setting: true,
});
```
HOTKEY
Type: Boolean
Default: true
Enables keyboard hotkeys for player control.
```js
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
hotkey: true,
});
```
Hotkeys
The following hotkeys are available for controlling the player. Note that these hotkeys only take effect after the player gains focus, for example by clicking on it.
Hotkey: Up arrow
Description: Increase volume
Hotkey: Down arrow
Description: Decrease volume
Hotkey: Left arrow
Description: Seek forward
Hotkey: Right arrow
Description: Seek backward
Hotkey: Space
Description: Toggle play/pause
Configuration Options
pip
Type: Boolean
Default: false
This setting determines whether to display the Picture-in-Picture toggle button in the bottom control bar.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
pip: true,
});
mutex
Type: Boolean
Default: true
When multiple players exist on the same page, this setting controls whether only one player is allowed to play at a time.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
mutex: true,
});
backdrop
Type: Boolean
Default: true
This enables or disables a backdrop blur effect for UI overlays like the settings panel, creating a frosted glass appearance. It may impact performance on some devices or older browsers.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
backdrop: false, // Disable frosted glass effect
});
fullscreen
Type: Boolean
Default: false
This setting determines whether to display the Window Fullscreen button in the bottom control bar.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreen: true,
});
fullscreenWeb
Type: Boolean
Default: false
This setting determines whether to display the Webpage Fullscreen button in the bottom control bar.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreenWeb: true,
});
subtitleOffset
Type: Boolean
Default: false
When enabled, this adds a subtitle timing offset control to the Settings Panel, allowing adjustments within a range of -5 to +5 seconds.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
subtitleOffset: true,
subtitle: {
url: '/assets/sample/subtitle.srt',
},
setting: true,
});
miniProgressBar
Type: Boolean
Default: false
When enabled, a mini progress bar will appear when the player loses focus but is still playing.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
miniProgressBar: true,
});
useSSR
Type: Boolean
Default: false
This setting enables Server-Side Rendering (SSR) mount mode, useful for pre-rendering the player's HTML. You can access the required HTML via Artplayer.html.
Example:
var $container = document.querySelector('.artplayer-app');
$container.innerHTML = Artplayer.html;
var art = new Artplayer({
container: $container,
url: '/assets/sample/video.mp4',
useSSR: true,
});
playsInline
Type: Boolean
Default: true
This controls whether to use playsInline mode for video playback on mobile devices.
Example:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
playsInline: true,
});
layers
Type: Array
Default: []
This array is used to initialize custom layers on the player.
Example:
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 detailed Component Configuration, please refer to: /component/layers.html
settings
Type: Array
Default: []
This array is used to initialize a custom settings panel. Note that the main 'setting' option must also be set to true.
Example:
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 detailed Settings Panel configuration, please refer to: /component/setting.html
contextmenu
Type: Array
Default: []
This array is used to initialize custom items in the player's right-click context menu.
Example:
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 detailed Component Configuration, please refer to: /component/contextmenu.html
controls
Type: Array
Default: []
This array is used to initialize custom controls in the bottom control bar.
Example:
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 detailed Component Configuration, please refer to: /component/controls.html
quality
Type: Array
Default: []
This array defines the available quality options for the Quality Selection list in the control bar. Each object in the array uses the following properties:
Property: default, Type: Boolean, Description: Marks this as the default quality.
Property: html, Type: String, Description: The display name for the quality.
Property: url, Type: String, Description: The video URL for this quality.
Example:
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
Type: Array
Default: []
This array is used to define highlight markers that will be displayed on the player's progress bar.
Here is the reorganized documentation for learning the ArtPlayer AI model, presented in a clean, readable plain text format with all code and configuration preserved.
The highlight option allows you to mark specific points in the video timeline with text annotations. Each highlight is defined by a time in seconds and a text string.
Property: time
Type: Number
Description: Highlight time (in seconds)
Property: text
Type: String
Description: Highlight text
Example configuration with multiple highlights:
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. A plugin is a function that receives the art instance and returns an object with a name and custom methods.
Example of defining 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. This requires a sprite image containing all thumbnails.
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
Basic configuration example:
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 are vtt, srt, and 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 with an SRT subtitle and 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 Attributes
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 adding inline playback attributes for mobile:
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 replacing the 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: For all icon definitions, refer to artplayer/types/icons.d.ts.
Type
Type: String
Default: ''
Used to specify the video format. It needs to be used in conjunction with customType. By default, the video format is determined by the suffix of the video URL (e.g., .m3u8, .mkv, .ts). However, sometimes the video URL lacks the correct suffix, so explicit specification is necessary.
Example specifying an HLS stream:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.m3u8',
type: 'm3u8',
});
Note: The player can parse suffixes like /assets/sample/video.m3u8 but not query parameters like /assets/sample/video?type=m3u8. If you use customType, it is best to also specify the type.
Custom Type
Type: Object
Default: {}
Matches based on the video's type and delegates video decoding to third-party programs. The handler function receives three parameters: video (the video DOM element), url (the video URL), and art (the current instance).
Example setting up a custom handler for HLS streams:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.m3u8',
customType: {
m3u8: function (video, url, art) {
// Your custom playback logic here
},
},
});
Language
Type: String
Default: navigator.language.toLowerCase()
The default display language. Currently supported: en, zh-cn.
Example setting the player to English:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lang: 'en',
});
Note: For more language settings, see /start/i18n.html.
Internationalization (i18n)
Type: Object
Default: {}
Custom i18n configuration. This configuration will be deeply merged with the built-in i18n.
Example adding a new language:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lang: 'your-lang',
i18n: {
'your-lang': {
Play: 'Your Play'
},
},
});
Example modifying an existing language:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
i18n: {
'zh-cn': {
Play: 'Your Play'
},
'zh-tw': {
Play: 'Your Play'
},
},
});
Note: For more language settings, see /start/i18n.html.
Lock
Type: Boolean
Default: false
Whether to display a lock button on mobile devices to hide the bottom control bar.
Example enabling the lock feature:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
lock: true,
});
Gesture
Type: Boolean
Default: true
Whether to enable gesture events on the video element on mobile devices.
Example disabling gestures:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
gesture: false,
});
Fast Forward
Type: Boolean
Default: false
Whether to add a long-press video fast-forward feature on mobile devices.
Example enabling fast-forward:
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fastForward: true,
});
Here is the documentation reorganized into a clean, plain text format.
Initialization Example
This is a basic example of creating an ArtPlayer instance.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fastForward: true,
});
autoPlayback
Type: Boolean
Default: false
Determines whether to use the automatic playback feature, which resumes video playback from the last watched position.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
id: 'your-url-id',
autoPlayback: true,
});
Note: By default, the player uses the video URL as the key to cache playback progress. If the same video can be accessed via different URLs, you must provide a unique 'id' to serve as the cache key.
autoOrientation
Type: Boolean
Default: false
When enabled on mobile web, this will automatically rotate the player during fullscreen mode based on the video's dimensions and the screen size.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoOrientation: true,
});
airplay
Type: Boolean
Default: false
Controls the visibility of the AirPlay button. Note that this feature is only supported in certain browsers.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
airplay: true,
});
cssVar
Type: Object
Default: {}
This object allows you to override the player's built-in CSS variables for custom styling.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
cssVar: {
// Define custom CSS variables here
},
});
For a full list of available CSS variables, please refer to the official type definition file: artplayer/types/cssVar.d.ts
proxy
Type: function
Default: undefined
This function can return a third-party HTMLCanvasElement or HTMLVideoElement. A common use case is to proxy an existing video DOM element for the player to use.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
proxy: () => document.createElement('video')
});
===== Type Definitions Overview =====
artplayer-plugin-ads.d.ts
This plugin adds advertising capabilities to ArtPlayer, supporting video, image, and HTML ad formats.
interface Option {
/**
* 广告源文本,支持视频链接、图片链接、HTML文本
* Ad source text, supports video links, image links, HTML text
*/
source: string
/**
* 知名广告的类型:'video' | 'image' | 'html'
* Known ad type: 'video' | 'image' | 'html'
*/
type: 'video' | 'image' | 'html'
/**
* 广告必看的时长,单位为秒
* Mandatory ad viewing duration in seconds
*/
playDuration?: number
/**
* 广告总的时长,单位为秒
* Total ad duration in seconds
*/
totalDuration?: number
/**
* 视频广告是否默认静音
* Whether video ads are muted by default
*/
muted?: boolean
}
interface Ads {
name: 'artplayerPluginAds'
/**
* 跳过广告
* Skip ad
*/
skip: () => void
/**
* 暂停广告
* Pause ad
*/
pause: () => void
/**
* 播放广告
* Play ad
*/
play: () => void
}
// The plugin is a function that takes an Option object and returns a function that takes an Artplayer instance, returning an Ads instance.
declare const artplayerPluginAds: (option: Option) => (art: Artplayer) => Ads
export default artplayerPluginAds
export = artplayerPluginAds
export as namespace artplayerPluginAds;
artplayer-plugin-ambilight.d.ts
This plugin creates an ambient light effect around the video player based on the video content.
interface Option {
blur?: string
opacity?: number
frequency?: number
zIndex?: number
duration?: number
}
interface Result {
name: 'artplayerPluginAmbilight'
start: () => void
stop: () => void
}
declare const artplayerPluginAmbilight: (option: Option) => (art: Artplayer) => Result
export default artplayerPluginAmbilight
export = artplayerPluginAmbilight
export as namespace artplayerPluginAmbilight;
artplayer-plugin-asr.d.ts
This plugin provides Automatic Speech Recognition (ASR) functionality, capturing audio chunks for subtitle generation.
interface AudioChunk {
pcm: ArrayBuffer
wav: ArrayBuffer
}
interface AsrPluginOption {
length?: number
interval?: number
sampleRate?: number
autoHideTimeout?: number
onAudioChunk?: (chunk: AudioChunk) => void | Promise<void>
}
interface AsrPluginInstance {
name: 'artplayerPluginAsr'
stop: () => void
hide: () => void
append: (subtitle: string) => void
}
declare function artplayerPluginAsr(option?: AsrPluginOption): (art: Artplayer) => AsrPluginInstance
export default artplayerPluginAsr
export = artplayerPluginAsr
export as namespace artplayerPluginAsr;
artplayer-plugin-audio-track.d.ts
This plugin allows adding an external audio track to synchronize with the video playback.
interface Option {
/**
* Audio track URL
*/
url: string
/**
* Time offset in seconds between video and audio
* Positive value means audio plays ahead of video
* Negative value means audio plays behind video
* @default 0
*/
offset?: number
/**
* Synchronization threshold in seconds
* @default 0.3
*/
sync?: number
}
interface Result {
name: 'artplayerPluginAudioTrack'
/**
* The audio element
*/
audio: HTMLAudioElement
/**
* Update option
*/
update: (option: Option) => void
}
declare const artplayerPluginAudioTrack: (option: Option) => (art: Artplayer) => Result
export default artplayerPluginAudioTrack
export = artplayerPluginAudioTrack
export as namespace artplayerPluginAudioTrack;
artplayer-plugin-auto-thumbnail.d.ts
This plugin automatically generates thumbnails for the video seek bar.
interface Option {
url?: string
width?: number
number?: number
scale?: number
}
interface Result {
name: 'artplayerPluginAutoThumbnail'
}
declare const artplayerPluginAutoThumbnail: (option: Option) => (art: Artplayer) => Result
export default artplayerPluginAutoThumbnail
export = artplayerPluginAutoThumbnail
export as namespace artplayerPluginAutoThumbnail;
artplayer-plugin-chapter.d.ts
This plugin adds chapter markers to the video timeline.
type Chapters = {
start: number
end: number
title: string
}[]
interface Option {
chapters?: Chapters
}
interface Result {
name: 'artplayerPluginChapter'
update: (option: Option) => void
}
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 Google Chromecast support for casting video to external devices.
interface Option {
url?: string
sdk?: string
icon?: string
mimeType?: string
}
interface Chromecast {
name: 'artplayerPluginChromecast'
}
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 applies a mask to danmaku (bullet comments) to prevent them from obscuring important content in the video, often using computer vision.
interface Option {
solutionPath?: string
modelSelection?: number
smoothSegmentation?: boolean
minDetectionConfidence?: number
minTrackingConfidence?: number
selfieMode?: boolean
drawContour?: boolean
foregroundThreshold?: number
opacity?: number
maskBlurAmount?: number
}
interface Result {
name: 'artplayerPluginDanmukuMask'
start: () => Promise<void>
stop: () => void
}
declare const artplayerPluginDanmukuMask: (option?: Option) => (art: Artplayer) => Result
export default artplayerPluginDanmukuMask
export = artplayerPluginDanmukuMask
export as namespace artplayerPluginDanmukuMask;
artplayer-plugin-danmuku.d.ts
This is the core danmaku (bullet comment) plugin with extensive configuration for display, behavior, and styling.
export type Mode = 0 | 1 | 2
export type Danmuku
= | Danmu[]
| string // URL
| (() => Promise<Danmu[]>)
| Promise<Danmu[]>
export interface Slider {
min?: number
max?: number
steps?: {
name?: string
value?: number | string
show?: boolean
}[]
}
export interface Danmu {
/**
* 弹幕文本
* Danmaku text
*/
text: string
/**
* 弹幕发送模式: 0: 滚动,1: 顶部,2: 底部
* Danmaku send mode: 0: scroll, 1: top, 2: bottom
*/
mode?: Mode
/**
* 弹幕颜色
* Danmaku color
*/
color?: string
/**
* 弹幕出现的时间,单位为秒
* Danmaku appearance time in seconds
*/
time?: number
/**
* 弹幕是否有描边, 默认为 false
* Whether the danmaku has a border, default is false
*/
border?: boolean
/**
* 弹幕自定义样式
* Danmaku custom style
*/
style?: Partial<CSSStyleDeclaration>
}
export interface Option {
/**
* 弹幕数据: 函数,数组,Promise,URL
* Danmaku data: function, array, Promise, URL
*/
danmuku: Danmuku
/**
* 弹幕持续时间,范围在[1 ~ 10]
* Danmaku duration, range [1 ~ 10]
*/
speed?: number
/**
* 弹幕上下边距,支持像素数字和百分比
* Danmaku top and bottom margin, supports pixel numbers and percentages
*/
margin?: [number | `${number}%`, number | `${number}%`]
/**
* 弹幕透明度,范围在[0 ~ 1]
* Danmaku opacity, range [0 ~ 1]
*/
opacity?: number
/**
* 默认弹幕颜色,可以被单独弹幕项覆盖
* Default danmaku color, can be overridden by individual danmaku items
*/
color?: string
/**
* 弹幕模式: 0: 滚动,1: 顶部,2: 底部
* Danmaku mode: 0: scroll, 1: top, 2: bottom
*/
mode?: Mode
/**
* 弹幕可见的模式
* Visible danmaku modes
*/
modes?: Mode[]
/**
* 弹幕字体大小,支持像素数字和百分比
* Danmaku font size, supports pixel numbers and percentages
*/
fontSize?: number | `${number}%`
/**
* 弹幕是否防重叠
* Whether danmaku prevents overlap
*/
antiOverlap?: boolean
/**
* 是否同步播放速度
* Whether to synchronize with playback speed
*/
synchronousPlayback?: boolean
/**
* 弹幕发射器挂载点, 默认为播放器控制栏中部
* Danmaku emitter mount point, defaults to the middle of the player control bar
*/
mount?: HTMLDivElement | string
/**
* 是否开启弹幕热度图
* Whether to enable danmaku heatmap
*/
heatmap?:
| boolean
| {
xMin?: number
xMax?: number
yMin?: number
yMax?: number
scale?: number
opacity?: number
minHeight?: number
sampling?: number
smoothing?: number
flattening?: number
}
/**
* 当播放器宽度小于此值时,弹幕发射器置于播放器底部
* When player width is less than this value, the danmaku emitter is placed at the bottom of the player
*/
width?: number
/**
* 热力图数据
* Heatmap data
*/
points?: { time: number, value: number }[]
/**
* 弹幕载入前的过滤器,只支持返回布尔值
* Filter before danmaku loads, only supports returning boolean
*/
filter?: (danmu: Danmu) => boolean
/**
* 弹幕发送前的过滤器,支持返回 Promise
* Filter before danmaku is sent, supports returning Promise
*/
beforeEmit?: (danmu: Danmu) => boolean | Promise<boolean>
/**
* 弹幕显示前的过滤器,支持返回 Promise
* Filter before danmaku is displayed, supports returning Promise
*/
beforeVisible?: (danmu: Danmu) => boolean | Promise<boolean>
/**
* 弹幕是否可见
* Whether danmaku is visible
*/
visible?: boolean
/**
* 是否开启弹幕发射器
* Whether to enable the danmaku emitter
*/
emitter?: boolean
/**
* 弹幕输入框最大长度, 范围在[1 ~ 1000]
* Danmaku input box maximum length, range [1 ~ 1000]
*/
maxLength?: number
/**
* 输入框锁定时间,范围在[1 ~ 60]
* Input box lock time, range [1 ~ 60]
*/
lockTime?: number
/**
* 弹幕主题,只在自定义挂载时生效
* Danmaku theme, only effective with custom mounting
*/
theme?: 'light' | 'dark'
/**
* 不透明度配置项
* Opacity configuration item
*/
OPACITY?: Slider
/**
* 弹幕速度配置项
* Danmaku speed configuration item
*/
SPEED?: Slider
/**
* 显示区域配置项
* Display area configuration item
*/
MARGIN?: Slider
/**
* 弹幕字号配置项
* Danmaku font size configuration item
*/
FONT_SIZE?: Slider
/**
* 颜色列表配置项
* Color list configuration item
*/
COLOR?: string[]
}
export interface Result {
name: 'artplayerPluginDanmuku'
/**
* 发送一条实时弹幕
* Send a real-time danmaku
*/
emit: (danmu: Danmu) => Result
/**
* 重载弹幕源,或者切换新弹幕
* Reload danmaku source, or switch to new danmaku
*/
load: (danmuku?: Danmuku) => Promise<Result>
/**
* 实时改变弹幕配置
* Change danmaku configuration in real time
*/
config: (option: Option) => Result
/**
* 隐藏弹幕层
* Hide danmaku layer
*/
hide: () => Result
/**
* 显示弹幕层
* Show danmaku layer
*/
show: () => Result
/**
* 挂载弹幕输入框
* Mount danmaku input box
*/
mount: (el?: HTMLDivElement | string) => void
/**
* 重置弹幕
* Reset danmaku
*/
reset: () => Result
/**
* 弹幕配置
* Danmaku configuration
*/
option: Option
/**
* 是否隐藏弹幕层
* Whether the danmaku layer is hidden
*/
isHide: boolean
/**
* 是否弹幕层停止状态
* Whether the danmaku layer is in stopped state
*/
isStop: boolean
}
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 appears to provide control interfaces for DASH (Dynamic Adaptive Streaming over HTTP) playback. The declaration file is incomplete in the provided input.
artplayer-plugin-dash-control.d.ts
This file defines a plugin for controlling DASH (Dynamic Adaptive Streaming over HTTP) quality and audio settings in ArtPlayer.
interface Config {
control?: boolean
setting?: boolean
title?: string
auto?: string
getName?: (level: object) => string
}
The Config interface defines options for a quality or audio control panel.
- `control`: Whether to show the control element (e.g., a button in the control bar).
- `setting`: Whether to include this option in the player's settings menu.
- `title`: The display title for this setting.
- `auto`: A label for an "Auto" or default selection.
- `getName`: A function that takes a quality/audio level object and returns a display name for it.
declare const artplayerPluginDashControl: (option: { quality?: Config, audio?: Config }) => (art: Artplayer) => {
name: 'artplayerPluginDashControl'
update: () => void
}
The plugin is a function that takes an options object. This object can have `quality` and/or `audio` properties, each of type `Config`. It returns another function that takes an `Artplayer` instance and returns a plugin object.
- `name`: Identifies the plugin.
- `update`: A method to manually refresh the control's state, useful if the available quality/audio levels change dynamically.
export default artplayerPluginDashControl
export = artplayerPluginDashControl
export as namespace artplayerPluginDashControl;
The plugin is exported for use in different module systems (ES modules, CommonJS) and as a global variable.
===== artplayer-plugin-document-pip.d.ts =====
This file defines a plugin for using the Document Picture-in-Picture (PiP) API with ArtPlayer.
interface Option {
width?: number
height?: number
placeholder?: string
fallbackToVideoPiP?: boolean
}
The Option interface configures the PiP window.
- `width` / `height`: The initial dimensions of the PiP window.
- `placeholder`: A string (likely a URL or CSS value) for a placeholder image.
- `fallbackToVideoPiP`: If the Document PiP API is not supported, attempt to use the standard Video element PiP API instead.
interface Result {
name: 'artplayerPluginDocumentPip'
isSupported: boolean
isActive: boolean
open: () => void
close: () => void
toggle: () => void
}
The plugin returns an object with these properties and methods.
- `name`: Identifies the plugin.
- `isSupported`: Boolean indicating if the Document PiP API is available in the current browser.
- `isActive`: Boolean indicating if the PiP window is currently open.
- `open`: Opens the PiP window.
- `close`: Closes the PiP window.
- `toggle`: Toggles the PiP window open or closed.
declare const artplayerPluginDocumentPip: (option: Option) => (art: Artplayer) => Result
The plugin function takes an `Option` object and returns a function that takes an `Artplayer` instance and returns the `Result` object.
export default artplayerPluginDocumentPip
export = artplayerPluginDocumentPip
export as namespace artplayerPluginDocumentPip;
===== artplayer-plugin-hls-control.d.ts =====
This file defines a plugin for controlling HLS (HTTP Live Streaming) quality and audio settings in ArtPlayer. Its structure is identical to the DASH control plugin.
interface Config {
control?: boolean
setting?: boolean
title?: string
auto?: string
getName?: (level: object) => string
}
declare const artplayerPluginHlsControl: (option: { quality?: Config, audio?: Config }) => (art: Artplayer) => {
name: 'artplayerPluginHlsControl'
update: () => void
}
export default artplayerPluginHlsControl
export = artplayerPluginHlsControl
export as namespace artplayerPluginHlsControl;
===== artplayer-plugin-jassub.d.ts =====
This file defines a plugin for rendering ASS/SSA subtitles using the JASSUB (libass) library in ArtPlayer.
export interface JassubOption {
workerUrl: string
wasmUrl: string
modernWasmUrl: string
subUrl?: string
subContent?: string
timeOffset?: number
debug?: boolean
prescaleFactor?: number
prescaleHeightLimit?: number
maxRenderHeight?: number
fonts?: string[] | Uint8Array[]
availableFonts?: Record<string, Uint8Array | string>
fallbackFont?: string
useLocalFonts?: boolean
libassMemoryLimit?: number
libassGlyphLimit?: number
[key: string]: any
}
The JassubOption interface configures the subtitle renderer. Key required properties are the URLs for the Web Worker and WebAssembly files.
- `subUrl` / `subContent`: Provide the subtitle data via URL or direct string content.
- `fonts`: An array of font URLs or binary data to load.
- `availableFonts`: A map of font names to their data, pre-loaded for use.
- Various performance and rendering tuning options like `prescaleFactor`, `libassMemoryLimit`.
export interface JassubInstance {
resize: (force?: boolean, width?: number, height?: number, top?: number, left?: number) => Promise<void>
setVideo: (video: HTMLVideoElement) => Promise<void>
destroy: () => Promise<void>
[key: string]: any
}
The JassubInstance interface represents the underlying subtitle renderer object, providing methods to control its lifecycle and positioning.
interface Result {
name: 'artplayerPluginJassub'
instance: JassubInstance
}
The plugin returns an object containing its name and a reference to the `JassubInstance`, allowing direct access to the renderer's methods.
declare const artplayerPluginJassub: (option: JassubOption) => (art: Artplayer) => Result
export default artplayerPluginJassub
export = artplayerPluginJassub
export as namespace artplayerPluginJassub;
===== artplayer-plugin-multiple-subtitles.d.ts =====
This file defines a plugin for managing multiple subtitle tracks in ArtPlayer.
declare const artplayerPluginMultipleSubtitles: (option: {
subtitles: {
url?: string
name?: string
type?: 'vtt' | 'srt' | 'ass'
encoding?: string
onParser?: (...args: object[]) => object
}[]
}) => (art: Artplayer) => {
name: 'multipleSubtitles'
}
The plugin takes an option object with a `subtitles` array. Each item in the array defines a subtitle track.
- `url`: The source URL of the subtitle file.
- `name`: The display name for the track.
- `type`: The format of the subtitle file (WebVTT, SubRip, or ASS/SSA).
- `encoding`: The text encoding of the file (e.g., 'utf-8').
- `onParser`: A custom function to parse the subtitle data; receives the raw data and should return a parsed object.
The plugin returns a simple object with its name.
export default artplayerPluginMultipleSubtitles
export = artplayerPluginMultipleSubtitles
export as namespace artplayerPluginMultipleSubtitles;
===== artplayer-plugin-vast.d.ts =====
This file defines a plugin for integrating VAST (Video Ad Serving Template) ads, typically using Google IMA (Interactive Media Ads), into ArtPlayer.
declare global {
interface Window {
artplayerPluginVast?: typeof artplayerPluginVast
}
}
This extends the global Window interface to optionally include the plugin as a property, allowing for global script access.
type PlayUrlFn = (url: string, config?: any) => void
type PlayResFn = (res: string, config?: any) => void
These are function types for playing an ad by URL (`PlayUrlFn`) or by a VAST response resource (`PlayResFn`).
interface VastPluginContext {
art: Artplayer
ima: any
imaPlayer: Player | null
playUrl: PlayUrlFn
playRes: PlayResFn
init: () => Player
adsRenderingSettings: any
playerOptions: PlayerOptions
container: HTMLDivElement | null
}
The `VastPluginContext` object is passed to the plugin's option function. It provides:
- The ArtPlayer instance (`art`).
- References to the IMA SDK (`ima`) and the IMA player instance (`imaPlayer`).
- Helper functions to play ads (`playUrl`, `playRes`).
- An `init` function to set up the IMA player.
- Configuration objects for ads and the player.
- The DOM container element for the ads.
export type ArtplayerPluginVastOption = (params: VastPluginContext) => void | Promise<void>
The plugin's option is not a configuration object, but a *function*. This function receives the fully constructed `VastPluginContext` and is responsible for setting up ad events, loading ad tags, etc. It can be async.
export interface ArtplayerPluginVastInstance {
name: 'artplayerPluginVast'
destroy?: () => void
}
The plugin instance returned to ArtPlayer. It includes a `destroy` hook for cleanup.
declare function artplayerPluginVast(
option: ArtplayerPluginVastOption,
): (art: Artplayer) => ArtplayerPluginVastInstance
The main plugin function. It takes the setup function (`ArtplayerPluginVastOption`) and returns the standard plugin factory function.
export default artplayerPluginVast
export = artplayerPluginVast
export as namespace artplayerPluginVast;
===== artplayer-plugin-vtt-thumbnail.d.ts =====
This file defines a plugin for displaying preview thumbnails on the progress bar using a WebVTT (Web Video Text Tracks) cue file.
declare const artplayerPluginVttThumbnail: (option: { vtt?: string, style?: Partial<CSSStyleDeclaration> }) => (
art: Artplayer,
) => {
name: 'artplayerPluginVttThumbnail'
}
The plugin takes an option object.
- `vtt`: The URL of the WebVTT file that contains the thumbnail cues (mapping time ranges to image URLs).
- `style`: Optional CSS styles to apply to the thumbnail preview element.
The plugin returns an object with its name.
export default artplayerPluginVttThumbnail
export = artplayerPluginVttThumbnail
export as namespace artplayerPluginVttThumbnail;
===== artplayer-plugin-websr.d.ts =====
This file defines a plugin for real-time video upscaling/super-resolution in the browser using a WebAssembly/WebWorker model.
interface Option {
compare?: boolean
networkSize?: 'small' | 'medium' | 'large'
weightsBaseUrl?: string
workerUrl?: string
videoScale?: number
}
Configuration for the upscaler.
- `compare`: Whether to show a side-by-side comparison of original vs upscaled video.
- `networkSize`: The size of the neural network model, affecting quality and performance.
- `weightsBaseUrl`: Base URL for loading the model weight files.
- `workerUrl`: URL of the Web Worker script.
- `videoScale`: The scaling factor (e.g., 2 for 2x upscale).
interface Result {
name: 'artplayerPluginWebsr'
upscaler: any
update: (option: Option) => void
}
The plugin returns its name, a reference to the internal `upscaler` object, and an `update` method to change configuration on the fly.
declare const artplayerPluginWebsr: (option?: Option) => (art: Artplayer) => Result
export default artplayerPluginWebsr
export = artplayerPluginWebsr
export as namespace artplayerPluginWebsr;
===== artplayer-proxy-canvas.d.ts =====
This file defines a utility that proxies video playback through an HTMLCanvasElement, allowing for frame-by-frame manipulation.
type Option = (ctx: CanvasRenderingContext2D, video: HTMLVideoElement) => void
The `Option` is a function (a render callback). It receives the canvas's 2D context and the source video element. This function is called repeatedly (e.g., on `requestAnimationFrame`) to draw each video frame onto the canvas, enabling custom filters or effects.
type Result = HTMLCanvasElement
The utility returns the canvas element that is now displaying the processed video.
declare const artplayerProxyCanvas: (option?: Option) => (art: Artplayer) => Result
The main function. If no `option` (render callback) is provided, it likely just copies the video frames to the canvas. It returns a factory function that takes an Artplayer instance and returns the proxy canvas.
export default artplayerProxyCanvas
export = artplayerProxyCanvas
export as namespace artplayerProxyCanvas;
===== artplayer-proxy-mediabunny.d.ts =====
This file defines a proxy utility that uses the MediaBunny library (or similar logic) to handle media playback, offering features like precise loading control and AV sync.
interface Option {
/**
* Timeout for loading media in milliseconds
* @default 0
*/
loadTimeout?: number
/**
* Interval for timeupdate events in milliseconds
* @default 250
*/
timeupdateInterval?: number
/**
* Audio-video synchronization tolerance in seconds
* @default 0.12
*/
avSyncTolerance?: number
/**
* Whether to drop late video frames
* @default false
*/
dropLateFrames?: boolean
/**
* Poster image URL
*/
poster?: string
/**
* Media source (URL, Blob, or ReadableStream)
*/
source?: string | Blob | ReadableStream<Uint8Array>
/**
* Check if server supports range requests before loading
* @default false
*/
preflightRange?: boolean
/**
* Initial volume (0-1)
* @default 0.7
*/
volume?: number
/**
* Initial muted state
* @default false
*/
muted?: boolean
/**
* Autoplay
* @default false
*/
autoplay?: boolean
/**
* Loop playback
* @default false
*/
loop?: boolean
/**
* Cross-origin setting
*/
crossOrigin?: string
}
The Option interface provides detailed control over media loading and playback behavior, with JSDoc comments explaining each property.
type Result = HTMLCanvasElement
Similar to `artplayerProxyCanvas`, this utility also outputs a canvas element, which serves as the video render target for the proxied media.
declare const artplayerProxyMediabunny: (option?: Option) => (art: Artplayer) => Result
export default artplayerProxyMediabunny
export = artplayerProxyMediabunny
export as namespace artplayerProxyMediabunny;
===== artplayer-tool-iframe.d.ts =====
This file defines a utility class for secure, promise-based communication between a parent page and an ArtPlayer instance embedded within an iframe.
interface Message {
type: string
data: any
id?: number
}
The structure of messages sent between the window and iframe.
declare class ArtplayerToolIframe {
constructor(option: { iframe: HTMLIFrameElement, url: string })
The constructor takes the target iframe element and a URL. The URL is likely used for origin validation or initial setup.
static iframe: boolean
static postMessage(message: Message): void
static onMessage(event: MessageEvent & { data: Message }): void
static inject(): void
Static members. `iframe: boolean` likely indicates if the code is running inside the iframe. `inject()` is called inside the iframe to set up the message listener. `postMessage` and `onMessage` are static handlers.
readonly promises: Record<number, { resove: (...args: any[]) => any, reject: (...args: any[]) => any }>
readonly injected: boolean
readonly destroyed: boolean
readonly $iframe: HTMLIFrameElement
readonly url: string
readonly messageCallback: (...args: any[]) => any
Instance properties. `promises` maps message IDs to promise callbacks for request/response patterns. `injected` and `destroyed` track state.
onMessage(event: MessageEvent & { data: Message }): void
postMessage(message: Message): Promise<any>
commit<T extends (...args: any[]) => any>(callback: T): Promise<ReturnType<T>>
message(callback: (...args: any[]) => any): void
destroy(): void
Instance methods.
- `onMessage`: Handles incoming messages.
- `postMessage`: Sends a message and returns a promise that resolves with the response.
- `commit`: A helper that sends a function (as a string) to be executed in the other context and returns its result.
- `message`: Sets a general callback for all incoming messages.
- `destroy`: Cleans up event listeners.
}
export default ArtplayerToolIframe
export = artplayerToolIframe
export as namespace artplayerToolIframe;
===== artplayer.d.ts (partial) =====
This is a fragment from the main ArtPlayer type definitions, showing a utility object.
export interface Utils {
isBrowser: boolean
userAgent: string
isMobile: boolean
isSafari: boolean
isIOS: boolean
isIOS13: boolean
}
The `Utils` interface contains boolean flags and strings for feature and environment detection, useful for writing conditional code for different browsers or platforms.
Here are the TypeScript declaration files for ArtPlayer's APIs, presented as plain text with developer explanations.
UTILITY FUNCTIONS
These are helper functions provided by ArtPlayer for DOM manipulation, event handling, and common utilities.
query: <T extends Element = Element>(selector: string, parent?: Document | HTMLElement) => T | null
// Selects a single DOM element. Returns null if not found.
// Example: query<HTMLVideoElement>('video', container)
queryAll: <T extends Element = Element>(selector: string, parent?: Document | HTMLElement) => T[]
// Selects all matching DOM elements. Returns empty array if none found.
addClass: (target: HTMLElement, className: string) => void
removeClass: (target: HTMLElement, className: string) => void
hasClass: (target: HTMLElement, className: string) => boolean
// Standard CSS class manipulation methods.
append: (target: HTMLElement, child: HTMLElement | string) => Element | ChildNode
remove: (target: HTMLElement) => HTMLElement
replaceElement: (newChild: HTMLElement, oldChild: HTMLElement) => HTMLElement
siblings: (target: HTMLElement) => HTMLElement[]
inverseClass: (target: HTMLElement, className: string) => void
// DOM manipulation methods for adding, removing, replacing elements and toggling classes.
createElement: <K extends keyof HTMLElementTagNameMap>(tag: K) => HTMLElementTagNameMap[K]
// Creates a typed HTML element with proper TypeScript inference.
setStyle: <T extends keyof CSSStyleDeclaration>(
element: HTMLElement,
key: T,
value: string | CSSStyleDeclaration[T],
) => HTMLElement
// Sets a single CSS style property with type safety.
setStyles: (element: HTMLElement, styles: Partial<CSSStyleDeclaration>) => HTMLElement
// Sets multiple CSS style properties at once.
getStyle: {
(element: HTMLElement, key: keyof CSSStyleDeclaration, numberType?: true): number
(element: HTMLElement, key: keyof CSSStyleDeclaration, numberType: false): string
}
// Gets computed style values. Can return as number (parsed) or string (raw).
setStyleText: (id: string, cssText: string) => void
// Injects CSS text into a style element with the given ID.
getRect: (el: HTMLElement) => { top: number, left: number, width: number, height: number }
// Gets element's bounding rectangle.
tooltip: (target: HTMLElement, msg: string, pos?: string) => void
// Creates a tooltip attached to an element.
isInViewport: (target: HTMLElement, offset?: number) => boolean
// Checks if element is visible in viewport.
includeFromEvent: (event: Event, target: HTMLElement) => boolean
// Checks if event target is within the specified element.
srtToVtt: (srtText: string) => string
vttToBlob: (vttText: string) => string
assToVtt: (assText: string) => string
// Subtitle format conversion utilities.
getExt: (url: string) => string
// Extracts file extension from URL.
download: (url: string, name: string) => void
// Triggers file download.
loadImg: (url: string, scale?: number) => Promise<HTMLImageElement>
// Loads image with optional scaling.
errorHandle: <T extends boolean>(condition: T, msg: string) => T extends true ? T : never
// Type-safe error handling that throws if condition is false.
def: (obj: object, name: string, value: unknown) => void
has: (obj: object, name: PropertyKey) => boolean
get: (obj: object, name: PropertyKey) => PropertyDescriptor | undefined
// Object property utilities similar to Object.defineProperty.
mergeDeep: <T extends object[]>(...args: T) => T[number]
// Deep merges multiple objects.
sleep: (ms: number) => Promise<void>
// Returns a promise that resolves after specified milliseconds.
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>
// Standard debounce and throttle implementations for event handlers.
clamp: (num: number, a: number, b: number) => number
// Restricts number between min and max values.
secondToTime: (second: number) => string
// Converts seconds to time string (HH:MM:SS).
escape: (str: string) => string
// Escapes HTML special characters.
capitalize: (str: string) => string
// Capitalizes first letter of string.
getIcon: (key?: string, html?: string | HTMLElement) => HTMLElement
// Gets icon element, either from built-in icons or custom HTML.
getComposedPath: (event: Event) => EventTarget[]
// Gets event path for shadow DOM compatibility.
supportsFlex: () => boolean
// Feature detection for flexbox support.
TEMPLATE INTERFACE
Contains references to all DOM elements in the player's template structure.
export interface Template {
readonly html: string
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 $controlsCenter: 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
}
SUBTITLE INTERFACE
Configuration for subtitle tracks.
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
/**
* Whether use escape, default true
*/
escape?: boolean
/**
* Change the vtt text
*/
onVttLoad?: (vtt: string) => string
}
SETTING INTERFACE
Configuration for player settings menu items.
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
}
SETTING OPTION INTERFACE
Internal representation of setting items with DOM references.
export interface SettingOption extends Omit<Setting, 'html' | 'icon' | 'tooltip'> {
html: string
icon: string | undefined
tooltip: string | undefined
$item: HTMLDivElement
$icon: HTMLDivElement | undefined
$html: HTMLDivElement
$tooltip: HTMLDivElement | undefined
$switch: HTMLDivElement | undefined
$range: HTMLInputElement | undefined
$parent: SettingOption | undefined
$parents: SettingOption[]
$option: SettingOption[]
$events: Array<() => void>
$formatted: boolean
}
QUALITY INTERFACE
Configuration for video quality options.
export interface Quality {
/**
* Whether the default is selected
*/
default?: boolean
/**
* Html string of quality
*/
html: string | HTMLElement
/**
* Video quality url
*/
url: string
}
TYPE ALIASES
Common type definitions used throughout the player.
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'
PLAYER CLASS
Main player class with getters and setters for player state and properties.
export declare class Player {
get aspectRatio(): AspectRatio
set aspectRatio(ratio: AspectRatio)
// Controls video aspect ratio.
get state(): State
set state(state: State)
// Current player state (standard, mini, pip, etc.).
get type(): CustomType
set type(name: CustomType)
// Video MIME type or custom type.
get playbackRate(): PlaybackRate
set playbackRate(rate: PlaybackRate)
// Playback speed multiplier.
get currentTime(): number
set currentTime(time: number)
// Current playback time in seconds.
get duration(): number
// Total video duration in seconds.
get played(): number
// Amount of video played in seconds.
get playing(): boolean
// Whether video is currently playing.
get flip(): Flip
set flip(state: Flip)
// Video flip state (normal, horizontal, vertical).
get fullscreen(): boolean
set fullscreen(state: boolean)
// Native fullscreen state.
get fullscreenWeb(): boolean
set fullscreenWeb(state: boolean)
// Web page fullscreen state.
get loaded(): number
// Amount of video loaded as percentage (0-1).
get loadedTime(): number
// Amount of video loaded in seconds.
get mini(): boolean
set mini(state: boolean)
// Mini player mode state.
get pip(): boolean
set pip(state: boolean)
// Picture-in-picture mode state.
get poster(): string
set poster(url: string)
// Poster image URL.
get rect(): DOMRect
// Player's bounding rectangle.
get bottom(): number
get height(): number
get left(): number
get right(): number
get top(): number
get width(): number
get x(): number
get y(): number
// Individual position and dimension properties.
set seek(time: number)
get seek(): number
// Alias for currentTime, used for seeking.
}
The ArtPlayer class provides the main API for controlling video playback and player configuration.
export class Artplayer {
// Sets the forward jump time in seconds
set forward(time: number)
// Gets the forward jump time in seconds
get forward(): number
// Sets the backward jump time in seconds
set backward(time: number)
// Gets the backward jump time in seconds
get backward(): number
// Gets the current video URL
get url(): string
// Sets the video URL
set url(url: string)
// Gets the current volume percentage (0-1)
get volume(): number
// Sets the volume percentage (0-1)
set volume(percentage: number)
// Gets whether audio is muted
get muted(): boolean
// Sets audio mute state
set muted(state: boolean)
// Gets the current theme color
get theme(): string
// Sets the theme color
set theme(theme: string)
// Gets the subtitle offset time in seconds
get subtitleOffset(): number
// Sets the subtitle offset time in seconds
set subtitleOffset(time: number)
// Gets the current switch URL
get switch(): string
// Sets the switch URL for video switching
set switch(url: string)
// Gets the available quality options
get quality(): Quality[]
// Sets the quality options
set quality(quality: Quality[])
// Gets the thumbnails configuration
get thumbnails(): Thumbnails
// Sets the thumbnails configuration
set thumbnails(thumbnails: Thumbnails)
// Pauses video playback
pause(): void
// Starts video playback, returns a promise
play(): Promise<void>
// Toggles between play and pause states
toggle(): void
// Gets or sets custom attributes on the player element
attr(key: string, value?: unknown): unknown
// Gets or sets CSS custom properties
cssVar<T extends keyof CssVar>(key: T, value?: CssVar[T]): CssVar[T]
// Switches to a new video URL
switchUrl(url: string): Promise<void>
// Switches video quality by URL
switchQuality(url: string): Promise<void>
// Gets the video as a data URL
getDataURL(): Promise<string>
// Gets the video as a blob URL
getBlobUrl(): Promise<string>
// Takes a screenshot of the current video frame
screenshot(name?: string): Promise<string>
// Initiates AirPlay streaming
airplay(): void
// Automatically resizes the player to fit its container
autoSize(): void
// Automatically adjusts player height
autoHeight(): void
// Resets the player to initial state
reset(): void
}
// CustomType defines supported video formats and allows for custom format extensions
export type CustomType
= | 'flv'
| 'm3u8'
| 'hls'
| 'ts'
| 'mpd'
| 'torrent'
| (string & Record<never, never>)
// Thumbnails interface defines configuration for video preview thumbnails
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
}
// 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 | undefined
/**
* Custom plugin list
*/
plugins?: ((this: Artplayer, art: Artplayer) => unknown | Promise<unknown>)[]
/**
* 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]
}>>
/**
* 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 | Promise<unknown>
>
>
}
// Icons interface defines all icon elements used in the player UI
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
}
// I18nKeys defines supported language codes with extensibility for custom languages
type I18nKeys
= | 'en'
| 'zh-cn'
| 'zh-tw'
| 'pl'
| 'cs'
| 'es'
| 'fa'
| 'fr'
| 'id'
| 'ru'
| 'tr'
| 'ar'
| 'vi'
| (string & Record<never, never>)
// I18nValue defines all translatable text keys used throughout the player interface
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
}
// I18n type defines the structure for internationalization support with partial overrides
export type I18n = Partial<Record<I18nKeys, Partial<I18nValue>>>
// Module declaration for importing language files from the i18n directory
declare module 'artplayer/i18n/*' {
const lang: Partial<I18nValue>
// @ts-expect-error TS2666
export default lang
}
// Bar type defines the different progress bar segments in the player
export type Bar = 'loaded' | 'played' | 'hover'
The Events interface defines all the events that can be emitted by the ArtPlayer instance. Each property key is the event name, and its value is a tuple type describing the arguments passed to the event listener.
export interface 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:resize': [event: Event]
'window:scroll': [event: Event]
'window:orientationchange': [event: Event]
'video:abort': [event: Event]
'video:canplay': [event: Event]
'video:canplaythrough': [event: Event]
'video:complete': [event: Event]
'video:durationchange': [event: Event]
'video:emptied': [event: Event]
'video:encrypted': [event: Event]
'video:ended': [event: Event]
'video:error': [error: Error]
'video:loadeddata': [event: Event]
'video:loadedmetadata': [event: Event]
'video:loadstart': [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]
'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: KeyboardEvent]
'destroy': []
'subtitleOffset': [offset: number]
'subtitleBeforeUpdate': [cue: VTTCue]
'subtitleAfterUpdate': [cue: VTTCue]
'subtitleLoad': [cues: VTTCue[], option: Subtitle]
'focus': [event: Event]
'blur': [event: Event]
'dblclick': [event: Event]
'click': [event: Event]
'hover': [state: boolean, event: Event]
'mousemove': [event: Event]
'resize': []
'view': [state: boolean]
'lock': [state: boolean]
'aspectRatio': [aspectRatio: AspectRatio]
'autoHeight': [height: number]
'autoSize': [size: { width: number, height: number }]
'ready': []
'airplay': []
'raf': []
'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, time: number]
'restart': [url: string]
'muted': [state: boolean]
'setBar': [type: Bar, percentage: number, event?: Event | undefined]
'keydown': [event: KeyboardEvent]
}
The CssVar interface defines a set of CSS custom properties (variables) used to theme and style the ArtPlayer UI. These variables control colors, sizes, spacing, and other visual aspects.
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
}
The Config interface defines a readonly structure that categorizes the properties, methods, events, and prototypes that ArtPlayer can proxy from the underlying video element. This is used for internal management and validation.
export interface Config {
readonly properties: readonly [
'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',
]
readonly methods: readonly ['addTextTrack', 'canPlayType', 'load', 'play', 'pause']
readonly events: readonly [
'abort',
'canplay',
'canplaythrough',
'durationchange',
'emptied',
'ended',
'error',
'loadeddata',
'loadedmetadata',
'loadstart',
'pause',
'play',
'playing',
'progress',
'ratechange',
'seeked',
'seeking',
'stalled',
'suspend',
'timeupdate',
'volumechange',
'waiting',
]
readonly prototypes: readonly [
'width',
'height',
'videoWidth',
'videoHeight',
'poster',
'webkitDecodedFrameCount',
'webkitDroppedFrameCount',
'playsInline',
'webkitSupportsFullscreen',
'webkitDisplayingFullscreen',
'onenterpictureinpicture',
'onleavepictureinpicture',
'disablePictureInPicture',
'cancelVideoFrameCallback',
'requestVideoFrameCallback',
'getVideoPlaybackQuality',
'requestPictureInPicture',
'webkitEnterFullScreen',
'webkitEnterFullscreen',
'webkitExitFullScreen',
'webkitExitFullscreen',
]
}
The Selector interface defines the structure for an item within a dropdown or selection component, such as a settings menu item.
export interface Selector {
/**
* Whether the default is selected
*/
default?: boolean
/**
* Html string of selector
*/
html: string | HTMLElement
/**
* Value of selector item
*/
value?: string | number
/**
* Allow custom properties
*/
[key: string]: any
}
The Component interface represents an instance of a UI component (like a button or control) within ArtPlayer. It provides methods to manage the component's visibility and lifecycle.
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 | ((art: Artplayer) => ComponentOption)) => HTMLElement | undefined
/**
* Dynamic remove a component by name
*/
remove: (name: string) => void
/**
* Dynamic update a component
*/
update: (option: ComponentOption) => HTMLElement | undefined
}
The ComponentOption interface defines the configuration object used to create or update a UI component. It includes the component's content, behavior, and lifecycle hooks.
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, used in controls for dropdowns or menus.
* Each selector item typically includes a label and a value.
*/
selector?: Selector[]
/**
* Callback when a selector item is clicked, used in controls.
* Provides the ArtPlayer instance, the clicked selector item, its HTML element, and the event.
*/
onSelect?: (this: Artplayer, selector: Selector, element: HTMLElement, event: Event) => void
}
// Export all major types for external use.
export type {
Config,
Events,
I18n,
Icons,
Option,
Player,
Setting,
SettingOption,
Subtitle,
Template,
Utils,
}
// The main ArtPlayer class, extending the base Player class.
export default class Artplayer extends Player {
// Constructor: initializes the player with an option object and an optional ready callback.
constructor(option: Option, readyCallback?: (this: Artplayer, art: Artplayer) => unknown)
// Static properties: global across all ArtPlayer instances.
static readonly instances: Artplayer[] // Array of all active ArtPlayer instances.
static readonly version: string // Current version string.
static readonly env: 'development' | 'production' // Build environment.
static readonly build: string // Build identifier or timestamp.
static readonly config: Config // Global configuration object.
static readonly utils: Utils // Utility functions.
static readonly scheme: Record<keyof Option, unknown> // Schema for option validation.
static readonly Emitter: new (...args: unknown[]) => unknown // Event emitter constructor.
static readonly validator: <T extends object>(option: T, scheme: object) => T // Validates options against a scheme.
static readonly kindOf: (item: unknown) => string // Type detection utility.
static readonly html: Artplayer['template']['html'] // HTML template string.
static readonly option: Option // Default option object.
// Static constants: configuration defaults for the player.
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: state flags and identifiers for a single player.
readonly id: number // Unique identifier for this instance.
readonly option: Option // The option object used to create this instance.
readonly isLock: boolean // Whether the player is locked (e.g., during loading).
readonly isReady: boolean // Whether the player is fully initialized.
readonly isFocus: boolean // Whether the player has focus.
readonly isInput: boolean // Whether an input element within the player is focused.
readonly isRotate: boolean // Whether the video is rotated (e.g., for mobile orientation).
readonly isDestroy: boolean // Whether the player has been destroyed.
// Optional properties for external libraries (e.g., for streaming formats).
flv?: unknown
m3u8?: unknown
hls?: unknown
ts?: unknown
mpd?: unknown
torrent?: unknown
// Event handling methods: on, once, emit, and off.
// These allow binding, triggering, and removing event listeners.
// Generic versions for typed events and fallback for custom string events.
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 shortcuts to commonly accessed properties.
query: Artplayer['template']['query'] // Query selector within the player's template.
proxy: Artplayer['events']['proxy'] // Event proxy utility.
video: Artplayer['template']['$video'] // Reference to the video element.
// Internal event storage: maps event names to arrays of listener functions and contexts.
e: { [K in keyof Events]?: { fn: (...args: Events[K]) => unknown, ctx: unknown }[] }
// Lifecycle methods: destroy removes the player, reset returns it to initial state.
destroy(removeHtml?: boolean): void
reset(): void
// Template property: provides HTML and DOM querying for the player's UI.
readonly template: {
get html(): string // Returns the HTML string of the player's template.
query: <T extends Element = Element>(selector: string) => T | null // Queries elements within the template.
} & Template // Extends with additional template-related methods.
// Events property: manages event listeners and global event binding.
readonly events: {
proxy: {
// Proxies an event listener, returning a removal function. Can handle single or multiple event names.
(target: EventTarget, eventName: string, handler: (event: Event) => void, options?: boolean | AddEventListenerOptions): () => void
(target: EventTarget, eventName: string[], handler: (event: Event) => void, options?: boolean | AddEventListenerOptions): Array<() => void>
}
hover: (element: HTMLElement, mouseenter?: (event: Event) => any, mouseleave?: (event: Event) => any) => void // Binds hover events.
remove: (destroyEvent: () => void) => void // Removes a specific event listener.
destroy: () => void // Removes all event listeners.
bindGlobalEvents: (source?: { window?: Window, document?: Document }) => void // Binds global window/document events.
}
// Storage property: manages persistent settings (e.g., volume, playback speed) via localStorage.
readonly storage: {
name: string // Storage key prefix.
settings: Record<string, unknown> // Current settings in memory.
get: {
(key: string): unknown // Gets a value by key.
(): Record<string, unknown> // Gets all settings.
}
set: (key: string, value: unknown) => void // Sets a value.
del: (key: string) => void // Deletes a key.
clear: () => void // Clears all settings.
}
// Icons property: contains SVG icon strings for UI elements.
readonly icons: Icons
// i18n property: handles internationalization and language switching.
readonly i18n: {
languages: I18n // All available language packs.
language: Partial<Record<string, string>> // Current language dictionary.
init: () => void // Initializes i18n with default language.
get: (key: string) => string // Gets a translated string by key.
update: (language: Partial<I18n>) => void // Updates the language pack.
}
// Notice property: manages temporary notification messages.
readonly notice: {
timer: number | null // Timer ID for auto-hiding.
get show(): boolean // Returns whether a notice is currently showing.
set show(msg: string | Error | false | '') // Shows a notice (string or Error) or hides it (false or empty string).
destroy: () => void // Clears any active notice.
}
// Layers, controls, and contextmenu: UI components that can be added or removed.
// Each is a Record of HTML elements by name, extended with Component methods (add, remove, show, hide).
readonly layers: Record<string, HTMLElement | undefined> & Component
readonly controls: Record<string, HTMLElement | undefined> & Component
readonly contextmenu: Record<string, HTMLElement | undefined> & Component
// Subtitle property: manages subtitle loading, switching, and styling.
readonly subtitle: {
get url(): string // Current subtitle URL.
set url(url: string) // Sets subtitle URL and loads it.
get textTrack(): TextTrack | undefined // The underlying TextTrack object.
get activeCues(): VTTCue[] // Currently active subtitle cues.
get cues(): VTTCue[] // All subtitle cues.
style: (name: string | Partial<CSSStyleDeclaration>, value?: string) => void // Applies CSS styles to subtitles.
switch: (url: string, option?: Subtitle) => Promise<string> // Switches to a new subtitle.
init: (subtitle: Subtitle) => Promise<string | null | undefined> // Initializes subtitles from an option.
} & Component // Extended with Component methods.
// Info and loading: simple UI components for displaying video info and loading indicators.
readonly info: Component
readonly loading: Component
// Hotkey property: manages keyboard shortcuts.
readonly hotkey: {
keys: Record<string, ((event: KeyboardEvent) => any)[]> // Map of key names to callback arrays.
add: (key: string, callback: (this: Artplayer, event: KeyboardEvent) => any) => Artplayer['hotkey'] // Adds a hotkey.
remove: (key: string, callback: (event: KeyboardEvent) => any) => Artplayer['hotkey'] // Removes a hotkey.
}
// Mask property: a UI component for overlays (e.g., for ads or pauses).
readonly mask: Component
// Setting property: manages the settings menu (e.g., playback speed, quality).
readonly setting: {
option: SettingOption[] // Array of available setting options.
updateStyle: (width?: number) => void // Updates the menu's width.
find: (name: string) => SettingOption | undefined // Finds a setting by name.
add: (setting: Setting) => Artplayer['setting'] // Adds a new setting.
update: (settings: Setting) => Artplayer['setting'] // Updates existing settings.
remove: (name: string) => Artplayer['setting'] // Removes a setting by name.
} & Component // Extended with Component methods.
// Plugins property: allows extending the player with custom functionality.
readonly plugins: {
add: (
plugin: (this: Artplayer, art: Artplayer) => unknown | Promise<unknown>,
) => Promise<Artplayer['plugins']> // Adds a plugin, which can be synchronous or asynchronous.
} & Record<string, unknown> // Plugins are stored as key-value pairs.
}
// Export for CommonJS and as a global variable in browser environments.
export = Artplayer
export as namespace Artplayer;
===== Examples Summary =====
ads.js example: This example demonstrates how to integrate the artplayer-plugin-ads plugin to display HTML or video advertisements before or during video playback. It uses the Artplayer constructor and the artplayerPluginAds plugin API. The configuration shows setting an HTML image ad, a video ad URL, a click-through link, mandatory watch duration, and total ad duration. It also attaches event listeners for when the ad is clicked or skipped.
// npm i artplayer-plugin-ads
// import artplayerPluginAds from 'artplayer-plugin-ads';
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)
})
ambilight.js example: This example shows the use of the artplayer-plugin-ambilight plugin to create an ambient lighting effect around the video player. It uses the Artplayer constructor and the artplayerPluginAmbilight plugin API. The feature demonstrated is a dynamic color border that samples video content, with configurable blur, opacity, update frequency, and transition duration.
// npm i artplayer-plugin-ambilight
// import artplayerPluginAmbilight from 'artplayer-plugin-ambilight';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoSize: true,
plugins: [
artplayerPluginAmbilight({
blur: '50px',
opacity: 1,
frequency: 10,
duration: 0.3,
}),
],
})
asr.js example: This example demonstrates using a plugin (presumably artplayer-plugin-asr) for Automatic Speech Recognition (ASR) to generate live subtitles from video audio. It uses the Artplayer constructor and a plugin configuration that processes audio chunks. The example includes a custom WebSocket implementation to send PCM audio data to an external ASR service and append the recognized text to the player as subtitles.
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/steve-jobs.mp4',
autoSize: true,
fullscreen: true,
fullscreenWeb: true,
moreVideoAttr: {
// crossOrigin: 'anonymous',
},
plugins: [
artplayerPluginAsr({
length: 2,
interval: 40,
sampleRate: 16000,
autoHideTimeout: 10000,
// Use your AI tool to convert pcm into subtitles
onAudioChunk: ({ pcm }) => startAsr(pcm),
}),
],
})
let ws = null
let loading = false
function stopAsr() {
try {
ws.send(JSON.stringify({ type: 'end' }))
ws.close()
}
catch {}
ws = null
loading = false
}
async function startAsr(buffer) {
if (loading)
return
if (!ws) {
loading = true
const api = 'https://api.aimu.app/asr/tencent?engine_model_type=16k_en'
const { url } = await (await fetch(api)).json()
ws = new WebSocket(url)
ws.binaryType = 'arraybuffer'
ws.onmessage = (event) => {
const { code, result, message } = JSON.parse(event.data)
if (code === 0) {
art.plugins.artplayerPluginAsr.append(result?.voice_text_str)
}
else {
console.error(code, message)
stopAsr()
}
}
loading = false
}
if (ws?.readyState === WebSocket.OPEN) {
ws.send(buffer)
}
}
art.on('destroy', stopAsr)
audio.track.js example: This example demonstrates using the artplayer-plugin-audio-track plugin to add an external audio track (like a commentary or dubbed track) synchronized with the main video. It uses the Artplayer constructor and the artplayerPluginAudioTrack plugin API. The feature shown is playing an AAC audio file alongside the video with configurable offset and sync parameters.
// npm i artplayer-plugin-audio-track
// import artplayerPluginAudioTrack from 'artplayer-plugin-audio-track';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/sprite-fight.mp4',
plugins: [
artplayerPluginAudioTrack({
url: '/assets/sample/sprite-fight.aac',
offset: 0,
sync: 0.3,
}),
],
});
auto.thumbnail.js example: This example demonstrates using the artplayer-plugin-auto-thumbnail plugin to automatically generate video thumbnails for the progress bar. It uses the Artplayer constructor and the artplayerPluginAutoThumbnail plugin API. The feature shown is enabling a visual preview of the video content on hover over the progress bar.
// npm i artplayer-plugin-auto-thumbnail
// import artplayerPluginAutoThumbnail from 'artplayer-plugin-auto-thumbnail';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
plugins: [
artplayerPluginAutoThumbnail({
//
}),
],
})
canvas.js example: This example demonstrates using the artplayer-proxy-canvas proxy to enable canvas-based video rendering, which can be used for advanced visual effects or processing. It uses the Artplayer constructor and the artplayerProxyCanvas proxy API. The example also enables many built-in Artplayer features like thumbnails, screenshot, settings, and playback controls.
// npm i artplayer-proxy-canvas
// import artplayerProxyCanvas from 'artplayer-proxy-canvas';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
poster: '/assets/sample/poster.jpg',
volume: 0.5,
autoplay: false,
autoSize: false,
screenshot: true,
setting: true,
loop: true,
flip: true,
pip: true,
playbackRate: true,
aspectRatio: true,
fullscreen: true,
fullscreenWeb: true,
miniProgressBar: true,
autoPlayback: true,
autoOrientation: true,
thumbnails: {
url: '/assets/sample/thumbnails.png',
number: 60,
column: 10,
scale: 0.85,
},
proxy: artplayerProxyCanvas(),
})
chapter.js example: This example demonstrates using the artplayer-plugin-chapter plugin to add chapter markers and navigation to the video progress bar. It uses the Artplayer constructor and the artplayerPluginChapter plugin API. The feature shown is defining video segments with start/end times and titles, allowing users to jump between chapters.
// npm i artplayer-plugin-chapter
// import artplayerPluginChapter from 'artplayer-plugin-chapter';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoSize: true,
fullscreen: true,
fullscreenWeb: true,
miniProgressBar: true,
autoOrientation: true,
thumbnails: {
url: '/assets/sample/thumbnails.png',
number: 60,
column: 10,
},
plugins: [
artplayerPluginChapter({
chapters: [
{ start: 0, end: 18, title: 'One more chance' },
{ start: 18, end: 36, title: '谁でもいいはずなのに' },
{ start: 36, end: 54, title: '夏の想い出がまわる' },
{ start: 54, end: 72, title: 'こんなとこにあるはずもないのに' },
{ start: 72, end: Infinity, title: '终わり' },
],
}),
],
})
chromecast.js example: This example demonstrates using the artplayer-plugin-chromecast plugin to enable Google Chromecast support for casting video to external devices. It uses the Artplayer constructor and the artplayerPluginChromecast plugin API. The feature shown is integrating casting capability, with optional configuration for the Cast SDK URL and media MIME type.
// npm i artplayer-plugin-chromecast
// import artplayerPluginChromecast from 'artplayer-plugin-chromecast';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreen: true,
fullscreenWeb: true,
plugins: [
artplayerPluginChromecast({
// sdk: '', // The URL of the Cast SDK
// mimeType: '', // The MIME type of the media
}),
],
})
danmuku.js example: This example demonstrates using the artplayer-plugin-danmuku plugin to display danmaku (bullet comments) over the video player. It uses the Artplayer constructor and the artplayerPluginDanmuku plugin API. The feature shown is loading danmaku from an XML file, with extensive configuration for appearance, behavior, filtering, and a custom async function to handle sending new comments.
// npm i artplayer-plugin-danmuku
// import artplayerPluginDanmuku from 'artplayer-plugin-danmuku';
// 使用文档 https://artplayer.org/document/plugin/danmuku.html
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
autoSize: true,
fullscreen: true,
fullscreenWeb: true,
autoOrientation: true,
plugins: [
artplayerPluginDanmuku({
danmuku: '/assets/sample/danmuku.xml',
// 以下为非必填
speed: 5, // 弹幕持续时间,范围在[1 ~ 10]
margin: [10, '25%'], // 弹幕上下边距,支持像素数字和百分比
opacity: 1, // 弹幕透明度,范围在[0 ~ 1]
color: '#FFFFFF', // 默认弹幕颜色,可以被单独弹幕项覆盖
mode: 0, // 默认弹幕模式: 0: 滚动,1: 顶部,2: 底部
modes: [0, 1, 2], // 弹幕可见的模式
fontSize: 25, // 弹幕字体大小,支持像素数字和百分比
antiOverlap: true, // 弹幕是否防重叠
synchronousPlayback: false, // 是否同步播放速度
mount: undefined, // 弹幕发射器挂载点, 默认为播放器控制栏中部
heatmap: true, // 是否开启热力图
width: 512, // 当播放器宽度小于此值时,弹幕发射器置于播放器底部
points: [], // 热力图数据
filter: danmu => danmu.text.length <= 100, // 弹幕载入前的过滤器
beforeVisible: () => true, // 弹幕显示前的过滤器,返回 true 则可以发送
visible: true, // 弹幕层是否可见
emitter: true, // 是否开启弹幕发射器
maxLength: 200, // 弹幕输入框最大长度, 范围在[1 ~ 1000]
lockTime: 5, // 输入框锁定时间,范围在[1 ~ 60]
theme: 'dark', // 弹幕主题,支持 dark 和 light,只在自定义挂载时生效
OPACITY: {}, // 不透明度配置项
FONT_SIZE: {}, // 弹幕字号配置项
MARGIN: {}, // 显示区域配置项
SPEED: {}, // 弹幕速度配置项
COLOR: [], // 颜色列表配置项
// 手动发送弹幕前的过滤器,返回 true 则可以发送,可以做存库处理
beforeEmit(danmu) {
return new Promise((resolve) => {
console.log(danmu)
setTimeout(() => {
resolve(true)
}, 1000)
})
},
}),
],
})
danmuku.mask.js example: This example demonstrates using both the artplayer-plugin-danmuku and artplayer-plugin-danmuku-mask plugins together. The mask plugin uses MediaPipe Selfie Segmentation to create a background mask, allowing danmaku comments to appear behind the speaker in the video. It uses the Artplayer constructor and both plugin APIs, showing integration of computer vision for enhanced danmaku display.
// npm i artplayer-plugin-danmuku-mask
// import artplayerPluginDanmukuMask from 'artplayer-plugin-danmuku-mask';
// npm i @mediapipe/selfie_segmentation
// 把 node_modules/@mediapipe/selfie_segmentation 目录复制到你的项目下
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/steve-jobs.mp4',
autoSize: true,
fullscreen: true,
fullscreenWeb: true,
autoOrientation: true,
plugins: [
artplayerPluginDanmuku({
danmuku: '/assets/sample/danmuku.xml',
}),
artplayerPluginDanmukuMask({
solutionPath: '/assets/@mediapipe/selfie_segmentation',
}),
],
})
dash.control.js example: This example demonstrates the setup for using the artplayer-plugin-dash-control plugin alongside the dash.js library to play MPEG-DASH adaptive streaming videos. It shows the import statements and dependencies required but does not include the full player instantiation code. The feature indicated is control and playback of DASH streams.
// npm i dashjs
// npm i artplayer-plugin-dash-control
// import dashjs from 'dashjs';
// import artplayerPluginDashControl from 'artplayer-plugin-dash-control';
Example 1: ArtPlayer with DASH plugin and custom playback handler
This example shows how to set up ArtPlayer with a DASH stream, using the dash.js library and a custom plugin for quality and audio track selection. It demonstrates the customType API for handling non-native video formats and the plugin system for extended controls.
const art = new Artplayer({
container: '.artplayer-app',
url: 'https://media.axprod.net/TestVectors/v7-Clear/Manifest_1080p.mpd',
setting: true,
plugins: [
artplayerPluginDashControl({
quality: {
// Show qualitys in control
control: true,
// Show qualitys in setting
setting: true,
// Get the quality name from level
getName: level => `${level.height}P`,
// I18n
title: 'Quality',
auto: 'Auto',
},
audio: {
// Show audios in control
control: true,
// Show audios in setting
setting: true,
// Get the audio name from track
getName: track => track.lang.toUpperCase(),
// I18n
title: 'Audio',
auto: 'Auto',
},
}),
],
customType: {
mpd: function playMpd(video, url, art) {
if (dashjs.supportsMediaSource()) {
if (art.dash)
art.dash.destroy()
const dash = dashjs.MediaPlayer().create()
dash.initialize(video, url, art.option.autoplay)
art.dash = dash
art.on('destroy', () => dash.destroy())
}
else {
art.notice.show = 'Unsupported playback format: mpd'
}
},
},
})
===== dash.js =====
Example 2: Basic DASH playback with dash.js
This example demonstrates a minimal setup for playing a DASH stream using dash.js. It shows the customType API for defining a playback handler and the 'ready' event to access the dash.js instance.
// npm i dashjs
// import dashjs from 'dashjs';
function playMpd(video, url, art) {
if (dashjs.supportsMediaSource()) {
if (art.dash)
art.dash.destroy()
const dash = dashjs.MediaPlayer().create()
dash.initialize(video, url, art.option.autoplay)
art.dash = dash
art.on('destroy', () => dash.destroy())
}
else {
art.notice.show = 'Unsupported playback format: mpd'
}
}
const art = new Artplayer({
container: '.artplayer-app',
url: 'https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps.mpd',
type: 'mpd',
customType: {
mpd: playMpd,
},
})
art.on('ready', () => {
console.info(art.dash)
})
===== document.pip.js =====
Example 3: Document Picture-in-Picture plugin
This example shows how to use the artplayer-plugin-document-pip plugin to enable Document Picture-in-Picture mode. It demonstrates plugin configuration and listening for the custom 'document-pip' event.
// npm i artplayer-plugin-document-pip
// import artplayerPluginDocumentPip from 'artplayer-plugin-document-pip';
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
plugins: [
artplayerPluginDocumentPip({
width: 480,
height: 270,
fallbackToVideoPiP: true,
placeholder: `Playing in Document Picture-in-Picture`,
}),
],
})
art.on('document-pip', (state) => {
console.log('Document Picture-in-Picture', state)
})
===== flv.js =====
Example 4: FLV playback with flv.js
This example demonstrates playing an FLV stream using the flv.js library. It shows the customType API and the 'ready' event to access the flv.js player instance.
// npm i flv.js
// import flvjs from 'flv.js';
function playFlv(video, url, art) {
if (flvjs.isSupported()) {
if (art.flv)
art.flv.destroy()
const flv = flvjs.createPlayer({ type: 'flv', url })
flv.attachMediaElement(video)
flv.load()
art.flv = flv
art.on('destroy', () => flv.destroy())
}
else {
art.notice.show = 'Unsupported playback format: flv'
}
}
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.flv',
type: 'flv',
customType: {
flv: playFlv,
},
})
art.on('ready', () => {
console.info(art.flv)
})
===== hls.control.js =====
Example 5: HLS playback with quality and audio controls
This example shows HLS playback using hls.js with the artplayer-plugin-hls-control plugin for quality and audio track selection. It demonstrates a comprehensive customType handler with fallback support for native HLS.
// npm i hls.js
// npm i artplayer-plugin-hls-control
// import Hls from 'hls.js';
// import artplayerPluginHlsControl from 'artplayer-plugin-hls-control';
const art = new Artplayer({
container: '.artplayer-app',
url: 'https://playertest.longtailvideo.com/adaptive/elephants_dream_v4/index.m3u8',
setting: true,
plugins: [
artplayerPluginHlsControl({
quality: {
// Show qualitys in control
control: true,
// Show qualitys in setting
setting: true,
// Get the quality name from level
getName: level => `${level.height}P`,
// I18n
title: 'Quality',
auto: 'Auto',
},
audio: {
// Show audios in control
control: true,
// Show audios in setting
setting: true,
// Get the audio name from track
getName: track => track.name,
// I18n
title: 'Audio',
auto: 'Auto',
},
}),
],
customType: {
m3u8: function playM3u8(video, url, art) {
if (Hls.isSupported()) {
if (art.hls)
art.hls.destroy()
const hls = new Hls()
hls.loadSource(url)
hls.attachMedia(video)
art.hls = hls
art.on('destroy', () => hls.destroy())
}
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = url
}
else {
art.notice.show = 'Unsupported playback format: m3u8'
}
},
},
})
===== hls.js =====
Example 6: Basic HLS playback with hls.js
This example shows a minimal setup for HLS playback using hls.js. It demonstrates the customType API and the 'ready' event to access the Hls instance.
// npm i hls.js
// import Hls from 'hls.js';
function playM3u8(video, url, art) {
if (Hls.isSupported()) {
if (art.hls)
art.hls.destroy()
const hls = new Hls()
hls.loadSource(url)
hls.attachMedia(video)
art.hls = hls
art.on('destroy', () => hls.destroy())
}
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = url
}
else {
art.notice.show = 'Unsupported playback format: m3u8'
}
}
const art = new Artplayer({
container: '.artplayer-app',
url: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8',
type: 'm3u8',
customType: {
m3u8: playM3u8,
},
})
art.on('ready', () => {
console.info(art.hls)
})
===== iframe.js =====
Example 7: Embedding ArtPlayer within an iframe using a tool
This example demonstrates how to embed and control an ArtPlayer instance inside an iframe using the artplayer-tool-iframe utility. It shows cross-document communication via postMessage for features like fullscreenWeb mode.
// npm i artplayer-tool-iframe
// import ArtplayerToolIframe from 'artplayer-tool-iframe';
const $iframe = document.createElement('iframe')
$iframe.allowFullscreen = true
$iframe.width = '100%'
$iframe.height = '100%'
const $container = document.querySelector('.artplayer-app')
$container.innerHTML = ''
$container.appendChild($iframe)
const iframe = new ArtplayerToolIframe({
iframe: $iframe,
url: '/iframe.html',
})
iframe.message(({ type, data }) => {
switch (type) {
case 'fullscreenWeb':
if (data) {
$iframe.classList.add('fullscreenWeb')
}
else {
$iframe.classList.remove('fullscreenWeb')
}
break
default:
break
}
})
iframe.commit(() => {
const art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
fullscreen: true,
fullscreenWeb: true,
})
art.on('fullscreenWeb', (state) => {
ArtplayerToolIframe.postMessage({
type: 'fullscreenWeb',
data: state,
})
})
})
===== index.js =====
Example 8: Placeholder file
This appears to be a placeholder or index file with no code, likely indicating the start of the examples or a file to be populated.
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/sample/video.mp4',
poster: '/assets/sample/poster.jpg',
volume: 0.5,
isLive: false,
muted: false,
autoplay: false,
pip: true,
autoSize: true,
autoMini: true,
screenshot: true,
setting: true,
loop: true,
flip: true,
playbackRate: true,
aspectRatio: true,
fullscreen: true,
fullscreenWeb: true,
subtitleOffset: true,
miniProgressBar: true,
mutex: true,
backdrop: true,
playsInline: true,
autoPlayback: true,
airplay: true,
theme: '#23ade5',
lang: navigator.language.toLowerCase(),
moreVideoAttr: {
crossOrigin: 'anonymous',
},
settings: [
{
width: 200,
html: 'Subtitle',
tooltip: 'Bilingual',
icon: '<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 shows a comprehensive configuration of the ArtPlayer instance. It demonstrates the core player API with a wide array of built-in features and custom UI components. Key features shown include: basic player setup with URL and poster; enabling numerous player controls like screenshot, loop, flip, playback rate, and fullscreen; custom settings panels with subtitle selector, switch, slider, and button components; custom context menu items; custom UI layers; multiple video quality options; thumbnail previews; subtitle styling and loading; video highlight markers; custom control bar buttons; and custom icon overrides for loading, state, and seek indicator.
===== jassub.js =====
// https://github.com/ThaUnknown/jassub
// npm i artplayer-plugin-jassub
// import artplayerPluginJassub from 'artplayer-plugin-jassub';
var art = new Artplayer({
container: '.artplayer-app',
url: '/assets/jassub/FGOBD.mp4',
autoSize: true,
fullscreen: true,
fullscreenWeb: true,
plugins: [
artplayerPluginJassub({
subUrl: '/assets/jassub/FGOBD.ass',
workerUrl: '/assets/jassub/jassub-worker.js',
wasmUrl: '/assets/jassub/jassub-worker.wasm',
modernWasmUrl: '/assets/jassub/jassub-worker-modern.wasm',
availableFonts: {
'liberation sans': '/assets/jassub/default.woff2'
},
fonts: [
'/assets/jassub/fonts/Averia Sans Libre Light.ttf',
'/assets/jassub/fonts/Averia Serif Simple Light.ttf',
'/assets/jassub/fonts/Gramond.ttf'
],
timeOffset: -0.041
}),
],
});
This example demonstrates the integration of the jassub plugin for advanced ASS/SSA subtitle rendering. It uses the plugins API to add the artplayerPluginJassub. The plugin configuration shows how to load ASS subtitle files, provide the required WebAssembly and worker scripts for subtitle rendering, specify custom fonts for accurate subtitle styling, and apply a timing offset to sync the subtitles with the video.
===== mediabunny.js =====
// npm i artplayer-proxy-mediabunny
// import artplayerProxyMediabunny from 'artplayer-proxy-mediabunny';
const art = new Artplayer({
container: '.artplayer-app',
url: 'https://artplayer.org/assets/sample/frag_bunny.mp4',
autoSize: true,
screenshot: true,
setting: true,
loop: true,
flip: true,
playbackRate: true,
fullscreen: true,
fullscreenWeb: true,
miniProgressBar: true,
autoPlayback: true,
autoOrientation: true,
thumbnails: {
url: '/assets/sample/frag_bunny.png',
number: 60,
column: 10,
scale: 0.85,
},
proxy: artplayerProxyMediabunny(),
})
This example shows the use of the mediabunny proxy plugin. It uses the proxy API to integrate artplayerProxyMediabunny. The feature demonstrated is the ability to proxy video data, which is often used for handling specific streaming protocols, adding DRM support, or modifying network requests. The player is configured with common UI features like thumbnails, screenshot, and playback controls, with the proxy handling the underlying video delivery.
===== mobile.js =====
This file appears to be incomplete in the provided input. A typical mobile.js example would demonstrate configuration options optimized for mobile devices, such as touch controls, playsInline for iOS, and autoOrientation. Since the code is not present, no analysis can be provided.
Example 1: Basic ArtPlayer Configuration
This example shows a comprehensive ArtPlayer setup with many built-in features enabled. It uses the core ArtPlayer constructor and demonstrates common configuration options, custom thumbnails, subtitles, layers, icons, and a custom settings menu.
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
},
},
],
})
===== mpegts.js =====
Example 2: Custom Playback for FLV Format with mpegts.js
This example demonstrates using a custom playback function for FLV video files via the mpegts.js library. It uses the `customType` configuration option and the player's `on` event hook.
// 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()
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 =====
Example 3: Multiple Subtitles Plugin
This example shows the integration of the `artplayer-plugin-multiple-subtitles` plugin. It demonstrates loading multiple subtitle tracks, creating a settings menu to control them, and applying custom CSS styles to different subtitle languages.
// 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 =====
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)
}
})
This example demonstrates the advanced customization of the ArtPlayer settings panel. It shows how to add custom settings items, including a subtitle selector with a toggle switch, a custom boolean switch, and a range slider. The second function argument uses the Artplayer.utils.sleep method and demonstrates the Setting API, including methods like show, builtin, find, resize, inactivate, remove, update, and add, to dynamically manipulate settings at runtime.
===== thumbnail.js =====
// 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,
}),
],
})
This example shows the basic integration of the artplayer-plugin-thumbnail. It initializes a player with the thumbnail plugin, which generates a preview strip from the video. The plugin configuration includes options for thumbnail width, the total number of thumbnails, and the scale.
===== tool.thumbnail.js =====
if (window.lastThumbnail) {
window.lastThumbnail.destroy();
}
var $popups = document.querySelector('.popups');
var $popinner = document.querySelector('.popinner');
var $artplayer = document.querySelector('.artplayer-app');
$artplayer.innerHTML = 'Drop video file here or click to upload.';
var thumbnail = new ArtplayerToolThumbnail({
fileInput: $artplayer,
number: 60, // 数量
width: 160, // 宽度
column: 10, // 列数
begin: 0, // 开始
end: NaN, // 结束
});
window.lastThumbnail = thumbnail;
thumbnail.on('file', function (file) {
console.log('Read video successfully: ' + file.name);
});
thumbnail.on('video', function (video) {
console.log('Video size: ' + video.videoWidth + ' x ' + video.videoHeight);
console.log('Video duration: ' + video.duration + 's');
thumbnail.start();
});
thumbnail.on('canvas', function (canvas) {
console.log('Build canvas successfully');
console.log('Canvas size: ' + canvas.width + ' x ' + canvas.height);
console.log('Preview density: ' + thumbnail.density + ' p/s');
});
thumbnail.on('update', function (url, percentage) {
console.log('Processing: ' + Math.floor(percentage.toFixed(2) * 100) + '%');
$popups.style.display = 'flex';
$popinner.style.backgroundImage = 'url(' + url + ')';
});
thumbnail.on('download', function (name) {
console.log('Start download preview: ' + name);
});
thumbnail.on('done', function () {
$popups.style.display = 'none';
thumbnail.download();
console.log('Build preview image complete');
[...Artplayer.instances].forEach(function (art) {
art.destroy(true);
});
new Artplayer({
container: $artplayer,
url: thumbnail.videoUrl,
autoSize: true,
poster: thumbnail.thumbnailUrl,
thumbnails: {
url: thumbnail.thumbnailUrl,
number: thumbnail.option.number,
column: thumbnail.option.column,
},
});
console.log('Build player complete');
});
This example demonstrates the standalone ArtplayerToolThumbnail utility for generating a thumbnail sprite from a user-uploaded video file. It uses the tool's event-driven API (on('file'), on('video'), on('canvas'), on('update'), on('download'), on('done')) to handle the workflow. The final step creates a new ArtPlayer instance configured with the generated thumbnail sprite and the original video.
===== vast.js =====
// 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')
})
}),
],
})
This example shows integration with the artplayer-plugin-vast for VAST/IMA ad playback. The plugin is configured with a callback that receives helper functions. The example uses art.once to listen for the first 'play' event and then triggers an ad playback from a VAST XML URL using the provided playUrl function.
===== vtt.thumbnail.js =====
// 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',
}),
],
})
This example demonstrates the use of the artplayer-plugin-vtt-thumbnail plugin. It loads a WebVTT file that contains thumbnail image coordinates and timing data, allowing the player to display a preview image on the progress bar that corresponds to the specific time in the video.
===== webtorrent.js =====
// npm i webtorrent
// import WebTorrent from 'webtorrent';
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'
}
}
This example provides a utility function, playTorrent, for streaming video from a torrent file using the WebTorrent library. It checks for WebRTC support, initializes a new WebTorrent client, registers a service worker, and adds the torrent. It finds the first .mp4 file within the torrent and streams it directly to a video element. It also sets up a listener to destroy the torrent client when the ArtPlayer instance is destroyed.
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 shows how to initialize an ArtPlayer instance to stream a video from a torrent magnet link. It uses the Artplayer constructor API with the 'url', 'type', and 'customType' options. The 'type' is set to 'torrent', and a 'customType' handler named 'playTorrent' (a function assumed to be defined elsewhere) is provided to handle the torrent playback logic. This demonstrates the player's extensibility for custom video sources, specifically integrating WebTorrent functionality. The event listener for the 'ready' event logs the torrent instance to the console, showing how to access the internal torrent object after the player is set up.