This topic describes the advanced features provided by ApsaraVideo Player SDK for web. This topic also describes how to implement these features for playback control and the playback of long videos.

Playback control

Autoplay

ApsaraVideo Player SDK for web supports autoplay. However, this feature may not be supported in specific browsers. In this case, you cannot enable autoplay by setting the autoplay attribute or calling the play() method. Videos can be automatically played only in mute mode or by manual configurations of the player. For example, after the player is initialized, you can call the setVolume method to mute the player.
Note
  • The autoplay feature is not supported in the following desktop browsers:
    • Safari 11 and later in macOS High Sierra
    • Google Chrome 55 and later
  • Autoplay may be allowed by specific mobile browsers and WebView-based apps, especially those in Android.
The following sample code provides an example on how to set the mute mode when you use an HTML5 player to play video streams based on a streaming URL:
// After the player is initialized, manually mute the player.

var player = new Aliplayer({

"id": "player-con",
// Your streaming URL. Example: example.aliyundoc.com/video/****.mp4.
"source":"<your URL>",

"width": "100%",

"height": "500px",

"autoplay": true,

"preload": true,

"controlBarVisibility": "hover",

"useH5Prism": true

}, function (player) {

player.mute()

// Alternatively, you can call the setVolume method to set the player volume to 0.

}

);

Continuous playback

The continuous playback feature enables autoplay of the next video at the end of the current video. This feature is affected by the playback sources, the player, and the playback scenarios.
  • URL-based playback
    For an HTML5 or a Flash player, you must configure the player to subscribe to the ended event. After the player receives the ended event, it calls the loadByUrl method to load the next video based on the specified URL. The following sample code provides an example:
    function endedHandle()
    {
      var newUrl = "";
      player.loadByUrl(newUrl);
    }
    player.on("ended", endedHandle);
  • Playback based on video IDs and playback credentials
    • For an HTML5 player, you can configure the player to call the replayByVidAndPlayAuth method after it receives the ended event. The ID and playback credential of the next video must be passed to the method. The following sample code provides an example:
      function endedHandle()
      {
       var newPlayAuth = "";
       player.replayByVidAndPlayAuth(vid,newPlayAuth);
      }
      player.on("ended", endedHandle);
    • A Flash player does not provide a method to switch to a video based on the video ID and playback credential. To switch to a video, you must destroy the existing player and create another player. The following sample code provides an example:
      function endedHandle()
      {
         var newPlayAuth = "";
         player.dispose(); // Destroy the existing player.
         $('#J_prismPlayer').empty();// The ID is the container ID of the player that is specified in HTML.
          // Create another player.
         player = new Aliplayer({
                   id: 'J_prismPlayer',
                   autoplay: true,
                   playsinline:true,
                   vid: vid,
                   playauth:newPlayAuth,
                   useFlashPrism:true
              });
         }
      }
      player.on("ended", endedHandle);
      Notice By default, a playback credential is valid only for 100s. When a player calls the replayByVidAndPlayAuth method, the player must pass a new playback credential to the method. For more information, see GetVideoPlayAuth.
  • Playback based on URLs of videos that use different streaming protocols
    If an MP4 video is being played and the next video uses the HTTP Live Streaming (HLS) protocol, you must create another player to enable autoplay of the next video at the end of the current video. The following sample code provides an example:
    function endedHandle()
    {
        var newUrl = ""; // The URL of the new video.
        player.dispose(); // Destroy the existing player.
         // Create another player.
       setTimeout(function(){
         player = new Aliplayer({
                  id: 'J_prismPlayer',
                  autoplay: true,
                  playsinline:true,
                  source:newUrl
             });
          }
       },1000);
    }
    player.on("ended", endedHandle);

Customize the appearance and components of the player

ApsaraVideo Player SDK for web allows you to customize the appearance of the player such as the player skin and specify whether to display the components of the player and the display area of each component. These components include user interface (UI) components of the control bar and the error UI.

  • UI components of the control bar

    You can specify whether to display the UI components and the display area of each component by setting the skinLayout attribute. For more information, see Configure the skinLayout attribute.

    • The following code provides the default configurations of the HTML5 player provided by ApsaraVideo Player SDK for web:
      skinLayout:[
         {name: "bigPlayButton", align: "blabs", x: 30, y: 80},
          {name: "H5Loading", align: "cc"},
          {name: "errorDisplay", align: "tlabs", x: 0, y: 0},
          {name: "infoDisplay"},
          {name:"tooltip", align:"blabs",x: 0, y: 56},
          {name: "thumbnail"},
          {
            name: "controlBar", align: "blabs", x: 0, y: 0,
            children: [
              {name: "progress", align: "blabs", x: 0, y: 44},
              {name: "playButton", align: "tl", x: 15, y: 12},
              {name: "timeDisplay", align: "tl", x: 10, y: 7},
              {name: "fullScreenButton", align: "tr", x: 10, y: 12},
              {name:"subtitle", align:"tr",x:15, y:12},
              {name:"setting", align:"tr",x:15, y:12},
              null
            ]
          }
        ]
    • The following code provides the default configurations of the Flash player provided by ApsaraVideo Player SDK for web:
      skinLayout:[
          {name:"bigPlayButton", align:"blabs", x:30, y:80},
          {
            name:"controlBar", align:"blabs", x:0, y:0,
            children: [
              {name:"progress", align:"tlabs", x: 0, y:0},
              {name:"playButton", align:"tl", x:15, y:26},
              {name:"nextButton", align:"tl", x:10, y:26},
              {name:"timeDisplay", align:"tl", x:10, y:24},
              {name:"fullScreenButton", align:"tr", x:10, y:25},
              {name:"streamButton", align:"tr", x:10, y:23},
              null
            ]
          },
          {
            name:"fullControlBar", align:"tlabs", x:0, y:0,
            children: [
              {name:"fullTitle", align:"tl", x:25, y:6},
              {name:"fullNormalScreenButton", align:"tr", x:24, y:13},
              {name:"fullTimeDisplay", align:"tr", x:10, y:12},
              null
            ]
          }
      ]
  • Error UI

    ApsaraVideo Player SDK for web provides a default error UI. You can also customize the error UI by using one of the following two methods. For more information, see Customize the error UI for the HTML5 player.

    • Modify the CSS file of the default error UI

      You can customize the error UI based on the default error UI. You can modify the CSS file to change the background color, font, and position and specify whether to display the error message.

    • Define a new error UI

      To define a new error UI, you must subscribe to error events.

  • Configure the player skin

    If the UI provided by ApsaraVideo Player SDK for web cannot meet your business requirements, you can modify the CSS file to customize the player skin.

    Configure the skin for an HTML5 player

    Note For more information about the configurations, see the CSS file aliplayer-min.css of the player. The following sample code provides an example on how to configure a large play button. For more information, see Configure the player skin.
    .prism-player .prism-big-play-btn {
      width: 90px;
      height: 90px;
      background: url("//gw.alicdn.com/tps/TB1YuE3KFXXXXaAXFXXXXXXXXXX-256-512.png") no-repeat -2px -2px;
    }

    Configure the skin for the Flash player

    Store the skin.png and skin.xml files in the http://[domain]/[path]/ directory. In addition, set the skinRes parameter to http://domain/path/skin for the player.

    Note The following sample code provides an example on how to configure a large play button. For more information, see Configure the player skin.
    <SubTexture name="bigPlayDown" x="2" y="94" width="90" height="90"/>
    <SubTexture name="bigPlayOver" x="94" y="2" width="90" height="90"/>
    <SubTexture name="bigPlayUp" x="2" y="2" width="90" height="90"/>

Customize the video thumbnail

Each video that you upload to ApsaraVideo VOD has a thumbnail. ApsaraVideo VOD provides multiple methods for you to change the thumbnail. Before you upload a video, you can specify an image or a video snapshot as the thumbnail. You can change the thumbnail after the video is uploaded. You can customize the video thumbnail by using one of the following methods:

  • Customize the video thumbnail in the ApsaraVideo for VOD console. For more information, see Set the video thumbnail.
  • Customize the video thumbnail by setting the cover parameter of the player.
    var player = new Aliplayer({
     "id": "player-con",
     "source":"//player.alicdn.com/video/aliyunm****.mp4",
      "cover":"Thumbnail URL",
    },
     function () { } 
    );

Video snapshot

ApsaraVideo Player SDK for web of a version later than V2.1.0 allows you to capture snapshots during playback. The captured snapshots can be of the image or JPEG type. You must configure settings for enabling the snapshot feature. When a snapshot is captured, the player returns Base64-encoded binary image data of the snapshot and the point in time at which the snapshot is captured in the source video.

Enable the snapshot feature

  • Enable the snapshot feature for an HTML5 player
    Notice You cannot capture snapshots of Flash Video (FLV) videos that are played in Safari. The snapshot button does not appear even if you enable the snapshot feature. Canvas is the element that enables the snapshot feature for an HTML5 player. You must add a header that is used to configure cross-origin resource sharing (CORS) for the playback domain. For more information, see Configure CORS.
    Add the settings of the snapshot UI to the skinLayout attribute. The following sample code provides an example:
        skinLayout:[
        {name: "bigPlayButton", align: "blabs", x: 30, y: 80},
        {
          name: "H5Loading", align: "cc"
        },
        {name: "errorDisplay", align: "tlabs", x: 0, y: 0},
        {name: "infoDisplay"},
        {name:"tooltip", align:"blabs",x: 0, y: 56},
        {name: "thumbnail"},
        {
          name: "controlBar", align: "blabs", x: 0, y: 0,
          children: [
            {name: "progress", align: "blabs", x: 0, y: 44},
            {name: "playButton", align: "tl", x: 15, y: 12},
            {name: "timeDisplay", align: "tl", x: 10, y: 7},
            {name: "fullScreenButton", align: "tr", x: 10, y: 12},
            {name:"subtitle", align:"tr",x:15, y:12},
            {name:"setting", align:"tr",x:15, y:12},
            {name: "volume", align: "tr", x: 15, y: 10},
            {name: "snapshot", align: "tr", x: 5, y: 12},
          ]
        }
      ]
    To enable the snapshot feature for an HTML5 player, you must configure CORS for videos to allow anonymous requests. The following sample code provides an example:
      extraInfo:{
        crossOrigin:"anonymous"
      }
  • Enable the snapshot feature for a Flash player
    Notice You cannot capture snapshots during the playback of Real-Time Messaging Protocol (RTMP) streams.

    To enable the snapshot feature for a Flash player, you must set the snapshot parameter to true.

Set the snapshot size and quality

Set the snapshot size and quality by calling the setSanpshotProperties(width,height,rate) method. By default, the size of a JPEG image is the same as that of a snapshot captured when you play a video. The following sample code provides an example:
// Set the width to 300, the height to 200, and the quality to 0.9.
// The unit of height and width is pixel. You can set the quality to a value ranging from 0 to 1. Default value: 1.
player.setSanpshotProperties(300,200,0.9)

Subscribe to the snapshoted event

After a snapshot is captured, the snapshoted event is triggered and the snapshot data is returned. The following sample code provides an example:
player.on("snapshoted", function(data) {
     console.log(data.paramData.time);
     console.log(data.paramData.base64);
     console.log(data.paramData.binary);
 });
The following list describes the parameters:
  • time: the point in time of the snapshot.
  • base64: the Base64-encoded string of the snapshot. It can be directly used to display the image.
  • binary: the binary data of the snapshot. It can be used to upload the image.

Text watermark

If you use an HTML5 player, you can set the snapshotWatermark attribute to add a text watermark to a snapshot. The following table describes the parameters in the attribute.
Parameter Description
left The distance to the left side.
top The height of the upper-left corner, including the height of text.
text The text in the watermark.
font The format of the text. You can set multiple font attributes together by separating them with spaces.
  • font-style: specifies the font style.
  • font-weight: specifies the font weight.
  • font-size: specifies the font size.
  • font-family: specifies the font family.
strokeColor The color that is used to stroke the path of the shape.
fillColor The color that is used to fill the shape.
The following sample code provides an example:
snapshotWatermark:{
    left:"100",
    top:"100",
    text:"test",
    font:"italic bold 48px arial",
    strokeColor:"red",
    fillColor:'green'
  }

Features for long videos

Adaptive bitrate streaming for HLS streams

To play videos in multiple bitrates, you must set the source parameter to a multi-bitrate streaming URL, which is called a master playlist. In addition, you must set the isVBR parameter to true. The adaptive bitrate streaming feature supports automatic definition switching based on the network environment. You can also manually switch the definition as needed.

Obtain the streaming URL

Obtain the streaming URL of the video in multiple bitrates: player._hls.levels[player._hls.currentLevel].

1
Note
  • The bitrate of the current video stream is not displayed in the player in Safari if Quality is set to Auto.
  • HLS streams are processed in a workflow in which an adaptive bitrate streaming template is used. To configure a template group that contains the adaptive bitrate streaming template to be used in the workflow, log on to the ApsaraVideo VOD console and choose Configuration Management > Media Processing > Transcoding Template Groups. On the page that appears, configure a template group as needed. For more information, see Configure video packaging templates.
The following sample code provides an example:
varplayer = newAliplayer({
 "id":"player-con",
 "source":"Multi-bitrate streaming URL",
 "isVBR":true,
 },
 function () { } 
);

The following figure shows the definition switching option after configuration.

Effect diagram

External subtitles

You can add external subtitles by using a subtitle template in a template group that is configured in the ApsaraVideo VOD console. No manual configurations are required for ApsaraVideo Player SDK for web. You can add external subtitles only if you play videos based on video IDs and playback credentials.

External subtitles
In addition to default UI components, ApsaraVideo Player SDK for web also provides the CCService plug-in to meet your business requirements, including switching languages of subtitles based on browsers. You can use the player._ccService attribute to customize the subtitles. The following table describes the subtitle-related functions that you can use.
Function Parameter Description
switch language Changes the language of subtitles.
open N/A Enables subtitles.
close N/A Disables subtitles.
getCurentSubtitle N/A Obtains the language of the subtitles.

Multiple audio tracks

No manual configurations are required for ApsaraVideo Player SDK for web. The following figure shows the effect of multiple audio tracks in the player.

2

Multiple languages

By default, ApsaraVideo Player SDK for web supports Chinese and English and automatically switches to Chinese or English based on the language settings of the browser. In addition, ApsaraVideo Player SDK for web allows you to customize other languages. ApsaraVideo Player SDK for web also allows you to play video resources in multiple regions based on ApsaraVideo VOD. You can play video resources stored in regions of Southeast Asia and Europe based on video IDs and playback credentials.

Usage notes for the language parameter

You can set the language parameter to specify a language for the player that overwrites the language setting of the browser. By default, this parameter is left empty. The following sample code provides an example:
var player = new Aliplayer({
    id: "player-con",
    source: "",
    width: "100%",
    height: "500px",
    autoplay: true,
    language: "en-us",
  }, function (player) {
    console.log("The player is created.");
  });

Create a player with UI elements in English

var player = new Aliplayer({
 "id": "player-con",
 "source": "",
 "language": "en-us" // A value of zh-cn indicates the Chinese language. A value of en-us indicates the English language. 
 },
 function (player) {}
);

Customize a language for the player

If you want the player to support UI elements in languages except for Chinese and English, you must specify the language by using the languageTexts attribute, which contains a list of key-value pairs. The value of the language attribute indicates the key, and the JSON value indicates the UI elements to be translated into the specified language. The following sample code provides an example:

Note If you cannot determine the UI elements that need to be translated, you can use the online configuration tool. Click Online Settings to go to the Online Settings page. In the upper part of the page, click the Advanced tab. On the Advanced tab, select Custom for the Language parameter. Then, the Custom Language Settings dialog box appears. In the dialogue box, translate the required UI elements into the specified language. Then, you can click the Code tab to view the generated code.
var player = new Aliplayer({
 "id": "player-con",
 "source": "",
 "language": "The specified language",// Specify a language in the STRING type.
"languageTexts":{
    "CustomLanguage":{
        "Pause":"Pause"
        // Other parameters. For more information, visit https://player.alicdn.com/lang.json? spm=a2c4g.11186623.0.0.5a746515vnwUSi&file=lang.json
            }
        }
    },
    function (player) {} 
);
Note
Play video resources of multiple regions

ApsaraVideo Player SDK for web allows you to play videos stored in the China (Shanghai), Germany (Frankfurt), and Singapore (Singapore) regions of the ApsaraVideo VOD service. You can play videos based on video IDs and playback credentials or Security Token Service (STS). The player parses the region information and obtains the streaming URL of the video in this region of the ApsaraVideo VOD service.

  • Playback based on video IDs and playback credentials: The player parses the region information from the playback credential to obtain the streaming URL of the video. In this case, you do not need to specify the region in the configurations.
  • STS-based playback: You can specify the region in which the video you want to play resides by setting the region parameter. Valid values of the region parameter: cn-shanghai, eu-central-1, and ap-southeast-1. Default value: cn-shanghai. The following sample code provides an example:
    var player = new Aliplayer({
        id: "player-con",
        width: "100%",
        height: "500px",
        autoplay: true,
        language: "en-us",
        vid : '1e067a2831b641db90d570b6480f****',
        accessKeyId: '',
        securityToken: '',
        accessKeySecret: ''
        region:'eu-central-1, // The Germany (Frankfurt) region.
      }, function (player) {
        console.log("The player is created.");
      });

Time shifting of live streaming by using an HTML5 player

  • Enable time shifting
    • You must enable time shifting in ApsaraVideo Live. For more information, see Time shifting.
    • The following table describes the attributes that you must set to enable time shifting for a player.
      Attribute Description
      isLive Set the value to true.
      liveTimeShiftUrl The URL that is used to query the time shifting information.
      liveStartTime The start time of live streaming.
      liveOverTime The end time of live streaming.
      liveShiftSource The HLS URL for time shifting.
      Note This attribute is set only for FLV live streams.
      liveShiftMinOffset A specific period of time is required for generating TS segments during time shifting. If you seek to a position that is extremely close to the current live streaming time, TS segments fail to be generated and a 404 error is reported. A minimum period of time must be specified between the seek position and the current live streaming time. You can set this parameter to specify the period of time in seconds. Default value: 30. A segment is generated every 10 seconds. This ensures that at least three segments exist.
  • Time shifting UI
    The time shifting UI consists of a progress bar, which displays time in the area that supports time shifting.
    Note The time area displays the current playback time, end time of live streaming, and current live streaming time from left to right.
  • Change the end time of live streaming
    You can call the liveShiftSerivce.setLiveTimeRange method to change the start and end time of live streaming. The UI changes along with the changes. The following sample code provides an example:
    player.liveShiftSerivce.setLiveTimeRange("",'2018/01/04 20:00:00')
  • FLV for live streaming and HLS for time shifting

    To reduce latency, we recommend you use FLV for live streaming and HLS for time shifting.

    Configurations of ApsaraVideo Player SDK:
    • source: the FLV URL for live streaming.
    • liveShiftSource: the HLS URL for time shifting.
    The following sample code provides an example:
    {
     source:'http://localhost/live****/example.flv',
     liveShiftSource:'http://localhost/live****/example.m3u8',
    }