All Products
Search
Document Center

ApsaraVideo VOD:Advanced features

Last Updated:Aug 01, 2024

This topic describes how to use common playback control features such as autoplay, custom player skin and UI, and snapshot capture in ApsaraVideo Player SDK for Web. This topic also describes how to use features that are suitable for long video scenarios and how to play H.265 and H.266 videos.

Playback control

Autoplay

  • ApsaraVideo Player SDK for Web supports autoplay.

    Many browsers impose stricter policies on autoplay. You cannot specify the autoplay attribute or call the play() method to enable autoplay. You can only enable autoplay by using the following methods: manual configuration or muting a video. For example, after a player is initialized, you can call setVolume to mute the video.

    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.

    • Browsers such as WeChat and QQ Browser use the built-in players for playback. In this case, autoplay is not supported even when the video is muted. For more information, see Video playback issues due to browser hijacking.

    The following sample code provides an example on how to automatically play videos in the mute mode when you use an HTML5 player for URL-based playback:

    • ApsaraVideo Player SDK for Web V2.20.3 and later

      var player = new Aliplayer({
        "id": "player-con",
        // The playback URL. Example: example.aliyundoc.com/video/****.mp4.
        "source":"<your URL>",
        "autoplay": true,
        "mute": true
        }, function (player) {});
    • ApsaraVideo Player SDK for Web of a version earlier than V2.20.3

      // After the player is initialized, mute the video.
      var player = new Aliplayer({
        "id": "player-con",
        // The playback URL. Example: example.aliyundoc.com/video/****.mp4.
        "source":"<your URL>",  
        "autoplay": true
        }, function (player) {
        player.mute()
        // Alternatively, you can call setVolume to set the player volume to 0.
        }
      );
  • You can enable the autoplay feature in WeChat for iOS. Sample code:

    <div id="player-con"></div>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script>
    wx.config({
        // The configuration information. You can call the wx.ready method 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 JavaScript APIs.
    });
    wx.ready(function() {
      // Initialize the player.
      createPlayer();
    });
    
    function createPlayer() {
      var player = new Aliplayer({
        id: 'player-con',
        source: '',
        autoplay: true
      });
    }
    </script>

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 methods, the player, and the playback scenarios.

  • URL-based playback

    For HTML5 and Flash players, you can 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 parameters of the next video in the request. Sample code:

      function endedHandle()
      {
       var newPlayAuth = "";
       player.replayByVidAndPlayAuth(vid,newPlayAuth);
      }
      player.on("ended", endedHandle);
    • Flash players do not provide a method to switch to the next video based on vid and playauth. To switch to the next video, you need to destroy the existing player and create a new one. Sample code:

      function endedHandle()
      {
         var newPlayAuth = "";
         player.dispose(); // Destroy the existing player.
         $('#J_prismPlayer').empty();// Configure the id parameter. This parameter specifies the container ID of the player specified in the HTML page.
          // Create a new 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 a new 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 a new 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.

  • 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 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 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 the 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. Then, specify skinRes:"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:

  • 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 attribute 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. The snapshot feature must be separately enabled. 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 from the source video.

Enable the snapshot feature

  • Enable the snapshot feature for the 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 allows 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 set crossOrigin to anonymous to allow anonymous cross-origin requests. Sample code:

      extraInfo:{
        crossOrigin:"anonymous"
      }
  • Enable the snapshot feature for the Flash player

    Note

    You cannot capture snapshots during the playback of Real-Time Messaging Protocol (RTMP) streams.

    To enable the snapshot feature for the Flash player, you must set the snapshot attribute 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 the source video. 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 snapshoted 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. The value can be directly used to display the img file.

  • binary: the binary data of the snapshot. The value 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.

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 text attributes. You can separate multiple attributes with spaces. Valid values:

  • font-style

  • font-weight

  • font-size

  • 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'
  }

Disable seeking on the progress bar

If you want to disable seeking on the progress bar, listen for the seeking event on the client side. This way, when a user drags the progress handle on the progress bar, the player seeks to the old playback position. Sample code:

const player = new Aliplayer({
  "id": "player-con",
  "source": "https://player.alicdn.com/video/aliyunmedia.mp4",
  "width": "100%",
}, function (player) {
    console.log("The player is created");
  }
);

let lastTime = 0;
player.on('timeupdate', () => {
  if (!player.tag.seeking) {
    // Obtain the last playback position.
    lastTime = player.getCurrentTime();
  }
})

player.on('seeking', () => {
  var delta = player.getCurrentTime() - lastTime;
  if (Math.abs(delta) > 0.01) {
    console.log("Seeking is disabled");
    // The player seeks to the old playback position when a user drags the progress handle.
    // This feature is not available in QQ Browser for iOS because you cannot obtain or modify the currentTime parameter in QQ Browser.
    player.tag.currentTime = lastTime;
  }
});

player.on('ended', function() {
    lastTime = 0;
});

Features for long videos

Adaptive bitrate streaming for HLS streams

To play a video in multiple bitrates, you must set the source parameter to a multi-bitrate playback URL, which is called a master playlist. You must also set the isVBR parameter to true. Adaptive bitrate streaming adjusts video quality based on network conditions. You can also adjust video quality based on your business requirements.

Obtain the playback URL

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

1

Note
  • If you set Quality to Auto, the current bitrate of the video stream is not displayed on players in Safari.

  • HLS video streams are processed in a workflow in which a transcoding template group is used. To configure a transcoding 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 based on your business requirements. 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 video quality setting.

效果图

Configure external subtitles

The following types of Web Video Text Tracks (WebVTT) subtitles are supported in ApsaraVideo Player SDK for Web:

  • Embedded subtitles in HLS (M3U8) videos: You can use a video ID and a playback credential or use a URL to play an HLS video with WebVTT subtitles embedded. The HLS video can be transcoded and generated by ApsaraVideo VOD or a third-party service.

  • External subtitles: You can set textTracks or call setTextTracks to import external WebVTT subtitles. For more information about the method, see API operations.

外挂字幕

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 browser language settings. You can specify player._ccService to use subtitles. The following table describes the subtitle-related functions that you can use.

Function name

Parameter

Description

switch

language

Changes the language of subtitles.

open

N/A

Turns on subtitles.

close

N/A

Turns 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 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 audio track setting.

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 specify custom 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 attribute

You can set the language attribute to specify a language for the player that overwrites the language setting of the browser. By default, this attribute is left empty. Sample code:

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 Chinese. en-us indicates English. 
 },
 function (player) {}
);

Specify a custom language for the player

If you want the player to support UI resources in languages other than Chinese and English, you must specify the languageTexts attribute. languageTexts contains a list of key-value pairs. The value of the language attribute specifies the key, and the JSON value specifies the UI resources to be translated into the specified language. Sample code:

Note

If you cannot determine the UI resources that you want to translate, you can use the online configuration tool. Visit Aliplayer to go to the Online Settings page. In the upper part of the page, click the Advanced tab. On the Advanced tab, select Custom from the Language drop-down list. Then, the Custom Language Settings dialog box appears. In the dialog box that appears, translate the required UI resources into the specified language. Then, 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 that are stored in multiple regions

ApsaraVideo Player SDK for Web allows you to play videos stored in the China (Shanghai), Germany (Frankfurt), and 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 the corresponding 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 attribute. Valid values for the region attribute: cn-shanghai, eu-central-1, and ap-southeast-1. Default value: cn-shanghai. Sample code:

    var player = new Aliplayer({
        id: "player-con",
        width: "100%",
        height: "500px",
        autoplay: true,
        language: "en-us",
        vid : '1e067a2831b641db90d570b6480f****',
        accessKeyId: '',// The AccessKey ID that is generated when the temporary STS token is issued. 
        securityToken: '',// The temporary STS token. To generate an STS token, call the AssumeRole operation. 
        accessKeySecret: ''// The AccessKey ID that is generated when the temporary STS token is issued. 
        region:'eu-central-1',// The Germany (Frankfurt) region.
      }, function (player) {
        console.log("The player is created.");
      });

Play H.265 and H.266 videos

Usage notes

  • ApsaraVideo Player SDK for Web V2.14.0 or later supports playback of H.265 videos and ApsaraVideo Player SDK for Web V2.20.2 or later supports playback of H.266 videos. To play H.265 and H.266 videos, submit a request on Yida to apply for a license.

  • For more information about the formats of H.265 and H.266 audio and video files that you can play by using ApsaraVideo Player SDK for Web, see Supported protocols.

  • Before you play H.265 and H.266 videos, take note of the requirements described in the following table.

    Item

    Description

    Environment requirements

    The player sends AJAX range requests to access video resources. Your browser must meet the following requirements:

    • Supports HTTP range requests. For more information, see HTTP range requests.

    • Supports the OPTIONS method. Before a browser such as Firefox sends an AJAX request with a range header, the browser first sends an HTTP OPTIONS request.

    Compatibility

    • H.265

      • Devices that run iOS 11 or later support playback of H.265 videos.

      • Specific browsers on Android devices such as the built-in browser, WeChat browser, UC Browser, and QQ Browser support hardware decoding of H.265 videos.

      • The support for software decoding of H.265 videos on browsers such as Chrome, Microsoft Edge, and Firefox depends on whether the browsers support the WebAssembly API. For more information, visit WebAssembly. If you use Chrome or Chromium on your device, update Chrome or Chromium to V74 or later. WebAssembly cannot work as expected on Chrome and Chromium of versions earlier than V74.

    • H.266

      • No browser natively supports playback of H.266 videos. In this case, software decoding is required to play H.266 videos in browsers. The support for software decoding of H.266 videos on browsers depends on whether the browsers support the WebAssembly API. For more information, visit WebAssembly. If you use Chrome or Chromium on your device, update Chrome or Chromium to V74 or later. WebAssembly cannot work as expected on Chrome and Chromium of versions earlier than V74.

      • Devices that run iOS 16.4 or earlier and most medium and low-end Android devices do not support software decoding of H.266 videos.

    Software decoding performance

    • H.265

      • You can use browsers on PCs to play videos that are in 2K or lower resolutions in multi-thread processes and play videos in 1080p or lower definitions in single-thread processes. The frame rates of the videos cannot exceed 30 frames per second (FPS).

      • You can use browsers on mobile devices to play videos that are in 720p or lower resolutions in single-thread processes. The frame rates of the videos cannot exceed 30 FPS. The software decoding performance of a mobile device varies based on the chip performance of the device. The following items describe the chips that support software decoding of videos in single-thread processes. The videos are in 720p and the FPS of the videos are 30.

        • Snapdragon 855 or later

        • Kirin 820 or later

        • Tianjic 800 or later

    • H.266

      • You can use browsers on PCs to play videos that are in 1080p or lower resolutions in multi-thread processes and play videos in 720p or lower definitions in single-thread processes. The frame rates of the videos cannot exceed 30 FPS.

      • You can use browsers on mobile devices to play videos that are in 720p or lower resolutions in single-thread processes. The frame rates of the videos cannot exceed 30 FPS. The software decoding performance of a mobile device varies based on the chip performance of the device. The following items describe the chips that support software decoding of videos in single-thread processes. The videos are in 720p and the FPS of the videos are 30.

        • Snapdragon 855 or later

        • Kirin 820 or later

Integrate the ApsaraVideo Player SDK for Web

Play H.265 videos

<div class="prism-player" id="player-con"></div>
<script>
var options = {
  id: "player-con",
  source: "//demo.example.com/video/test/h265/test_480p_mp4_h265.mp4",
  enableH265: true,
  license: {
    domain: "example.com",
    key: "example-key"
  }
}
var player = new Aliplayer(options);
</script>

Play H.266 videos

<div class="prism-player" id="player-con"></div>
<script>
var options = {
  id: "player-con",
  source: "//demo.example.com/video/test/h266/test_480p_mp4_h266.mp4",
  enableH266: true,
  license: {
    domain: "example.com",
    key: "example-key"
  }
}
var player = new Aliplayer(options);
</script>

Parameter

Description

id

The container ID of the player. Make sure that the container ID is included in DOM.

source

The playback URL. You can specify URLs of H.264, H.265, or H.266 videos.

enableH265/enableH266

If you specify URLs of H.265 or H.266 videos for the source parameter, set this parameter to true. In this case, the player loads a small amount of data to sniff the video codec and then determines whether H.265 or H.266 videos can be played on the current device.

Note

After you set this parameter to true, ApsaraVideo Player SDK for Web pulls video streams. This consumes traffic and increases the loading time.

license.domain

The top-level domain that you specified when you apply for a license. For example, if you want to use ApsaraVideo Player SDK for Web on example.com/product/vod, specify example.com for this parameter.

license.key

The key that is issued when the license file is generated. The key is a string of 49 characters.

The following sample code provides an example on how to specify URLs of videos in multiple definitions for the source parameter. For more information about the supported definitions, see Multi-definition playback.

Note

If you specify URLs of videos in multiple definitions for the source parameter, the video codecs must be the same. In this case, you can specify URLs of only H.264, H.265, or H.266 videos.

{
  //... Configure other parameters.
  source: JSON.stringify({
      FD: '//h265_fd.mp4',
      HD: '//h265_hd.mp4'
    }),
}

Select a decoding method

ApsaraVideo Player SDK for Web selects an optimal decoding solution based on the video codec and the browser environment. The following logic applies:

  1. For H.265 videos, the player checks the capabilities of the browser and selects a decoding method in the following order: playback based on the video source > playback based on Media Source Extensions (MSE) > software decoding by using WebAssembly and playback by using Canvas. This ensures the decoding performance.

  2. If you use WebAssembly for software decoding, the player enables multi-tread processing or single instruction, multiple data (SIMD) processing based on the capabilities of the browser to provide optimal decoding performance. For more information, visit Roadmap.

Use a degraded protocol for playback

H.265 playback degradation

If an H.265 video fails to be played or stuttering occurs during playback, we recommend that you configure an error message to notify the user. You can also specify to automatically play the H.264 video if the H.265 video fails to be played or stuttering occurs during the playback. The following section describes the common causes of playback failures or stuttering:

  • Cause 1: Your browser does not support the API operations that are required for software decoding, including WebAssembly, Canvas, and Web Worker.

  • Cause 2: Video decoding failed due to encoding errors or decoder compatibility issues.

  • Cause 3: The hardware performance of your device is poor and the speed of software decoding does not match the normal playback speed.

You can listen to the events of ApsaraVideo Player for Web to obtain information about the errors that occur during the playback of H.265 videos.

  • Listen to the error event of the player. If an error code from 4300 to 4304 is returned, an error occurred during the playback of H.265 or H.266 videos. In this case, Cause 1 or Cause 2 described in the preceding section applies.

  • Listen to the h265DecoderOverload event of the player. If an h265DecoderOverload event occurs, Cause 3 described in the preceding section applies.

The following sample code provides an example on how to listen to events:

player.on('error', (e) => {
        var code = String(e.paramData.error_code);
    if (['4300', '4301', '4302', '4303', '4304'].indexOf(code) > -1) {
      // Notify the user or use a degraded protocol for playback if the API operation is not supported in your browser or video decoding failed.
    }
});

player.on('h265DecoderOverload', (e) => {
    var data = e.paramData;
    // data.decodedFps specifies the number of frames per second that are decoded by using software decoding.
    // data.fps specifies the frame rate of the current video.
    // data.playbackRate specifies the current playback speed.
    // If the product of data.fps and data.playbackRate is greater than data.decodedFps for more than 5 seconds, an error event occurs. In this case, stuttering may occur during playback. You need to notify the user or use a degraded protocol for playback.
});
                            

The following sample code provides an example on how to configure a degradation logic:

  var player;

  // Create a player.
  function createPlayer(_options) {
    player && player.dispose();
    player = new Aliplayer(_options);
    player.on('error', (e) => {
      var code = String(e.paramData.error_code);
      if (['4300', '4301', '4302', '4303', '4304'].indexOf(code) > -1) {
        fallbackTo264(_options)
      }
    });
    player.on('h265DecoderOverload', () => {
      // We recommend that you use a degraded protocol for playback after two consecutive error events are triggered because decoding may also trigger an error event.
      fallbackTo264(_options)
    })
    return player;
  }

  // Configure a degradation logic.
  function fallbackTo264(_options) {
      // Specify the playback URL of an H.264 video for the source parameter.
      _options.source = '//h264.mp4';
      // Set enableH265.to false to disable codec sniffing.
      _options.enableH265 = false;
      createPlayer(_options);
  }

  // Initialize the player.
  var options = {
    id: "player-con",
    source: "//h265.mp4",
    enableH265: true
  }
  createPlayer(options)

H.266 playback degradation

If an H.266 video fails to be played or stuttering occurs during playback, we recommend that you configure an error message to notify the user. You can also specify to automatically play the H.264 video if the H.266 video fails to be played or stuttering occurs during playback. The following section describes the common causes of playback failures or stuttering:

  • Cause 1: Your browser does not support the API operations that are required for software decoding, including WebAssembly, Canvas, and Web Worker.

  • Cause 2: Video decoding failed due to encoding errors or decoder compatibility issues.

You can listen to the events of ApsaraVideo Player for Web to obtain information about the errors that occur during the playback of H.266 videos.

Listen to the error event of the player. If an error code from 4300 to 4304 is returned, an error occurred during the playback of H.265 or H.266 videos. In this case, Cause 1 or Cause 2 described in the preceding section applies.

The following sample code provides an example on how to listen to events:

player.on('error', (e) => {
        var code = String(e.paramData.error_code);
    if (['4300', '4301', '4302', '4303', '4304'].indexOf(code) > -1) {
      // Notify the user or use a degraded protocol for playback if the API operation is not supported in your browser or video decoding failed.
    }
});          

The following sample code provides an example on how to configure a degradation logic:

  var player;

  // Create a player.
  function createPlayer(_options) {
    player && player.dispose();
    player = new Aliplayer(_options);
    player.on('error', (e) => {
      var code = String(e.paramData.error_code);
      if (['4300', '4301', '4302', '4303', '4304'].indexOf(code) > -1) {
        fallbackTo264(_options)
      }
    });
    return player;
  }

  // Configure a degradation logic.
  function fallbackTo264(_options) {
      // Specify the playback URL of an H.264 video for the source parameter.
      _options.source = '//h264.mp4';
      // Set enableH266. to false to disable codec sniffing.
      _options.enableH266 = false;
      createPlayer(_options);
  }

  // Initialize the player.
  var options = {
    id: "player-con",
    source: "//h266.mp4",
    enableH266: true
  }
  createPlayer(options)

API

For more information about the attributes, methods, and events that are supported in ApsaraVideo Player SDK for Web and corresponding descriptions and examples, see API operations. The following section describes the attributes, methods, and events that are supported for H.265 and H.266 videos:

  • Supported attributes

    source, autoplay, rePlay, preload, cover, width, height, skinLayout, waitingTimeout, vodRetry, keyShortCuts, and keyFastForwardStep

  • Supported methods

    play, pause, replay, seek, dispose, getCurrentTime, getDuration, getVolume, setVolume, loadByUrl, setPlayerSize, setSpeed, setSanpshotProperties, fullscreenService, getStatus, setRotate, getRotate, setImage, setCover, setProgressMarkers, setPreviewTime, getPreviewTime, and isPreview

  • Supported events

    ready, play, pause, canplay, playing, ended, hideBar, showBar, waiting, timeupdate, snapshoted, requestFullScreen, cancelFullScreen, error, startSeek, completeSeek, h265PlayInfo, and h266PlayInfo

    Note

    The h265PlayInfo and h266PlayInfo callbacks returns the playback method that is used for the H.265 or H.266 video. renderType indicates the playback method, simd indicates SIMD processing, and wasmThreads indicates multi-tread processing.

Error codes

The following table describes the error codes that may be returned for H.265 and H.266 playback errors. For more information about other error codes, see API operations.

Error code

Description

4300

wasm/worker/canvas/audiocontent/webgl is not supported. H.265 and H.266 videos cannot be played.

4301

An internal scheduling error occurred.

4302

Video decoding failed.

4303

Buffer overload occurred.

4304

The container format of the video is not MP4.

Enable multi-thread processing

If you use WebAssembly for software decoding, you can enable multi-thread processing to improve the decoding performance. SharedArraryBuffer is disabled for mainstream browsers due to security reasons. WebAssembly threads are dependent on SharedArraryBuffer. You can use one of the following methods to enable SharedArraryBuffer.

Example

Save the resources that need to be loaded such as images, scripts, and videos to your local project and return the following request headers when the resources are accessed:

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

Check whether self.crossOriginIsolated is set to true and whether SharedArrayBuffer is defined. If self.crossOriginIsolated is set to true and SharedArrayBuffer is defined, SharedArrayBuffer is enabled.H265

Use the player to play H.265 or H.266 videos and listen to the h265PlayInfo or h266PlayInfo event. If true is returned for event.paramData.wasmThreads, multi-thread decoding is enabled for the player.H265-1

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 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 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 is mainly 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')
  • 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 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',
    }

Customize deployment

By default, resources in ApsaraVideo VOD such as JavaScript and CSS files are stored in Alibaba Cloud CDN. To deploy these resources to your server, perform the following steps:

  1. Download the resources for ApsaraVideo Player SDK.

    You must obtain the complete resource package because ApsaraVideo Player dynamically references resource files other than the aliplayer-min.js and aliplayer-min.css files.

    Download link: apsara-media-box-imp-web-player-dist.tar.gz

  2. Decompress the package and deploy the files.

    Decompress the resource package and deploy all files in the folder to your server. Make sure that the directory levels of files are not changed.

  3. Initialize the player in a custom path.

    The following sample code provides an example on URLs of the CSS and JavaScript files for custom deployment:

    https://player.alicdn.com/assets/skins/default/aliplayer-min.css
    https://player.alicdn.com/assets/aliplayer-min.js

    Perform the following steps to initialize the player:

    1. Reference URLs of the CSS and JavaScript files in the upper part of the page.

      <head>
        <link rel="stylesheet" href="https://player.alicdn.com/assets/skins/default/aliplayer-min.css" />
        <script charset="utf-8" type="text/javascript" src="https://player.alicdn.com/assets/aliplayer-min.js"></script>
      </head>
    2. Initializes the player and specify the assetPrefix parameter.

      The assetPrefix parameter specifies the prefix of the custom path. If you play an HLS video in the player, the system dynamically references the https://player.alicdn.com/assets/hls/aliplayer-hls2-min.js file. Make sure that the path of the file is correct.

      new Aliplayer({
        assetPrefix: 'https://player.alicdn.com/assets'
        // Specify other parameters.
      })