欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

flowplayer JavaScript API

shiping1 的头像

 

Global API access

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:

Console screenshot

Via the second argument - called root above - you can access the root or container element of the player.

Selective API access

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:

Instant API access

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.

Properties

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:

propertydefault valuedescription
confObjectthe initial configuration object
currentSpeed1the current playback speed level:
- 1 = normal speed
less than 1 = slow motion
greater than 1 = fast forward
disabledfalsetrue while the player is disabled
engineobjectthe chosen video engine, the name of the engine can be retrieved asengine.engineName
errorundefinedtrue once an error has occured
finishedfalsetrue while the player is stopped at the end of the video
forcedSplashfalsewhether a splash setup was enforced for this player, true on mobile devices
isFullscreenfalsetrue while the player is in fullscreen mode
loadingfalsetrue while the player is being loaded
mutedfalsetrue while the player is muted
pausedfalsetrue while the player is paused
playingfalsetrue while the player is playing
posterfalsev6.0.4 true while the player is in poster state
readyfalsetrue once the player API is ready and completely loaded
rtlfalsetrue if the player has a right-to-left layout
seekingfalsetrue while the player is seeking
splashfalsetrue while the player is in splash state
videoObjectthe current video object
volumeLevel0.8the 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.

  • tip When skinning is involved you can often achieve your scripting goals with pure CSS programming by defining rules for the state classes instead of querying JavaScript API properties.

Extension and plugin properties

The following properties are provided by player extensions and plugins. Follow the link in the third column for further details:

propertykindextension
cuepointsarrayCuepoints extension
pluginQualitySelectorEnabledbooleanQuality selector plugin
subtitlesarraySubtitles extension

Video object

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.

Methods

methoddescription
disable([flag])disable() without argument toggles between disabled and normal API statedisable(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.

Extension methods

The following methods are provided by player extensions. Follow the link in the second column for further details:

methodextension
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

Load method

Load player

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 video

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:

  • Array of sources
    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.

  • URL as string
    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>

 

  • tip If in doubt go for the full clip object syntax instead of using a shorthand. This will make your code more self explanatory, transparent and easier to maintain in the long term.
  • Callback
    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.

Events

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:

  1. The event object; if the event was attached via jQuery, the jQuery event object. Provides fine-grained event control via its properties.
  2. Provides a handle on the player API.
  3. Optional, depends on the event.

The event properties, like targettype etc., can be inspected in the browser console:

api.on("mute", function (e) {
    console.log(e);
});

 

Here is a complete list of player events:

eventwhen it fires
beforeseekBefore 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.
disableWhen the player toggles between disabled and normal state. In disabled mode the UI elements cannot be used.
errorWhen an error occurred. The 3rd argument provides an object featuring thecode and message properties. See the error table below.
finishWhen playback has finished.
fullscreenWhen the player goes to fullscreen mode.
fullscreen-exitWhen player exits fullscreen mode.
loadFirst 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.
muteWhen the player's mute state is toggled.
pauseWhen playback is paused.
progressWhen 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.
readyWhen the video is fully loaded and video metadata (such as duration) becomes available from the video object which is provided by the 3rd argument.
resumeWhen playback is resumed.
seekWhen seeking is completed at the target position. The 3rd argument gives access to the target position.
shutdownWhen the player and API instance is destroyed, after the shutdown() methodhas been invoked. Last event in a player's life cycle.
speedWhen the playback speed is changed. The new level is provided by the 3rd argument.
stopWhen playback is stopped by the stop() method.
unloadWhen the player goes back to the splash state.
volumeWhen the volume level is changed. The new level is provided by the 3rd argument.
  • tip You will often find that Flowplayer's CSS programming capabilities provide a more elegant way to customize the player's look and feel dynamically according to its state.

Error codes

Error codes and error messages returned by the third argument of the error event are mapped the following way:

error codeerror message
1Video loading aborted
2Network error
3Video not properly encoded
4Video file not found
5Unsupported video
6Skin not found
7SWF file not found
8Subtitles not found
9Invalid RTMP URL
10Unsupported video format. Try installing Adobe Flash.

Errors 1 through 4 are HTML5 video exceptions, errors 5 through 10 are Flowplayer exceptions.

Extension events

The cuepoint event is provided by 2 player extensions. Follow the link in the second column for further details:

eventextension
cuepointCuepoints extension
cuepointSubtitles extension

Attaching events

The following methods attach (or detach) events:

methoddescription
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 
    }
});

 

API event binding

Normally events are simply attached to the API, like in the example above.

Events attached to the API return the API object.

jQuery event binding

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.

Name space

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");

 

Attaching to JavaScript installation

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
});

 

Attaching to manual installation

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.

Event chaining

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
});

 

Event prevention

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:

methodeffect
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 returnfalse 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.

Engines

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.

window.flowplayer

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

 

flowplayer.set

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.

  • caveat If the specified property is itself an Object, its nested properties are still overridden, also by omission. In the example above one would have to repeat any previous embed settings if still applicable. Only previous top-level values are merged.

flowplayer.support

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.videois true. Here are the supported properties:

  • animation - HTML animation support
  • browser - returns information about current browser and version
  • dataload - whether any video data can be loaded before hitting play
  • flashVideo - flash video support
  • firstframe - support for display of first video frame on load
  • fullscreen - native HTML5 fullscreen support
  • fullscreen_keyboard - keyboard support in fullscreen mode
  • hlsDuration - whether duration of HLS stream is natively recognized
  • inlineBlock - CSS inline-block support
  • inlineVideo - support for playing video inline
  • seekable - support for seeking when video is ready
  • subtitles - native subtitle support
  • touch - touch interface support
  • video - HTML video support
  • volume - volume support via JavaScript API
  • zeropreload - whether preload="none" completely disables preloading

Migration from Version 5

The 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
});

普通分类: