Upload a Video

Dailymotion Player Tools

JavaScript API

Overview

Users can control embedded Dailymotion video players via JavaScript calls made to the JavaScript API. Controls include but are not limited to play, pause, seek, mute and set volume.

Demo

This example shows all the features of the API (view source).

  • Waiting for the player to be ready ...
    Waiting for media progress information ...
    Waiting metadatas ...

Requirements

Flash Player 9 or higher must be installed to use the API properly. Accordingly, we recommend handling the SWF embed and Flash Player version detection with SWFObject.

Starting Out

Loading the player

You can use a chromeless player or an embedded player in your application. Both players support the same functions. However, the embedded player displays standard controls, including a play/pause button, a progress bar, a volume control, and more. The chromeless player, on the other hand, does not display any controls, so you will need to develop your own custom player controls.

  • Loading an empty player

    Use the following URL to load an empty player in your application. Once loaded the player will be totaly empty but ready to load any video through loadVideoById, cueVideoById, loadVideoByUrl or cueVideoByUrl.

    http://www.dailymotion.com/swf
  • Loading the player with a video

    Use the following URL to load the player with a video in your application. In the URL, replace the string VIDEO_ID with the Dailymotion video ID of the video that the player will show.

    http://www.dailymotion.com/swf/VIDEO_ID
  • Loading the chromeless player

    If your application is using a chromeless player, pass the URL parameter chromeless parameter to activate the chromeless mode.

    http://www.dailymotion.com/swf?chromeless=1

    or :

    http://www.dailymotion.com/swf/VIDEO_ID?chromeless=1

Enabling JavaScript API handlers

In the URL of the player you want to control, pass the URL parameter enableApi=1 to activate the JavaScript API. Model your URL as follows to embed the SWF.

http://www.dailymotion.com/swf/VIDEO_ID&enableApi=1

This command enables the player's JavaScript API handlers, and signals the player to alert the containing HTML page via a callback when the player is loaded and ready to receive JavaScript calls. Once the player is ready, the JavaScript function onDailymotionPlayerReady will be called.

Specifying the player's id

Alternatively, you may pass in a playerapiid parameter - this will identify the player when the onDailymotionPlayerReady callback is invoked. Whatever value is passed in as playerapiid will be passed back to onDailymotionPlayerReady as the first argument.

http://www.dailymotion.com/swf/VIDEO_ID&enableApi=1&playerapiid=dmplayer1

Examples below provide more details on embedding a Dailymotion player SWF into your page.

Operations

A reference to the player object you want to control is necessary to call the player API methods. To get this reference, call getElementById() on the object or embed tag containing the player SWF if using http://code.google.com/p/swfobject/ to embed the player SWF.

Queueing functions

player.loadVideo(videoId:String, type:String, parameters:Object):Void

This is the advanced and recommanded method to load a video. You need to specify the id of the video, the type (cue, play or full) and a list of parameter.

  • The required videoId parameter specifies the Dailymotion Video ID of the video to be played.
  • The type must be one of the following:
    • full: loads the full video sequence (start screen + video screen + related screen)
    • play: loads only the video screen and plays it automatically
    • cue: loads only the video screen but doesn't play it automatically, the video will be paused and the stream will start downloading.
  • The list of parameter can be an empty Object or specify any of the parameters defined in the Player's sequence Parameters documentation.

player.cueVideoById(videoId:String):Void

Loads the specified video based on it's id, but don't play it.

  • The required videoId parameter specifies the Dailymotion Video ID of the video to be played.

player.loadVideoById(videoId:String):Void

Loads the specified video based on it's id and play it.

  • The required videoId parameter specifies the Dailymotion Video ID of the video to be played.

player.cueVideoByUrl(mediaContentUrl:String):Void

Loads the specified video based on the url of it's page on dailymotion, but don't play it.

  • The mediaContentUrl must be a fully qualified Dailymotion player URL in the format http://www.dailymotion.com/video/VIDEO_ID.

player.loadVideoByUrl(mediaContentUrl:String):Void

Loads the specified video based on the url of it's page on dailymotion and play it.

  • The mediaContentUrl must be a fully qualified Dailymotion player URL in the format http://www.dailymotion.com/video/VIDEO_ID.

Playing a video

player.playVideo():Void

Plays the currently loaded/cued video.

player.pauseVideo():Void

Pauses the currently playing video.

player.stopVideo():Void

Immediately halts playback and returns the playhead to the beginning of the media file.

player.clearVideo():Void

Stops video playback, closes the NetStream object and cancels the video loading. Once clearVideo() is called, the player must be reloaded, or a new video must be loaded before video playback can be resumed.

player.seekTo(seconds:Number):Void

Seeks, in seconds, to the specified time in video playback. Note that seekTo() will attempt to find the keyframe just before the seconds specified, so that sometimes the play head may seek to ~2 seconds in advance of the requested time.

  • The seconds parameter identifies the time from which the video should start playing.
    • If the player has already buffered the portion of the video to which the user is advancing, then the player will start playing the video at the closest keyframe to the specified time. This behavior is governed by the seek() method of the Flash player's NetStream object. In practice, this means that the player could advance to a keyframe just before or just after the specified time. (For more information, see Adobe's documentation for the NetStream class.)
    • If the player has not yet buffered the portion of the video to which the user is seeking, then the player will start playing the video at the closest keyframe before the specified time.

player.setPlaybackQuality(suggestedQuality:String):Void

Changes playback quality for the current video.

Changing the player volume

player.mute():Void

Mutes the audio playback.

player.unMute():Void

Unmutes the audio playback.

player.isMuted():Boolean

If audio playback is muted, returns true, false otherwise.

player.setVolume(volume:Number):Void

Sets the volume to any integer between 0-100.

player.getVolume():Number

Returns the player's current volume as an integer between 0-100. An integer will be returned by getVolume() even if audio playback is muted.

Playback status

player.getVideoBytesLoaded():Number

Returns the number of bytes loaded for the current video.

player.getVideoBytesTotal():Number

Returns the size in bytes of the video that is currently loaded or playing.

player.getCurrentTime():Number

Returns the current time in seconds of the current video.

player.getPlayerState():Number

Returns player state, expressed by the values unstarted (-1), ended (0), playing (1), paused (2).

player.getPlaybackQuality():String

Returns playback quality when defined (sd, hq, hd720, hd1080) otherwise 'undefined'.

Retrieving video information

player.getDuration():Number

Returns the number of seconds in the current video. Until the video's metadata is loaded getDuration() will return 0 - this is common right after the video starts playing.

player.getVideoEmbedCode():String

Returns the embed code for the video currently loaded or playing.

player.getAvailableQualityLevels():Array

Returns available quality levels for the current video.

Adding an event listener

player.addEventListener(event:String, listener:String):Void

Adds a listener function for the specified event. The Events section below identifies the different events that the player might fire. The listener is a string that specifies the function that will execute when the specified event fires.

Events

onStateChange

Triggered by a change in the player state. May send one of the following values:

  • -1: Unstarted is sent when the video is loaded initially
  • 0: ended
  • 1: playing
  • 2: paused
  • 3: buffering is sent when the video begin beffuring
  • 5: and video cued is sent when the video is ready to play

onError

Triggered when an error occurs in the player. May send one of the following values:

  • stream_not_found
  • stream_rejected
  • stream_error
  • internal_error

onSeek

Dispatched when the user seeks within the video. Sends the requested time in seconds.

onVideoMetadata

Dispatched when video's metadatas are availables. Sends the following values:

  • videoDuration: the video duration in second
  • videoBitrate: the video bitrate in Byte
  • videoFramerate: the video frame rate in frames per second
  • videoCodec: the video codec
  • videoTotalSeekPoints: the video total seek point
  • quality: the video's current quality (sd, hq, hd)
  • volume: the current video volume
  • audioBitrate: the audio bitrate in Byte
  • audioCodec: the audio codec

onVideoProgress

Dispatched when constantly durring the video progression. Sends the following values:

  • mediaProgress: the current playback progression in percent
  • mediaTime: the current playback progression in seconds
  • mediaBytesTotal: the total size of the video in Bytes
  • mediaBytesReceived: the total Bytes received by the client
  • averageBandwidth: the average download bandwidth

onVideoBufferFull

Dispatched when the video finished buffering.

onLinearAdStart

Dispatched when a linear ad starts (preroll, midroll or postroll). The video is paused during a linear ad.

onLinearAdComplete

Dispatched when a linear ad ends.

onNonlinearAdStart

Dispatched when a nonlinear ad starts (overlay). The video playback does not stop during non linear ads and the ad is display over the video.

onNonlinearAdComplete

Dispatched when a nonlinear ad ad ends.

onPlaybackQualityChange

Triggered when playback quality changes. Sends suggested playback quality as a string (sd, hq, hd720, hd1080).

Event Handlers

Your HTML pages must implement a callback function named onDailymotionPlayerReady. The API will call this function when the player is fully loaded and the API is ready to receive calls.

onDailymotionPlayerReady(playerid)

Triggered when player has finished loading and the API can receive calls. Playerapiids passed into the player via URL arguments will be passed to this function, which must be implemented in the HTML page containing the Dailymotion player.

Examples

Embedding the Dailymotion player using SWFObject

Any players that will be accessed using the JavaScript API should be embedded using SWFObject. This is advisable because the JavaScript API needs Flash Player 9 or higher to function, and SWFObject can detect the version running on the user's machine. Moreover, SWFObject will suppress the "Click to activate this control" box affixed by Internet Explorer. Pass in the parameter enablejsapi=1 to activate the API in the SWF.

Below is a sample script used to embed a JavaScript API-enabled Dailymotion player, including a dmplayer playerapiid.

<script type="text/javascript" src="swfobject.js"></script>
<div id="dmapiplayer">
    You need Flash player 9+ and JavaScript enabled to view this video.
</div>

<script type="text/javascript">
    var params = { allowScriptAccess: "always" };
    var atts = { id: "mydmplayer" };
    swfobject.embedSWF("http://www.dailymotion.com/swf/VIDEO_ID&enableApi=1&playerapiid=dmplayer",
                       "dmapiplayer", "425", "356", "9", null, null, params, atts);
</script>

Because the player is not hosted on the same domain as the HTML page, the player SWF cannot call functions on the containing HTML page without the allowScriptAccess parameter.

The id of the embed object is the only attribute passed in. Here, it is mydmplayer. Dailymotion uses this ID to retreive a reference to the player via getElementById().

Use swfobject.embedSWF to load the player from Dailymotion, and to embed it.

swfobject.embedSWF(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj)

  • swfUrlStr - The URL belonging to the SWF. To enable JavaScript API calls, the enablejsapi and playerapiid parameters have been added to the normal Dailymotion SWF URL.
  • replaceElemIdStr - The HTML DIV id to be replaced by the embed content. Above, it is dmapiplayer.
  • widthStr - Player width in pixels.
  • heightStr - Player height in pixels.
  • swfVersionStr - Defines the minimum version required to view the content (here, it is Flash 8). The default line of text in the HTML DIV will be displayed to users without the minimum requirement.
  • xiSwfUrlStr - (Optional) Defines the express install SWF URL. Omitted here.
  • flashVarsObj - (Optional) Defines FlashVars in name:value pairs. Omitted here.
  • parObj - (Optional) Embed object parameters. Here, allowScriptAccess is set.
  • AttObj - (Optional) Embed object attributes. Here, the id is set to mydmplayer.

Grabbing the SWF Reference Object

When ready, the player will call onDailymotionPlayerReady.

Use getElementById() to retrieve the reference to the player. Once the object has been received, calls to the API can begin.

function onDailymotionPlayerReady(playerId)
{
  dmplayer = document.getElementById("mydmplayer");
}

Issuing Calls

Functions can now be called using the player reference. Playing a video when a link is click would look like the following example:

function play()
{
    if (dmplayer)
    {
        dmplayer.playVideo();
    }
}
<a href="javascript:void(0);" onclick="play();">Play</a>

Or,

<a href="javascript:dmplayer.playVideo()">Play</a>

Subscribing to Events

Append an event listener to the player reference to subscribe to events. To be notified of a change in player state, for example, append an event listener, including a callback function, for onStateChange.

function onDailymotionPlayerReady(playerId)
{
  dmplayer = document.getElementById("mydmplayer");
  dmplayer.addEventListener("onStateChange", "ondmplayerStateChange");
}

function ondmplayerStateChange(newState)
{
   alert("Player's new state: " + newState);
}