This topic describes the advanced features provided by ApsaraVideo Player SDK for Web. This topic also describes how to use common playback control features and how to integrate and use the features that are ideal for long video scenarios.

Playback control

Autoplay

  • ApsaraVideo Player SDK for Web supports autoplay.

    Many browsers have introduced stricter policies on autoplay. You cannot set the autoplay attribute or call the play() method to enable autoplay. Autoplay can be achieved through two methods: manual configuration by the user, or playing muted videos. For example, after the player is initialized, you can call the setVolume method to mute the videos.
    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 in specific mobile browsers and WebView apps, especially those in Android.
    The following sample code provides an example on how to mute videos when you use an HTML5 player to play video streams based on playback URLs:
    // After the player is initialized, manually mute the video.
    
    var player = new Aliplayer({
    
    "id": "player-con",
    // The playback 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 setVolume to set the player volume to 0.
    
    }
    
    );
  • The autoplay feature can be enabled in WeChat for iOS. Sample code:
    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script>
    function autoPlay() {
                wx.config({
                    // The configuration information. The wx.ready method can be called even if the configuration information is invalid.
                    debug: false,    // false indicates that the debug mode is disabled and true indicates that the debug mode is enabled.
                    appId: '',       //appId
                    timestamp: 1,    // The timestamp when the signature is generated.
                    nonceStr: '', // A random string that is used to generate the signature.
                    signature: '',   // The signature.
                    jsApiList: []    // The required JS APIs.
                });
                wx.ready(function() {
                    if(player) // The ApsaraVideo Player object that is created.
                    {
                      player.play();
                    }
                });
        };
        // The video autoplay feature is enabled for iOS devices.
        autoPlay();
    </script>

Continuous playback

The continuous playback feature enables autoplay for the next video after the playback of the current video ends. This feature is affected by the playback methods, the player, and the playback scenarios.
  • URL-based playback
    For HTML5 and Flash players, you must configure the player to subscribe to the ended event. Then, the player calls the loadByUrl method in the ended event to load the next video based on the specified URL. Sample code:
    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 in the ended event. You must specify the vid and playauth of the next video in the call. Sample code:
      function endedHandle()
      {
       var newPlayAuth = "";
       player.replayByVidAndPlayAuth(vid,newPlayAuth);
      }
      player.on("ended", endedHandle);
    • Flash players do not provide a method to switch to a video based on vid and playauth. To switch to the next video, you must destroy the existing player and create another player. Sample code:
      function endedHandle()
      {
         var newPlayAuth = "";
         player.dispose(); // Destroy the existing player.
         $('#J_prismPlayer').empty();// Configure the id parameter. This parameter indicates the container ID of the player specified in the HTML page.
          // Create another player.
         player = new Aliplayer({
                   id: 'J_prismPlayer',
                   autoplay: true,
                   playsinline:true,
                   vid: vid,
                   playauth:newPlayAuth,
                   useFlashPrism:true
              });
         }
      }
      player.on("ended", endedHandle);
      Important By default, a playback credential is valid for only 100s. You must obtain a new playauth when you call the replayByVidAndPlayAuth method. For more information, see GetVideoPlayAuth.
  • Switch the video playback protocol
    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 for the next video after the playback of the current video ends. Sample code:
    function endedHandle()
    {
        var newUrl = ""; // Specify the URL of the next 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 the control bar and the error UI.

  • Control bar

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

    • The following code shows 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},
              {name: "volume", align: "tr", x: 5, y: 10}
            ]
          }
        ]
    • The following code shows 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},
              {name:"volume", align:"tr", x:10, y:25}
            ]
          },
          {
            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},
              {name:"fullZoom", align:"cc"}
            ]
          }
      ]
  • 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.

    • Rewrite the CSS file of the default error UI

      You can customize the error UI based on the default layout of the player. You can rewrite the CSS file to change the background color, font, and position of the UI 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 rewrite 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 a Flash player

    Store the skin.png and skin.xml files in the http://[domain]/[path]/ directory. Then, 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 also change the thumbnail after the video is uploaded. You can configure the video thumbnail by using one of the following methods:

  • Configure the video thumbnail in the ApsaraVideo VOD console. For more information, see Set the video thumbnail.
  • Configure 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 snapshots

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 to enable the snapshot feature. When a snapshot is captured, the player returns Base64-encoded binary image data of the snapshot and the playback position at which the snapshot is captured in the source video.

Enable the snapshot feature

  • Enable the snapshot feature for an HTML5 player
    Important You cannot capture snapshots from 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. Sample code:
        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
    Important 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

Call the setSanpshotProperties(width,height,rate) method to set the snapshot size and quality. By default, the size of the snapshot is the same as that of a video image. Sample code:
// Set the snapshot width to 300, height to 200, and quality to 0.9.
// The snapshot height and width are displayed in pixels. You can set the snapshot quality to a value ranging from 0 to 1. The default value is 1.
player.setSanpshotProperties(300,200,0.9)

Subscribe to the snapshot event

After a snapshot is captured, the snapshoted event is triggered and the snapshot data is returned. Sample code:
player.on("snapshoted", function(data) {
     console.log(data.paramData.time);
     console.log(data.paramData.base64);
     console.log(data.paramData.binary);
 });
The following items describe the parameters:
  • time: the playback position at which the snapshot is captured.
  • 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.

Snapshot watermark

If you use an HTML5 player, you can set the snapshotWatermark attribute to add a watermark to a snapshot. The following table describes the parameters in the attribute.
Parameter Description
left The distance between the left side of the watermark and the left side of the snapshot.
top The distance between the bottom of the watermark and the top of the snapshot.
text The text in the watermark.
font The format of the text. You can separate multiple attributes with spaces to set multiple attributes at a time.
  • 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 stroke color.
fillColor The color that is used to fill the shape.
Sample code:
snapshotWatermark:{
    left:"100",
    top:"100",
    text:"test",
    font:"italic bold 48px arial",
    strokeColor:"red",
    fillColor:'green'
  }

Features for long videos

Adaptive bitrate switching for HLS streams

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

Obtain the playback URL

Obtain the playback 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 on players in Safari if Quality is set to Auto.
  • HLS video streams are processed in a workflow in which a transcoding template group is used. To configure a template group, 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.
Sample code:
varplayer = newAliplayer({
 "id":"player-con",
 "source":"Multi-bitrate playback URL",
 "isVBR":true,
 },
 function () { } 
);

The following figure shows the definition switching option after the configuration.

Effect diagram

External subtitles

The following types of Web Video Text Tracks (WebVTT) subtitles are supported in ApsaraVideo Player SDK for Web:
  • Internal subtitles for HLS (M3U8) videos: You can use a video ID and a playback credential or use a URL to play an HLS video with the WebVTT subtitles. The HLS videos can be transcoded and generated by ApsaraVideo VOD or a third-party service.
  • External subtitles: You can set the textTracks parameter or call setTextTracks to import external WebVTT subtitles. For more information about the method, see API operations.
External subtitles
In addition to default UI components, ApsaraVideo Player SDK for Web also provides the CCService plug-in to meet your business requirements, such as 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 Turn on subtitles.
close N/A Turn off subtitles.
getCurrentSubtitle N/A Obtains the language of the subtitles.
Sample code:
// Change the subtitle language.
var lang = 'zh-Hans/en-US';
player._ccService.switch(lang);
player._ccService.updateUI(lang); // The UI elements are not automatically updated. You can manually call API operations to update the UI elements.

// Turn on subtitles.
var result = player._ccService.open();
player._ccService.updateUI(result.language);

// Turn off subtitles.
player._ccService.close();
player._ccService.updateUI();

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 between Chinese and English based on the language settings of the browser. ApsaraVideo Player SDK for Web allows you to customize other languages. ApsaraVideo Player SDK for Web allows you to play videos in multiple regions based on ApsaraVideo VOD. You can play videos 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" // zh-cn indicates the Chinese language. 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 besides Chinese and English, you must specify 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. Sample code:

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": "CustomLanguage",// 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) {} 
);
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. You can play videos by using video IDs and playback credentials or by using Security Token Service (STS). The player parses the region information and obtains the playback URL of the video in this region.

  • Playback based on video IDs and playback credentials: The player parses the region information from the playback credential to obtain the playback 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 for 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 in HTML5 players

  • Enable time shifting
    • You must enable the time shifting feature in ApsaraVideo Live. For more information, see Time shifting.
    • The following table describes the attributes that you must set to enable the time shifting feature 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 required 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 a 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 when the start or end time changes. Sample code:
    player.liveShiftSerivce.setLiveTimeRange("",'2018/01/04 20:00:00')
  • Switch between FLV and HLS formats for live streaming and time shifting

    To reduce latency, we recommend that you use the FLV format for live streams and the HLS format for time shifting streams.

    Configurations of ApsaraVideo Player SDK for Web:
    • source: The URL of the live stream in the FLV format.
    • liveShiftSource: The URL of the time shifting stream in the HLS format.
    Sample code:
    {
     source:'http://localhost/live****/example.flv',
     liveShiftSource:'http://localhost/live****/example.m3u8',
    }