Javascript Player API

Introduction

The SproutVideo Javascript Player API gives you more control over the SproutVideo Video Player. Not only can you receive events from the player, but you can also control the player through Javascript.

Table Of Contents

Requirements

There are no external library requirements such as jQuery or Prototype required to use the SproutVideo Javascript Player API. All necessary requirements are included in the client library. To start using the SproutVideo Javascript Player API, include the following script somewhere in your <head>.

<script type="text/javascript" src="https://c.sproutvideo.com/player_api.js"></script>
  • SRI Hash Value: sj9/Wopla+sf2Ocv1VH0m4E7Z98Prnf/xHnzPgaoI3rjcsRrSf3UnQjMDK9Srg34
  • Date of Hash Generation: 10/25/2024

You must also be using the iframe-based embed codes. The SproutVideo Javascript Player API will not work with the legacy, <object> tag, embed codes.

NOTE: Your site needs to be served over the HTTPS protocol in order for the Javascript Player API to work. The player API will not work if your site or page is served using file://.

Supported Browsers

  • IE 9, 10 and 11
  • Edge
  • Firefox 3.6, 4, 5, 6 and greater
  • Safari 4, 5, 5.1 and greater
  • Chrome 10, 11, 12, 13, and greater
  • Opera 10.6, 11, 11.1, 11.5 and greater
  • iOS Safari 3.1, 4.0-4.1, 4.2-4.3 and greater
  • Android Browser 2.1, 2.2, 3.0 and greater

Setup

To use the SproutVideo Javascript Player API, you must create a Player instance. The constructor for the Player object takes an object that has the following properties:

Property description Required?
videoId This is the ID of the video you wish to control through the API Optional (specify either the videoId or playlistId property)
playlistId This is the ID of the video you wish to control through the API Optional (specify either the videoId or playlistId property)
var player = new SV.Player({videoId: 'abc123'});

It is recommended that the code above be run in an onLoad function, such as jQuery’s $(document).ready(), as it attempts to find the iframe in the DOM. If the iframe can not be found, an error will be thrown.

Methods

The following methods are available:

method description
bind(event,function) The bind() method allows you to execute a function when a video event is fired.
unbind(event,function) The unbind() method allows you to stop a previously binded function from executing when the event is fired.
play() The play() method will start playing the video if the player is paused or the video has not begun playing yet.
pause() The pause() method will pause the video if it is playing.
setVolume(float) The setVolume() method will set the volume of the player. setVolume accepts a float value between 0.0 and 1.0.
getVolume() The getVolume() method returns the current volume level of the player.

Returns: A float value between 0.0 and 1.0 representing the current volume of the player.
seek(float) The seek() method will seek to the given time in the video. The seek method accepts an float value representing the number of seconds from the beginning of the video to which to seek. If you try to seek to a point greater than the duration of the video, the video will start over from the beginning.
getCurrentTime() The getCurrentTime() method returns the current position of the player within the video.

Returns:A float representing the number of seconds from the beginning of the video.
getPercentLoaded() The getPercentLoaded() method returns the percentage of the video that has loaded.

Returns: A float value between 0.0 and 1.0 wich represents the percentage of bytes of the video which have been loaded.
getDuration() The getDuration method returns the duration of the video.

Returns: An integer value representing the duration of the video in seconds.
getEmail() The getEmail() method will return the email address that was collected if an email address is required to play the video or if one was passed into the embed code using the vemail parameter.

Returns: An email address if one was passed in or null if there was none collected.
setPlaybackRate(float) The setPlaybackRate() method will change the playback rate of the video. Most browsers stop playing audio outside playbackRate bounds of 0.5 and 4, leaving the video playing silently. For most applications, it’s recommended that you limit the range to between 0.5 and 4. The pitch of the audio track does not change when the playback rate is altered. Negative values will not cause the media to play in reverse.
getPlaybackRate() The getPlaybackRate() method returns the current playback rate of the video.

Returns: A float value representing the current playback rate of the video.
setQualityLevel(int/string) The setQualityLevel() method will trigger a quality level switch for the next video fragment. Pass in the hieght value of any available levels advertised by the qualityLevels event, or ‘auto’ to revert back to automatic quality switching.
getQualityLevel() The getQualityLevel() method returns the current quality level of the video.

Returns: A integer value representing the height of the currently selected quality level, or ‘auto’ if the player is set to automatically handle quality level switching on it’s own.

The following additional methods are available for playlists:

method description return value
play(index) The play() method for playlists allows you to begin playing a specific video in the playlist. The index parameter indicates which video, using a 0 based index, in the playlist to play. nothing

Events

The event object contains two properties:

  • type: The name of the event.
  • data: The data associated with the event.

Here are the different events fired by the player:

type description data
play The play event is dispatched any time the player begins playing a video. none
pause The pause event is dispatched any time the player pauses playing a video. none
loading The loading event is dispatched while the video is loading. A float value between 0.0 and 1.0 representing the percentage of the video that has been loaded.
progress The progress event is dispatched periodically as the video plays An object containing the following properties:
  • time: A float value representing the position of the playhead in seconds from the beginning of the video.
  • percent: A float valuebetween 0.0 and 1.0 representing the position of the playhead as a percentage of the total duration of the video.
  • completed The completed event is dispatched when the video has finished playing. none
    volume The volume event is dispatched whenever the volume changes. A float value between 0.0 and 1.0 that represents the new volume setting.
    ready The ready event is dispatched when the video player is ready to begin playback An object containing the following properties:
  • duration: The duration of the video in seconds.
  • viewerId: The unique identifier for the current viewer. Can be used to look up engagement sessions using our API.
  • sessionId: The unique identifier for the current playback session. Can be used to look up engagement sessions using our API.
  • email: The email address entered if the video requires an email address in ordered to be played.
  • vfname: The first name entered if the video requires a name in ordered to be played.
  • vlname: The last name entered if the video requires a name in ordered to be played.
  • rateChange The rateChange event is dispatched whenever the playback rate has changed. A float value representing the new playback rate of the video.
    qualityLevels The qualityLevels event is dispatched when the player loads and includes all of the available quality levels for the video An array containing objects with the following properties:
  • width: The width of the quality level.
  • height: The height of the quality level.
  • label: A label representing the quality level (e.g. 1080p, 4K).
  • qualityLevelChange The qualityLevelChange event is dispatched whenever the quality level is manually changed either through the player UI or the API. Automatic quality level changes will not dispatch an event. An integer representing the height of the selected quality level, or ‘auto’ if the player is set to automatically change quality levels.

    There are some additional events fired by playlists:

    type description data
    switchvideo The switchvideo event is dispatched when a new video in the playlists begins playing. An object containing the following properties:
  • videoID: The ID of the video to which the playlist just switched.
  • videoIndex: The index of the video in the playlist to which the playlist just switched.
  • playlistcomplete The playlistcomplete event is dispatched when the last video in the playlist has compelted playing none.

    Usage Examples

    Execute code the first time a video plays

    player.bind('play',function(e){
        alert('Video Playing!');
        return this.unbind; //magic unbinding!
    })
    

    As a convenience, if you return this.unbind, we’ll automatically unbind this listener. You can also unbind the function like this if you need some more control over your unbinding:

    function playHandler(e) {
        alert('Playing!');
        player.unbind('play', playHandler);
    }
    player.bind('play', playerHandler);
    

    Start the player muted

    player.bind('ready', function(e) {
        player.setVolume(0);
    });
    

    Automatically resume a video where it was left off

    In this example, we’ll use jQuery and the jQuery.cookie plugin:

    $(function(){
        var videoID = 'e898d2b5111be3c860';
        var player = new SV.Player({videoId: videoID});
        var resumeTime = $.cookie('video-' + videoID + '-time');
        
        // keep track of where the viewer is in the video
        player.bind('progress', function(e) {
          $.cookie('video-' + videoID + '-time', e.data.time);
        });
    
        // remove the cookie once the video is over
        player.bind('completed', function() {
          $.removeCookie('video-' + videoID + '-time');
        });
        
        // seek to the start time if the video has started playing
        // for the first time.
        player.bind('play', function(){
          if (!!resumeTime) {
            player.seek(resumeTime);
            resumeTime = false;
          }
        });
    });
    

    Autoplay a video only the first time a visitor visits your page:

    In this example, we’ll use jQuery and the jQuery.cookie plugin:

    $(function(){
        var videoID = 'abc123';
        var player =  new SV.Player({videoId: videoID});
    
        // check to see if the cookie has been set
        if (typeof $.cookie('video:' + videoID + ':played') == 'undefined') {
            // if not, play the video and set the cookie
            player.play();
            $.cookie('video:' + videoID + ':played', {expires: 9999});
        }
    });
    

    Display a message one minute into the video

    player.bind('progress', function(e) {
        if (e.data.time == 60) {
            alert("You've watched for a minute! Congratulations!");
        }
    });
    

    Loop a playlist

    var player = new SV.Player({playlistId:'abc123'}); // create api client
    
    // listen for the playlist complete event
    player.bind('playlistcomplete', function(e) {
        player.play(0); // start playing the first video in the playlist
    });
    

    Working Example

    Check out a working example of the SproutVideo Javascript Player API here.

    Here is a step-by-step example of building a custom skin for a player using the Javascript Player API: https://sproutvideo.com/blog/quick-and-dirty-custom-player-using-jquery-ui.html

    Was this article helpful?
    Related Articles

    Other articles in the API section: