欢迎各位兄弟 发布技术文章
这里的技术是共享的
Use the flowplayer
function to get a global handle on the API. Here we attach two custom events to the API of all players which will be installed on the page:
flowplayer(function (api, root) {
api.on("load", function () {
// do something when a new video is about to be loaded
}).on("ready", function () {
// do something when a video is loaded and ready to play
});
});
View standalone demo.
This anonymous callback function is provided by the Flowplayer library and is called every time a Flowplayer instance is created.
You use it to customize the default behaviour of all players on your page in a similar manner as you setglobal configuration options, and thus it should be called right after the flowplayer script is included in the HEAD section of the page and before the page is loaded - before the DOM (Document Object Model) is ready.
The API is provided by the first argument and it looks like this in the browser console:
Via the second argument - called root
above - you can access the root or container element of the player.
Once the players are installed initialized you can access specific player instances like this:
// get the first player
var api = flowplayer();
// same thing with jQuery
api = $(".flowplayer:first").data("flowplayer");
// and the second player
api = flowplayer(1);
// .. with jQuery
api = $(".flowplayer:eq(1)").data("flowplayer");
// use any jQuery selector
api = $(".mycustom.flowplayer").data("flowplayer");
// return the API in given jQuery object
api = flowplayer($(".myplayer"));
// or DOM object
var elem = document.getElementById("myplayer");
api = flowplayer(elem);
The installation method determines when you have access to selected APIs:
The pure JavaScript installation allows instant API access to the specific instance:
var api = flowplayer("#player", {
// player configuration goes here
});
Contrary to the other selective API access methods the API is accessible in a 1-step operation.
During its life cycle the player is in varying states which are reflected in the the properties of the API. Here is a complete list of the API properties:
property | default value | description |
conf | Object | the initial configuration object |
currentSpeed | 1 | the current playback speed level: - 1 = normal speed less than 1 = slow motion greater than 1 = fast forward |
disabled | false | true while the player is disabled |
engine | object | the chosen video engine, the name of the engine can be retrieved asengine.engineName |
error | undefined | true once an error has occured |
finished | false | true while the player is stopped at the end of the video |
forcedSplash | false | whether a splash setup was enforced for this player, true on mobile devices |
isFullscreen | false | true while the player is in fullscreen mode |
loading | false | true while the player is being loaded |
muted | false | true while the player is muted |
paused | false | true while the player is paused |
playing | false | true while the player is playing |
poster | false | v6.0.4 true while the player is in poster state |
ready | false | true once the player API is ready and completely loaded |
rtl | false | true if the player has a right-to-left layout |
seeking | false | true while the player is seeking |
splash | false | true while the player is in splash state |
video | Object | the current video object |
volumeLevel | 0.8 | the current volume level between 0 and 1 |
Depending on the state of the player at the moment when you grab the API or call one of its methods, the full depth of its properties might be not be available.
For example: Before the player is ready
video metadata such as its duration has not been processed and is therefore undefined
. Similarly you cannot obtain a sensible value for the current playback position at all times. A safe way to retrieve that position would be:
var api = flowplayer(), currentPos;
// get the current position, default to 0
currentPos = api.ready ? api.video.time : 0;
API properties should be considered as read only. Use API methods to change the state of the player and its properties. Setting properties is only needed in advanced cases and situations which often should be avoided in the first place, like in this demo which recovers from an invalid video location.
The following properties are provided by player extensions and plugins. Follow the link in the third column for further details:
property | kind | extension |
cuepoints | array | Cuepoints extension |
pluginQualitySelectorEnabled | boolean | Quality selector plugin |
subtitles | array | Subtitles extension |
The video property is a reference to the currently playing video. Here is an example:
{
// the length of the available buffer in seconds - not available over RTMP
buffer: 15.43,
// flag indicating whether the buffer is fully loaded
buffered: false,
// length of video in seconds
duration: 18.85,
// width of video file in pixels
width: 640
// height of video in pixels
height: 280,
// current index in the playlist
index: 0,
// true in case the clip is the last in a playlist
is_last: false,
// whether the server supports random jumping on timeline
seekable: true,
// path to currently playing video as given on setup
src: 'http://mydomain.com/video1.webm',
// current playback position in seconds
time: 5.27681660899654,
// video format (media type)
type: 'video/webm',
// array of video formats
sources: [
{ type: 'application/x-mpegurl', src: '//mydomain.com/video1.m3u8', suffix: 'm3u8' },
{ type: 'video/webm', src: '//mydomain.com/video1.webm', suffix: 'webm' },
{ type: 'video/mp4', src: '//mydomain.com/video1.mp4', suffix: 'mp4' }
],
// video filename suffix
suffix: 'webm',
// absolute URL of the video
url: 'http://mydomain.com/video1.webm',
// subtitles - array contains subtitle objects if available
subtitles: [ ],
// the clip title (if configured)
title: 'My video'
}
Check out this demo which prints the entire video object to the page for inspection.
method | description |
disable([flag]) | disable() without argument toggles between disabled and normal API state. disable(true) disables anddisable(false) enables the API.While the API is disabled loading, pausing, resuming and seeking is not possible. The progress bar is greyed out (color configurable via CSS). |
fullscreen() | Toggles between native fullscreen mode and initial screen size. When native fullscreen support is not present the player expands to the full size of the browser window. Note: Many browsers allow this method to work only from events which are triggered by user interaction, like "click", and not for example from player events like "ready" which happen at moments undetermined by the user. |
load([video], [callback]) | Loads the player with the specified video. See the section on the load method. |
mute([flag]) | mute() without argument toggles between muted and normal state. mute(true) mutes and mute(false) unmutes. The original volume level is remembered between page loads. |
pause([callback]) | Pauses playback. |
play([video], [callback]) | Alias for the load method. |
resume() | Resumes playback. |
seek(time, [callback]) | Seeks to the given position in seconds. For example: 13.5 .The callback is executed once after the seek. |
seek(flag, [callback]) | seek(true) seeks 10% forward and seek(false) seeks 10% backward. Same as pressing → or ← on the keyboard.The callback is executed once after the seek. |
seekTo(position, [callback]) | seekTo(1) jumps to 10% on the timeline, seekTo(2) goes to 20% and so on.The callback is executed once after the seek. |
seekTo() | Seeks to last seek position. Same as pressing . on the keyboard. |
shutdown() | Destroys the player instance. Call this method before you remove the container element from the page, or before you remove the player from it. This way all Flowplayer event handles are cleaned up as well. |
speed(rate, [callback]) | Sets the speed level to the given rate. 1 = normal speed less than 1 = slow motion greater than 1 = fast forward The callback is executed once after the speed has changed. |
speed(flag, [callback]) | Changes the speed based on the speed configuration variable.speed(false) switches backward on the speed array.speed(true) switches forward.The callback is executed once after the speed has changed. |
stop() | Pauses playback and seeks to the beginning of the video. In a poster setup the player goes back into poster state. |
toggle() | Toggles between pause and play. |
unload() | In a splash setup unloads the player back to the splash state. In non-splash setups the player is not unloaded but goes back to its initial state, the poster or first video frame is shown. |
volume(level) | Set the volume level to a decimal value between 0.0 (no volume) and 1.0 (full volume). The volume level is remembered between page loads. |
All methods return the API object, with the exception of shutdown()
. This allows method chaining:
// re-enable the api for the 2nd player on the page and resume
flowplayer(1).disable(false).resume();
See also the methods for event handling.
The following methods are provided by player extensions. Follow the link in the second column for further details:
method | extension |
addCuepoint(cuepoint) | Cuepoints extension |
addPlaylistItem(clip) | Playlist extension |
disableSubtitles() | Subtitles extension |
embedCode() | Embedding extension |
loadSubtitles(index) | Subtitles extension |
next() | Playlist extension |
play(index) | Playlist extension |
prev() | Playlist extension |
removeCuepoint(position) | Cuepoints extension |
removePlaylistItem(index) | Playlist extension |
setCuepoints(array) | Cuepoints extension |
setPlaylist(array) | Playlist extension |
Without argument the load()
method initializes player and video from the splash state on demand:
api.load();
A VIDEO or OBJECT tag is created depending on browser or engine preference.
load()
also accepts a clip object as argument in the same way a pure JavaScript installation does as value to the clip
option. The video represented by this clip object is then loaded into an existing player instance:
api.load({
sources: [
{ type: "application/x-mepgurl",
src: "//mydomain.com/video2.m3u8" },
{ type: "video/webm",
src: "//mydomain.com/video2.webm" },
{ type: "video/mp4",
src: "//mydomain.com/video2.mp4" }
]
});
The following shorthands are available for the clip object argument:
api.load([
{ mpegurl: "//mydomain.com/video2.m3u8" },
{ webm: "//mydomain.com/video2.webm" },
{ mp4: "//mydomain.com/video2.mp4" }
]);
This shorthand does not accept further clip or source options.
api.load("//mydomain.com/my/another/video2.mp4");
This shorthand does not accept further clip or source options. And it expects the same source types to be present as configured for the player instance referenced by the API. Additionally the sources must be available via HTTP and obey the same file naming scheme: they can only differ by their filename suffix.
The above shorthand could be applied successfully to the following player for example:
<div class="flowplayer">
<video>
<source type="application/x-mpegurl" src="//mydomain.com/video1.m3u8">
<source type="video/webm" src="//mydomain.com/video1.webm">
<source type="video/mp4" src="//mydomain.com/video1.mp4">
</video>
</div>
api.load({
sources: [
{ type: "application/x-mepgurl",
src: "//mydomain.com/video2.m3u8" },
{ type: "video/webm",
src: "//mydomain.com/video2.webm" },
{ type: "video/mp4",
src: "//mydomain.com/video2.mp4" }
]
}, function (e, api, video) {;
console.log(video.duration);
});
The callback function will be invoked when the player is ready and the new video is about to start.
The attaching methods can be used to execute custom JavaScript when a specified event happens in the player. For example:
api.on("pause", function(e, api) {
// do your thing when the player is paused
});
The first argument is the event name or a space separated string of several event names, and the second is a callback function which is fed with 2 or 3 arguments:
The event properties, like target
, type
etc., can be inspected in the browser console:
api.on("mute", function (e) {
console.log(e);
});
Here is a complete list of player events:
event | when it fires |
beforeseek | Before seeking starts at the origin position. The 3rd argument gives access to the seek target position. By calling event.preventDefault() (where event is the callback's 1st argument) the seek can be stopped. |
disable | When the player toggles between disabled and normal state. In disabled mode the UI elements cannot be used. |
error | When an error occurred. The 3rd argument provides an object featuring thecode and message properties. See the error table below. |
finish | When playback has finished. |
fullscreen | When the player goes to fullscreen mode. |
fullscreen-exit | When player exits fullscreen mode. |
load | First event in the lifecycle of the (first) clip, before the configured clip or a new video starts playing. Offers an opportunity to alter the video properties. The 3rd argument provides the video object featuring basic data like src , but not yet the video metadata from the server (such as duration ). Returning false will prevent the video from loading. |
mute | When the player's mute state is toggled. |
pause | When playback is paused. |
progress | When the playhead moves forward. Happens approximately every 250 milliseconds during playback. The 3rd argument provides the current playback position, i.e. the current value of the time property of the video object. |
ready | When the video is fully loaded and video metadata (such as duration ) becomes available from the video object which is provided by the 3rd argument. |
resume | When playback is resumed. |
seek | When seeking is completed at the target position. The 3rd argument gives access to the target position. |
shutdown | When the player and API instance is destroyed, after the shutdown() methodhas been invoked. Last event in a player's life cycle. |
speed | When the playback speed is changed. The new level is provided by the 3rd argument. |
stop | When playback is stopped by the stop() method. |
unload | When the player goes back to the splash state. |
volume | When the volume level is changed. The new level is provided by the 3rd argument. |
Error codes and error messages returned by the third argument of the error event are mapped the following way:
error code | error message |
1 | Video loading aborted |
2 | Network error |
3 | Video not properly encoded |
4 | Video file not found |
5 | Unsupported video |
6 | Skin not found |
7 | SWF file not found |
8 | Subtitles not found |
9 | Invalid RTMP URL |
10 | Unsupported video format. Try installing Adobe Flash. |
Errors 1
through 4
are HTML5 video exceptions, errors 5
through 10
are Flowplayer exceptions.
The cuepoint
event is provided by 2 player extensions. Follow the link in the second column for further details:
event | extension |
cuepoint | Cuepoints extension |
cuepoint | Subtitles extension |
The following methods attach (or detach) events:
method | description |
bind() | Alias for the on() method. |
off() | Removes the event handler(s) specified in the 1st argument. No callback, unless the event was attached to the container via jQuery. Similar to the jQuery method of the same name. |
on() | Attaches the callback in the 2nd argument to the events specified in the 1st argument. Similar to the jQuery method of the same name. |
one() | One time event handle. The callback in the 2nd argument is fired once for (each of) the event(s) specified in the 1st argument. Similar to the jQuery method of the same name. |
unbind() | Alias for the off() method. |
Events can be attached either to the API, or, with the help of jQuery, to the container element.
Multiple events can be attached in one call by passing their names in a space separated string in the first argument:
api.on("fullscreen fullscreen-exit", function (e, api) {
if (/exit/.test(e.type)) {
// do something after leaving fullscreen
} else {
// do something after going fullscreen
}
});
Normally events are simply attached to the API, like in the example above.
Events attached to the API return the API object.
You can also bind your events directly to the jQuery object referencing the container element. For example:
$(".flowplayer:first").on("pause", function(e, api) {
// do something on pause
});
This makes for seamless integration of the Flowplayer API into custom jQuery plugins.
Events attached via jQuery return the jQuery object of the container element.
As this is a jQuery event, the this
keyword refers to the root or container element of the player within the callback. It corresponds to the currentTarget property of the first argument.
All Flowplayer events can be confined to a specific name space when you attach them:
api.on("pause.mypause", function (e, api) {
// do something on pause
});
Flowplayer event name spaces work as in jQuery, but do not require jQuery to be loaded. They come in handy for instance if you want to turn off a specific callback:
// turns off pause.mypause, but not the entire pause callback
api.off("pause.mypause");
Events can immediately be attached to the API of a specific JavaScript installation:
flowplayer("#player", {
// player configuration goes here
}).on("pause", function (e, api) {
// do something on pause with this player
});
Events can immediately be attached to the container jQuery object of a specific manual installation:
$(".player").flowplayer({
// player configuration goes here
}).on("pause", function (e, api) {
// do something on pause with these players
});
Caveat: This will catch the load
event of splash setups only because otherwise the container element containing the VIDEO tag is already loaded. - One of the reasons why we recommend the pure JavaScript installation method for scripting-heavy setups.
All Flowplayer events return the API, or, if attached via jQuery the jQuery object of the container element. Therefore event bindings can be chained:
api.on("pause", function (e, api) {
// do something on pause
}).on("resume", function (e, api) {
// do something on resume
});
In some situations it is desireable to prevent player events from happening or to limit their scope, and optionally take a different action. To achieve this the Flowplayer API offers two methods which can be chained to the event variable provided by first argument of the event handle:
method | effect |
e.preventDefault() | The default action of this event will not be triggered. Note: In rare cases one may have to use brute force and simply return false from within the event, but calling this method should be preferred.Similar to the jQuery method of the same name. |
e.stopPropagation() | Other handlers of this event will not be notified. Similar to the jQuery method of the same name. |
This demo gives an example of both methods in action to show how seeking can be disabled.
Flowplayer ships with two engines named html5
and flash
. They share a common engine interface which is implemented as follows:
var engineImpl = function (player, root) {
var engine = {
engineName: engineImpl.engineName,
pick: function (sources) {
// engine specific picking mechanism
},
load: function (video) {
// how this engine loads the video
},
resume: function () {
// how this engine resumes playback
},
/* etc. */
};
return engine;
};
engineImpl.engineName = "myengine";
engineImpl.canPlay = function (type, conf) {
// return boolean whether this engine can play media of type type
// in the player configuration conf
};
// add the engines to the existing engines
flowplayer.engines.push(engineImpl);
Look for the implementation details in Github or check out our MPEG-DASH demo - its experimental engine can be inspected here.
The flowplayer
function is used for accessing the player, making extensions and engines. It also provides the following properties:
// version number
var version = flowplayer.version;
// default configuration for all players (v5.1)
flowplayer.defaults;
// global configuration to override defaults
flowplayer.conf = { };
// list of engines which are supported by the browser
flowplayer.engines
The flowplayer.set
method allows to extend the existing global configuration without discarding other existing top-level settings, thereby offering more flexibility compared to specifying theflowplayer.conf
object directly.
A typical scenario where this comes in handy: All pages on a site load a default script which contains Flowplayer configuration settings, but you want to override selected settings without discarding others:
flowplayer.set({
// all videos on this page have a 4:3 aspect ratio
ratio: 3/4,
// all players on this page will be embedded with the minimalist skin
embed: {
skin: "//releases.flowplayer.org/6.0.4/skin/minimalist.css"
}
});
Like anything relating to global configuration, flowplayer.set
should be used only in the HEAD section of your page, before the DOM is ready.
embed
settings if still applicable. Only previous top-level values are merged.flowplayer.support
is a collection of properties that represent the presence of different browser features. If for example HTML5 video is supported then flowplayer.support.video
is true
. Here are the supported properties:
animation
- HTML animation supportbrowser
- returns information about current browser and versiondataload
- whether any video data can be loaded before hitting playflashVideo
- flash video supportfirstframe
- support for display of first video frame on loadfullscreen
- native HTML5 fullscreen supportfullscreen_keyboard
- keyboard support in fullscreen modehlsDuration
- whether duration of HLS stream is natively recognizedinlineBlock
- CSS inline-block supportinlineVideo
- support for playing video inlineseekable
- support for seeking when video is readysubtitles
- native subtitle supporttouch
- touch interface supportvideo
- HTML video supportvolume
- volume support via JavaScript APIzeropreload
- whether preload="none" completely disables preloadingThe second argument provided by the anonymous callback of the global API setup function is not a jQuery object anymore but a reference to the container element itself. If jQuery is loaded, you can still access the container element the jQuery way like this:
flowplayer(function (api, root) {
root = $(root);
// ... code referring to root as jQuery object
});