Skip to content
Guang-De Lin edited this page Nov 3, 2017 · 49 revisions

Overview

Here are samples to demonstrate how to initialize and utilize a StraaS web player with StraaS Web Player SDK. References of player properties, player events, and player function are also provided in detail.

Breaking Change

Consider stability and compatibility, The lastest link ( https://app.straas.net/straas_sdk ) ALWAYS redirects to version 1.2.3, and is deprecated. We encourage our users to migrate to fixed URL instead of straas_sdk, and fully test in development or staging environment for new release.

Demo

Please refer to online demo/basic for the basic example.

Please refer to https://straas.github.io/straas-web-player-sdk/demo/ for all the sample codes.

HTML Sample

Below is a html sample which import StraaS SDK and index.js, index.js is the example of using StraaS SDK.

<!DOCTYPE html>
<html>
  <head> <meta charset="utf-8"> </head>
  <body>
    <div id="player"></div>
    <!-- https://github.com/StraaS/StraaS-web-player-sdk/releases //-->
    <script src="https://app.straas.net/sdk/1.3.0/player-sdk.js"></script>
    <script src="./index.js"></script>
  </body>
</html>

Import StraaS Web Player SDK

<!-- https://github.com/StraaS/StraaS-web-player-sdk/releases //-->
<script src="https://app.straas.net/sdk/1.3.0/player-sdk.js"></script>

How to use StraaS Web Player SDK

In index.js, it writes code as below to get player instance. Notice that: StraaS SDK is loads asynchronously, so you will need to put all your code running inside StraaSOnInit.

First, register a StraaSOnInit on the window:

var playerInstance
window['StraaSOnInit'] = function() {}

Next, get StraaS instance using window.StraaS:

var playerInstance
window['StraaSOnInit'] = function() {
  var StraaS = window.StraaS
}

Next, get Player class from StraaS.Player:

var playerInstance
window['StraaSOnInit'] = function() {
  var StraaS = window.StraaS

  var Player = StraaS.Player
}

Finally, initialize the player with arguments:

var playerInstance
window['StraaSOnInit'] = function() {
  var StraaS = window.StraaS

  var Player = StraaS.Player

  playerInstance = new Player(Argument1, Argument2)
}

see section Initialize player for Argument1 and Argument2

Initialize player

After getting StraaS player instance, you need to initialize it.

playerInstance = new Player(Argument1, Argument2)

Argument1 is DOM element(ex: div), in this example is div tag player. Here select it through #player and indicates it to Argument1.

playerInstance = new Player('#player', ...)

Argument2 is an object with all the required and optional configuration related to video, and event triggers.

There are some changes on new release 1.1.0. For more information, read the link as follows:

https://github.com/StraaS/StraaS-web-player-sdk/releases

player = new Player('#player', {
  type: Player.Type.VIDEO,
  id: '84HhWLCK',                        // requirement, replace by yours
  accountId: 'straas.io',                // requirement, replace by yours
  token: '',
  playerVars: {
    loop: Player.Loop.YES,
    autoplay: Player.Autoplay.YES,
    //'muted' switch is shipped with version 1.1.0
    muted: Player.Muted.YES,
    playlistMenu: Player.PlaylistMenu.YES,
    showViewsCount: true,
    objectFit: Player.ObjectFit.COVER,
    ...
  },
  videoJsOptions: {
    inactivityTimeout: 6000,
  },
  events: {...},
  deps: [...],
  plugins: [...],
})

Notice: Due to downward compatibility reason, following options are still acceptable, but they will be removed in the future release:

//Version < 1.1.0
player = new Player('#player', {
  playerVars: {
    loopPlay: Player.LoopPlay.YES,
    autoPlay: Player.AutoPlay.YES,
  }
})
  • type

    • Player.Type.VIDEO: Only single VOD
    • Player.Type.PLAYLIST:A list of VOD playlist
    • Player.Type.LIVE:A live stream
  • id (required):

    • It means video id, you can get it from StraaS management.
  • accountId (required):

    • Put your StraaS account id at this column.
  • token (optional):

    This token means jwt token, you get this token from StraaS API. And your end-user should keep this token in their device.

    • Guest does not have token (Null), if this column is Null, SDK assumes this user is a guest.
    • This token is for verifying whether this user has permission to access this video or not.
    • If VOD is free to access, you can assign arbitrary value even Null to this column.
  • videoJsOptions (optional): Use videoJsOptions to customize the StraaS Player with your own videojs options such as inactivityTimeout: 6000.

    for instance:

    var playerInstance = new Player('#player', {
      id: 'QHYo2rfH',
      accountId: 'straas.io',
      type: Player.Type.VIDEO,
      videoJsOptions: {
        // take the control bar disappear after 6 seconds (defaults 2 seconds)
        inactivityTimeout: 6000,
      }
    })
    

    for more videojs options, see videojs docs

  • deps (optional): The deps takes your urls (*.js and *.css) and SDK will import they internally, which means you can either import videojs plugins or import libraries such as lodash and jQuery on this argument.

    If You importted libraries, you can use the functionality that provided by libraries on your plugins.

    for instance:

       var playerInstance = new Player('#player', {
         id: 'QHYo2rfH',
         accountId: 'straas.io',
         type: Player.Type.VIDEO,
         deps: [
           'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js',
           'https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js',
           'https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css',
         ]
       })
    

    also see Argument2.plugins

  • plugins (optional):

    The plugins takes your argument for your videojs plugins, SDK will register and initialize the plugins internally. Before you use this, make sure you are specified urls as dependencies on the argument2.deps.

    for instance:

       var playerInstance = new Player('#player', {
         id: 'QHYo2rfH',
         accountId: 'straas.io',
         type: Player.Type.VIDEO,
         deps: [
           // for example we use the videojs plugin:
           // https://github.com/funnyordie/videojs-imageOverlay
           'https://cdn.rawgit.com/funnyordie/videojs-imageOverlay/master/videojs.imageOverlay.js',
           'https://cdn.rawgit.com/funnyordie/videojs-imageOverlay/master/videojs.imageOverlay.css',
         ],
         plugins: [
           {
             // follow the plugin usage, find the name, in this case `imageOverlay`
             name: 'imageOverlay',
             // then put plugin options here:
             options: {
               image_url: 'http://assets0.ordienetworks.com/misc/JimCarreyEyebrow.jpg',
               click_url: 'https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewAlbum?id=624854547',
               opacity: 1,
               start_time: 5,
               height: '20%',
             }
           }
         ]
       })
    
      Please refer to the demo for more details: [https://straas.github.io/StraaS-web-player-sdk/demo/plugin-usage/](https://straas.github.io/StraaS-web-player-sdk/demo/plugin-usage/)
    
  • playerVars (optional):

    loopPlay

    • Player.LoopPlay.YES

    • Player.LoopPlay.NO (default)

    autoPlay

    • Player.AutoPlay.YES - Supported on iOS 10 or above with new release 1.1.0

    • Player.AutoPlay.NO (default)

    note:

    The auto play limitation in mobile browsers is an intentional limitation put in by the OS developers.

    see section User Control of Downloads Over Cellular Networks on developer.apple.com

    see http://stackoverflow.com/questions/20499341/html5-video-autoplay-on-mobile-browser

    muted ( >= 1.1.0 )

    • Player.Muted.YES

    • Player.Muted.NO (default)

    playlistMenu

    • Player.PlaylistMenu.YES (default)

    • Player.PlaylistMenu.NO

    showViewsCount

    A threshold for views count of Video.

    • true (default) - Always show Views Count

    • false - Always hide Views Count

    • <X: number> - Show Views Count if views >= X, the reverse is hide if views < X.

      for instance:

      showViewsCount: 300 if views >= 300, show Views Count

    hidePaymentUI

    Specify the built-in payment UI will be shown or hidden.

    Useful if you are prefer to implement your own payment UI/UX.

    • true - Always hidden built-in payment UI

    • false (default) - Show built-in payment UI if payment rules exists

    objectFit

    Set object fit mode of player's video and poster.

    • Player.ObjectFit.CONTAIN (default) - Player's video and poster are sized to maintain its aspect ratio while fitting within the element’s content box.
    • Player.ObjectFit.COVER - Player's video and poster are sized to maintain its aspect ratio while filling the element’s entire content box.

Player Properties

Getters and setters of SDK player.

...
var width = player.videoWidth // get player video source width
var height = player.videoHeight // get player video source height
...

player.volume = 0.5 // set player volume to 0.5
...
  • controls

    Get or set whether or not the controls are showing.

  • currentTime

    Get or set the current time (in seconds)

  • currentLiveDateTime

    Notice: This property is available on 1.3.0(beta)

    Get recorded date & time on playback video if it is available, otherwise null is returned.

    The value of the property is measured in milliseconds which is the same as

    (new Date()).getTime()

    For more information and usage, feel free to read:

    https://github.com/StraaS/StraaS-web-player-sdk/releases/tag/1.3.0

  • duration readonly

    Get the length in time of the video in seconds.

  • ended readonly

    Get whether or not the player is in the "ended" state.

  • muted

    Get the current muted state, or turn mute on or off.

  • networkState readonly

    Get the current state of network activity for the element, from the codes in the list below.

    • NETWORK_EMPTY (numeric value 0) The element has not yet been initialised. All attributes are in their initial states.
    • NETWORK_IDLE (numeric value 1) The element's resource selection algorithm is active and has selected a resource, but it is not actually using the network at this time.
    • NETWORK_LOADING (numeric value 2) The user agent is actively trying to download data.
    • NETWORK_NO_SOURCE (numeric value 3) The element's resource selection algorithm is active, but it has not yet found a resource to use.
  • paused readonly

    Get if the player is paused.

  • playbackRate

    Get or set the current playback rate. A playback rate of 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.

  • readyState

    Get a value that expresses the current state of the element with respect to rendering the current playback position, from the codes in the list below.

    • HAVE_NOTHING (numeric value 0) No information regarding the media resource is available.
    • HAVE_METADATA (numeric value 1) Enough of the resource has been obtained that the duration of the resource is available.
    • HAVE_CURRENT_DATA (numeric value 2) Data for the immediate current playback position is available.
    • HAVE_FUTURE_DATA (numeric value 3) Data for the immediate current playback position is available, as well as enough data for the user agent to advance the current playback position in the direction of playback.
    • HAVE_ENOUGH_DATA (numeric value 4) The user agent estimates that enough data is available for playback to proceed uninterrupted.
  • seeking readonly

    Get whether or not the player is in the "seeking" state.

  • src readonly

    Get the video source.

  • videoHeight readonly

    Get video height.

  • videoWidth readonly

    Get video Width.

  • volume

    Get or set the current volume of the media.

  • viewsCount readonly

    Get player views count.

  • usersCount readonly

    Get player concurrent users count.

  • level (supported since v1.5.0)

    Get or set player's quality level.

    Getter returns a Level object, it represents a given quality level and contains quality level related info as below:

    • auto: is auto level selection enabled or not
    • bitrate: level bitrate
    • idx: level index
    • name: level name, this is for reference only
    • width: video width
    • height: video height

    See sample Level object below:

    {
      idx: 0,
      auto: true,
      bitrate: 600000,
      name: "video-360p",
      width: 640,
      height: 360
    }

    Setter takes a level index or a constant: Player.Quality.AUTO. For example: 0 ~ 2 are valid level indexes if we have 3 levels available.

    // suppose now we have 2 levels, level 360p with idx 0 and level 720p with idx 1.
    
    // get player's level
    var currentLevel = player.level // {auto: true, idx: 0, bitrate: 600000, name: "video-360p", width: 640, height: 360}
    
    // set player's level
    player.level = 1 // switch to level 720p, and turn off auto level selection
    
    player.level = Player.Quality.AUTO // turn on auto level selection
  • levels readonly (supported since v1.5.0)

    Get player's playback available quality levels.

    var levels = player.levels // [{idx: 0, bitrate: 600000, name: "video-360p", width: 640, height: 360}, {...}]

Player Events

events parameter is also included in Argument2, it handle video changed event or error event.

player = new Player(..., {
    ...
    events: {
      onVideoChange: function onVideoChange(event) {
        console.log(event)
        /*
          {
            target: player
            data: {
              video: {
                id: '84HhWLCK'
              }
            }
          }
        */
      },
      onError: function onError(event) {
        console.log(event)
        /*
          {
            target: player
            data: {
              code: Player.ErrorReason.NOT_FOUND
              reason: 'Video 84HhWLCK not found'
            }
          }
        */

        // ok, now you can do something like this:
        if (Player.ErrorReason.UNAUTHORIZED === event.data.code) {
          alert(event.data.reason)
        }
      },
      canplay: function(event) {},// This callback is triggered when video can be played
      volumechange: function(event) {},
      // ...and more events, see below
    },
  }))

onVideoChange

This event only trigger when type is Player.Type.PLAYLIST

- target: player
    - The player object

- data:
    - video
        - id:It means id of this video

onError

This event trigger when error happened.

- target: player
    - The player object

- data:
    - code
        - (1001) Player.ErrorReason.UNAUTHORIZED:You haven't logged in
        - (1003) Player.ErrorReason.FORBIDDEN:You have logged in, but you don't have permission
        - (1004) Player.ErrorReason.NOT_FOUND:The resource is not found
        - (1012) Player.ErrorReason.NOT_ALLOW_DOMAIN:內容擁有者不開放於其他網站上觀看
        - (1023) Player.ErrorReason.UNAVAILABLE:影片不公開
    - reason:Error message

abort

  • Sent when playback is aborted; for example, if the media is playing and is restarted from the beginning, this event is sent.

canplay

  • Sent when enough data is available that the media can be played, at least for a couple of frames. This corresponds to the HAVE_ENOUGH_DATA readyState.

canplaythrough

  • Sent when the ready state changes to CAN_PLAY_THROUGH, indicating that the entire media can be played without interruption, assuming the download rate remains at least at the current level. It will also be fired when playback is toggled between paused and playing. Note: Manually setting the currentTime will eventually fire a canplaythrough event in firefox. Other browsers might not fire this event.

durationchange

  • The metadata has loaded or changed, indicating a change in duration of the media. This is sent, for example, when the media has loaded enough that the duration is known.

emptied

  • The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.

encrypted

  • The user agent has encountered initialization data in the media data.

ended

  • Sent when playback completes.

loadeddata

  • The first frame of the media has finished loading.

loadedmetadata

  • The media's metadata has finished loading; all attributes now contain as much useful information as they're going to.

loadstart

  • Sent when loading of the media begins.

pause

  • Sent when playback is paused.

play

  • Sent when playback of the media starts after having been paused; that is, when playback is resumed after a prior pause event.

playing

  • Sent when the media begins to play (either for the first time, after having been paused, or after ending and then restarting).

progress

  • Sent periodically to inform interested parties of progress downloading the media. Information about the current amount of the media that has been downloaded is available in the media element's buffered attribute.

ratechange

  • Sent when the playback speed changes.

seeked

  • Sent when a seek operation completes.

seeking

  • Sent when a seek operation begins.

stalled

  • Sent when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming.

suspend

  • Sent when loading of the media is suspended; this may happen either because the download has completed or because it has been paused for any other reason.

timeupdate

  • The time indicated by the element's currentTime attribute has changed.

volumechange

  • Sent when the audio volume changes (both when the volume is set and when the muted attribute is changed).

waiting

  • The waiting event is fired when playback has stopped because of a temporary lack of data.

viewscountchange

  • Sent when player views count changed.

userscountchange

  • Sent when concurrent users count changed.

livestopped

  • Sent when streaming is stopped.

liveended

  • Sent if live Event is ended.

livepreparing

  • Sent when live is waiting for data.

livestreaming

  • Sent when live is streaming.

levelchange (supported since v1.5.0)

  • Sent when player playback's quality level changed.

Player Functions

Besides player events, player functions enable developers to control the player object in a synchronous way.

player.playVideo(): void
player.pauseVideo(): void
player.mute(): void
player.unMute(): void
player.setVolume(percent: number): void  // ex: player.setVolume(0.3)

Get iframe from player

You can get iframe object from player API getIframe().

var iframe = player.getIframe()