Skip to content
KueiHua edited this page Feb 15, 2023 · 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 config, properties, events, and functions are also provided in detail. The content of wiki is based on last version SDK. You can check Changelog to know the differences between versions.

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/2.1.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/2.1.0/player-sdk.js"></script>

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

Please refer to Player Configs for Argument1 and Argument2

Player Configs

To initialize a player instances with player configs:

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
  appToken: 'xxxxx',              // requirement, should retrieve "appToken" from the server side
  memberToken: '[YOUR MEMBER TOKEN]', // optional. If user is Guest, then this column is unnecessary
  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.
  • memberToken (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 value is null, undefined or empty string, 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

  • enableJsDeps (optional): This attribute must be true when third-party plugins is used.

  • deps (optional): SDK takes urls of your custom dependencies (*.js and *.css), and import them internally. You can either import videojs plugins or libraries such as lodash and jQuery via this argument.

    If you imports libraries, you can use the functionalities 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

  • cacheJsDeps (optional, >= 1.9.0):

    • If this option is supplied with true value, all the javascript URL defined in "deps" option will be requested without timestamp key, allowing them cached by browsers.
  • 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. There are many video.js extensions can be used. 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/)
    
  • controls (optional):

     Get or set whether or not the controls are showing.
    
  • 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)

    • Player.AutoPlay.ANY - Autoplay video normally if browser allows. If not, Mute and play video. It works on most browsers.

    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

    playlistVideoId

    Specify the initial video to play when loading the playlist.

    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.

    videoTitle ( >= 3.4.0 )

    Set the video's title attribute

    • The video control panel with the title will show on the lock screen of iOS Platform.
    • Android platforms use the top domain's title ( title tag in the HTML head section ) instead to show on the lock screen.

Player Properties

Getters and setters of SDK Web Player instances.

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

  • playbackSpeed

    Get or set the current playbackSpeed. A playbackSpeed 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

Player event handlers can be injected via events parameter in Argument2. They handle events like 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.data)
        /*
          {
              code: 2
              straasErrorCode: "CMS_API_REQUEST_TOO_MANY_REQUESTS"
              message: "The server is busy. Please try again later."
          }
        */

        // 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

  • Sent when video being played is changed.
  • This event is triggered only when type is Player.Type.PLAYLIST.
  • target: player
    • The player object
  • data:
    • video
      • id: id of this video

onError

  • Sent when an error occurred. ( >= 3.4.1 )
  • target: player
    • The player object triggering the "onError" event
  • data:

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

Player functions enable developers to control the player instance in a synchronous way.

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

playVideoAnyway function will play video if browser allows. If not, mute and then play video. It works on most browsers. We suggest you to use it in option way(please see Player.AutoPlay.ANY above) to avoid calling it multiple times.

updateConfigurations

Require player SDK version >= 3.3.2

Call this method to inform the player to load the video with specific video id

player.updateConfigurations({ id: "new video id"})

[Version 3.3.2] Only id property is permitted, other properties will be ignored.

Get iframe from player

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

var iframe = player.getIframe()