All Products
Search
Document Center

ApsaraVideo VOD:How to play an encrypted video

Last Updated:Jun 10, 2025

ApsaraVideo VOD and ApsaraVideo Live provide multiple video encryption methods. You can use ApsaraVideo Player SDK to decrypt and play videos to prevent hotlinking, illegal downloads, and distribution of video content. This topic describes how to use ApsaraVideo Player SDK to play videos encrypted by using Alibaba Cloud proprietary cryptography, HTTP Live Streaming (HLS) encryption, and digital rights management (DRM) encryption.

Introduction to video encryption

ApsaraVideo VOD provides a comprehensive content security protection mechanism to prevent hotlinking, illegal downloads, and distribution of video content. This security mechanism includes access restrictions, URL signing, remote authentication, video encryption, and secure downloads.

For more information about security mechanisms such as access restrictions, URL signing, and remote authentication, see Overview of video security. This topic focuses on how to play videos encrypted by using three encryption methods. The following table describes the three methods that can be used to encrypt videos.

Security mechanism

Method

Features

Security Level

Deployment complexity

Video encryption

Alibaba Cloud proprietary cryptography

ApsaraVideo VOD uses a proprietary cryptography algorithm to provide a cloud-device integrated video encryption solution. This ensures the security of transmission links.

High

Relatively low. You need to only perform simple configurations and integrate ApsaraVideo Player SDK.

HTTP Live Streaming (HLS) encryption

HLS encryption uses AES-128 to encrypt video content and supports all HLS-compatible players. However, the keys are prone to theft.

High

High. You must set up a key management service and a token issuance service. You must also ensure the security of transmission links.

Commercial DRM

Native support for Apple FairPlay and Google Widevine with very high security levels, meeting the requirements of most copyright content providers.

High

High. You are charged based on the number of license calls. You need to only integrate ApsaraVideo Player SDK.

Compatibility of ApsaraVideo Player SDK with encrypted playback

Note
  1. Before you use ApsaraVideo Player SDK for Web to play encrypted videos, make sure that your browser supports the playback of encrypted videos. For example, ApsaraVideo Player SDK for Web supports the playback of videos encrypted by using Alibaba Cloud proprietary cryptography on mainstream mobile browsers. For more information, see Browser compatibility and Feature compatibility. ✔️ and ❌ indicate that the feature is supported and not supported, respectively.

  2. We recommend that you download the latest version of ApsaraVideo Player SDK to ensure feature compatibility. For more information about how to download the latest version, see SDK introduction.

  3. Note: The container format of HLS is M3U8.

Client

Playback method

Alibaba Cloud proprietary cryptography (HLS)

License-based Alibaba Cloud proprietary cryptography (HLS)

License-based Alibaba Cloud proprietary cryptography (MP4)

Alibaba Cloud proprietary cryptography (Live FLV)

HLS encryption

DRM encryption

Web Client

UrlSource-based playback

✔️

VidAuth-based playback

✔️

✔️

✔️

VidSts-based playback

✔️

✔️

UrlSource-based live streaming

✔️

LiveStsSource-based live streaming

✔️

✔️

✔️

Native (iOS/Android/Flutter)

UrlSource-based playback

✔️

✔️

Supported only in ApsaraVideo Player SDK V6.17.0 or later.

✔️

Supported only in ApsaraVideo Player SDK V6.8.0 or later.

✔️

VidAuth-based playback

✔️

✔️

✔️

VidSts-based playback

✔️

✔️

✔️

✔️

Note

Not supported in ApsaraVideo Player SDK for Flutter.

UrlSource-based live streaming

✔️

LiveStsSource-based live streaming

✔️

✔️

✔️

✔️

Note

Not supported in ApsaraVideo Player SDK for Flutter.

Encryption introduction

Alibaba Cloud proprietary cryptography

Alibaba Cloud proprietary cryptography encrypts video data. Even if the video is downloaded to a local device, the video remains encrypted. This effectively prevents malicious secondary distribution, leakage, and hotlinking. For more information, see Alibaba Cloud proprietary cryptography.

ApsaraVideo Player SDK encapsulates the decryption logic and interaction with the server. You need to only configure encryption transcoding and integrate the player to implement encrypted playback at a low cost.

Important
  • Alibaba Cloud proprietary cryptography is free of charge. However, you must transcode the video for encryption. Transcoding incurs fees. For more information about the billing standards, see Media transcoding billing.

Configure Alibaba Cloud proprietary cryptography

For more information about the detailed process and configuration of Alibaba Cloud proprietary cryptography, see How to use.

Limits

Alibaba Cloud proprietary cryptography supports the encryption of videos in the HLS (M3U8), FLV, and MP4 formats. This feature supports playback only by using ApsaraVideo Player. On the web client, only HLS format playback is supported. On the native client, playback of all formats is supported.

License-based Alibaba Cloud proprietary cryptography

License-based Alibaba Cloud proprietary cryptography ensures playback security based on Alibaba Cloud proprietary cryptography. It further improves the startup speed by directly using the encrypted video URL for playback. This feature is suitable for short videos and short dramas.

Important
  • License-based Alibaba Cloud proprietary cryptography is free of charge. However, you must transcode the video for encryption. Transcoding incurs fees. For more information about the billing standards, see Media transcoding billing.

Configure Alibaba Cloud proprietary cryptography

For more information about the detailed process and configuration of Alibaba Cloud proprietary cryptography, see How to use.

Limits

License-based Alibaba Cloud proprietary cryptography supports the encryption of videos in the HLS and MP4 formats. This feature supports playback only by using ApsaraVideo Player.

HLS encryption

HLS encryption uses AES-128 to encrypt video content. It is compatible with all HLS players and supports self-developed or open source players. It provides high flexibility but has a higher threshold and lower security. For more information, see HLS encryption.

Important

Alibaba Cloud proprietary cryptography (HLS encryption) is free of charge. However, you must transcode the video for encryption. Transcoding incurs fees. For more information about the billing standards, see Media transcoding billing.

Configure HLS encryption

For more information about the detailed process and configuration of HLS encryption, see Access procedure.

Limits

HLS encryption is compatible with all HLS players. You can choose a player based on your needs. This topic uses ApsaraVideo Player as an example to describe how to play HLS-encrypted videos. ApsaraVideo Player supports token passing. CDN dynamically adjusts the decryption URI in the M3U8 file and attaches the user token for business verification.

DRM encryption

ApsaraVideo VOD supports industry-standard DRM encryption (Digital Rights Management) for one-stop management of copyrighted videos. It is compatible with WideVine and FairPlay solutions. For more information, see DRM encryption.

Important

DRM encryption is implemented during video transcoding. You are charged only for transcoding when you transcode a video. You are charged for DRM encryption every time a device requests a license to play a DRM-encrypted video. For more information about billing, see DRM billing.

Configure DRM encryption

DRM encryption can be enabled only in the ApsaraVideo VOD console. For more information about the detailed operations, see Configure DRM encryption.

Limits

DRM-encrypted videos can be played only by using ApsaraVideo Player.

Web client

Note
  • Before you use ApsaraVideo Player SDK for Web, make sure that your browser supports the playback of videos encrypted by using Alibaba Cloud proprietary cryptography. The following items describe the compatibility of ApsaraVideo Player:

    • H5 mode supports desktop and mobile browser environments. For more information about the supported browsers, see Feature compatibility.

  • For security reasons, you cannot use Alibaba Cloud proprietary cryptography to encrypt videos that are already encrypted.

Procedure

You can embed ApsaraVideo Player SDK for Web into a web page to play videos encrypted by using Alibaba Cloud proprietary cryptography.

  1. For more information about how to import ApsaraVideo Player SDK for Web into your page, see Quick Intergation.

  2. Select an encryption method and play the video.

    You can embed ApsaraVideo Player SDK for Web into a web page to play videos encrypted by using Alibaba Cloud proprietary cryptography. The following sample code provides examples:

Alibaba Cloud proprietary cryptography

Use VidAuth to play an on-demand video encrypted by using Alibaba Cloud proprietary cryptography (HLS format)

When you use VidAuth to play a video encrypted by using Alibaba Cloud proprietary cryptography, you must set the encryptType parameter to 1 to enable Alibaba Cloud proprietary cryptography, which is different from playing a regular video.

<!DOCTYPE html>
  <html>
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
       <title>Demo for playing an on-demand video that is encrypted by using Alibaba Cloud proprietary cryptography</title>
       <link rel="stylesheet" href="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/skins/default/aliplayer-min.css" />
       <script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/aliplayer-min.js"></script>
      </head>
      <body>
          <div class="prism-player" id="J_prismPlayer"></div>
          <script>
              var player = new Aliplayer({
                id: 'J_prismPlayer',
                width: '100%',
                vid : '<your video ID>',// Required. You can log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video to obtain the video ID. Example: 1e067a2831b641db90d570b6480f****.
                playauth : '<your PlayAuth>',// Required. You can call the GetVideoPlayAuth operation to obtain the playback credential.
                encryptType: 1, // Required. Set this parameter to 1 if you use Alibaba Cloud proprietary cryptography to encrypt the video. Otherwise, leave this parameter empty.
                playConfig:{EncryptType:'AliyunVoDEncryption'}, // You must specify this parameter if the output M3U8 streams include streams that are encrypted by using an algorithm other than Alibaba Cloud proprietary cryptography.
                // authTimeout: 7200, // The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 7200 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.
              },function(player){
                console.log('The player is created.')
             });
          </script>
      </body>
  </html>

Use LiveStsSource to play a live stream encrypted by using Alibaba Cloud proprietary cryptography (HLS format)

When you use LiveStsSource to play a live stream encrypted by using Alibaba Cloud proprietary cryptography, you must specify the URL and temporary Security Token Service (STS) credentials. For more information about how to generate temporary STS credentials, see Obtain an STS token. The following sample code provides an example:

<!DOCTYPE html>
 <html>
     <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
      <title>Demo for playing a live stream that is encrypted by using Alibaba Cloud proprietary cryptography</title>
      <link rel="stylesheet" href="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/skins/default/aliplayer-min.css" />
      <script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/aliplayer-min.js"></script>
     </head>
     <body>
         <div class="prism-player" id="J_prismPlayer"></div>
         <script>
             var player = new Aliplayer({
               id: 'J_prismPlayer',
               width: '100%',
               isLive: true, // Set this parameter to true.
               source: '<your live stream url>',// Required. The streaming URL is the URL of an HLS stream that is encrypted by using Alibaba Cloud proprietary cryptography.
               accessKeyId: '<your AccessKey ID>',// Required. The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS.
               accessKeySecret: '<your AccessKey secret>',// Required. The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS.
               securityToken: '<your STS token>',// Required. The STS token. To generate an STS token, call the AssumeRole operation in STS.
               domain: '<your Domain>',// Required. The domain name used for stream pulling.
               app:'<your App Name>',// Required. The name of the application.
               stream:'<your Stream Name>',// Required. The name of the live stream.
               regionId: '<region of your video>',// Required. The region in which your service is deployed. Examples: cn-shanghai, eu-central-1, and ap-southeast-1.
             },function(player){
               console.log('The player is created.')
            });
         </script>
     </body>
 </html>
Note
  • If you want to play on-demand videos encrypted by using Alibaba Cloud proprietary cryptography on iOS 17.1 or earlier, perform the following operations to deploy an additional player plug-in:

    Principle: iOS 17.1 or earlier requires an additional plug-in that uses Service Worker technology. Due to browser security policy restrictions, websites can access only service worker scripts that are from the same origin as the current website. Therefore, you must deploy the player plug-in script to the same domain name as your website.

    1. Download the script: https://g.alicdn.com/apsara-media-box/imp-web-player/<version number>/aliplayer-worker-min.js

    2. Deploy the script: Assume that the website where you play videos encrypted by using Alibaba Cloud proprietary cryptography is https://www.aliyun.com/a/b.html. You must deploy the script to https://www.aliyun.com/a/aliplayer-worker-min.js, which is at the same directory level as the current website.

    3. Pass this address when you initialize the player:

      new Aliplayer({
        // ... Configure other parameters
        swScriptURL: 'https://www.aliyun.com/a/aliplayer-worker-min.js' // Specify a complete URL of the plug-in script and make sure the URL is accessible.
      })

    Note: Make sure that the player and plug-in are of the same version.

  • If your web page runs in a custom packaged iOS application (such as uni-app), you must configure your website domain name in WKAppBoundDomains in the Info.plist file of the application to enable the Service Worker feature in WKWebview. For more information, see App-Bound Domains.

HLS encryption

Use VidAuth to play an HLS-encrypted on-demand video

When you use VidAuth to play an HLS-encrypted video, if the video has other non-HLS-encrypted streams or regular transcoded streams, you can set the video encryption type to HLSEncryption to filter HLS-encrypted streams for playback. The following sample code provides an example:

let player = new Aliplayer({
   id:'J_prismPlayer',
   vid:'<your video ID>', // Required. The ID of the audio or video. Example: 1e067a2831b641db90d570b6480f****.
   playauth:'<your PlayAuth>', // Required. The playback credential.
   playConfig: { // Optional.
     MtsHlsUriToken: '', // Optional. You can pass this parameter if you want to verify MtsHlsUriToken.
     EncryptType: 'HLSEncryption', // Optional. If you set the encryption type to HLSEncryption, only videos that are encrypted by using HLS encryption are returned.
   },
 });

Use VidSts to play an HLS-encrypted on-demand video

When you use VidSts to play an HLS-encrypted video, if the video has other non-HLS-encrypted streams or regular transcoded streams, you can set the video encryption type to HLSEncryption to filter HLS-encrypted streams for playback. The following sample code provides an example:

let player = new Aliplayer({
   id: 'J_prismPlayer',
   vid : '<your video ID>', // Required. After you upload an audio or video file, you can log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video to view the ID of the audio or video file. Alternatively, you can call the SearchMedia operation provided by the ApsaraVideo VOD SDK to obtain the ID. Example: 1e067a2831b641db90d570b6480f****.
   accessKeyId: '<your AccessKey ID>', // Required. The AccessKey ID is returned when the temporary STS token is generated.
   securityToken: '<your STS token>', // Required. The STS token. To obtain an STS token, call the AssumeRole operation.
   accessKeySecret: '<your AccessKey Secret>', // Required. The AccessKey secret is returned when the temporary STS token is generated.
   region: '<region of your video>', // Required. The ID of the region in which the media asset resides, such as cn-shanghai, eu-central-1, and ap-southeast-1.
   playConfig: { // Optional.
     MtsHlsUriToken: '', // Optional. You can pass this parameter if you want to verify MtsHlsUriToken.
     EncryptType: 'HLSEncryption', // Optional. If you set the encryption type to HLSEncryption, only videos that are encrypted by using HLS encryption are returned.
   },
 };

Use UrlSource to play an HLS-encrypted video

When you use UrlSource to play an HLS-encrypted live stream or on-demand video, the configuration is the same as that for playing a regular video. No additional parameters are required.

  let player = new Aliplayer({
    id:'J_prismPlayer',
    source:'<your play URL>', // The playback URL of the live stream or on-demand video.
    isLive: true, // Specifies whether to play live streams.
  });

DRM encryption

Use VidSts to play a DRM-encrypted on-demand video

When you use VidSts to play a DRM-encrypted video, you must set the isDrm parameter to true to enable DRM encryption, which is different from playing a regular video.

<!DOCTYPE html>
 <html>
     <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
      <title>Demo for playing a DRM-encrypted on-demand video</title>
      <link rel="stylesheet" href="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/skins/default/aliplayer-min.css" />
      <script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/aliplayer-min.js"></script>
     </head>
     <body>
         <div class="prism-player" id="J_prismPlayer"></div>
         <script>
             var player = new Aliplayer({
               id: 'J_prismPlayer',
               width: '100%',
               isDrm: true,
               vid: '<your video ID>',// Required. You can log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video to obtain the video ID. Example: 1e067a2831b641db90d570b6480f****.
               accessKeyId: '<your AccessKey ID>',// Required. The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS.
               securityToken: '<your STS token>',// Required. The STS token. To generate an STS token, call the AssumeRole operation in STS.
               accessKeySecret: '<your AccessKey Secret>',// Required. The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS.
               region: '<region of your video>', // Required. The ID of the region in which the media asset is stored, such as cn-shanghai, eu-central-1, and ap-southeast-1.
               certId: '<your certificate ID>', // This parameter is required for playback on Apple devices. This parameter is used to request an Apple certificate. You can obtain the certificate ID from the ApsaraVideo VOD or ApsaraVideo Live console.
               // authTimeout: 7200, // The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 7200 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.
             },function(player){
               console.log('The player is created.')
            });
         </script>
     </body>
 </html>

Use LiveStsSource to play a DRM-encrypted live stream

When you use LiveStsSource to play a DRM-encrypted live stream, you must specify the URL and temporary STS credentials. For more information about how to generate temporary STS credentials, see Obtain an STS token. The following sample code provides an example:

<!DOCTYPE html>
 <html>
     <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
      <title>Demo for playing a DRM-encrypted live stream</title>
      <link rel="stylesheet" href="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/skins/default/aliplayer-min.css" />
      <script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/aliplayer-min.js"></script>
     </head>
     <body>
         <div class="prism-player" id="J_prismPlayer"></div>
         <script>
             var player = new Aliplayer({
               id: 'J_prismPlayer',
               width: '100%',
               isLive: true, // Set this parameter to true.
               isDrm: true,
               source: '<your live stream url>',// Required. The streaming URL of the live stream that is encrypted by DRM.
               accessKeyId: '<your AccessKey ID>',// Required. The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS.
               securityToken: '<your STS token>',// Required. The STS token. To generate an STS token, call the AssumeRole operation in STS.
               accessKeySecret: '<your AccessKey Secret>',// Required. The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS.
               region: '<region of your video>', // Required. The ID of the region in which the media asset is stored, such as cn-shanghai, eu-central-1, and ap-southeast-1.
               certId: '<your certificate ID>', // This parameter is required for playback on Apple devices. This parameter is used to request an Apple certificate. You can obtain the certificate ID from the ApsaraVideo VOD or ApsaraVideo Live console.
             },function(player){
               console.log('The player is created.')
            });
         </script>
     </body>
 </html>

Android client

Procedure

You can integrate ApsaraVideo Player SDK for Android into your application. The following content describes how to use ApsaraVideo Player SDK for Android for playback and provides sample code:

  1. Integrate ApsaraVideo Player SDK for Android.

    For more information about how to integrate ApsaraVideo Player SDK for Android, see Quick Intergation.

  2. Create a player for playback.

    For more information about how to create a player, see Create a player. For Step 3: Configure a playback source, select one of the following methods based on your business requirements.

Alibaba Cloud proprietary cryptography

Precautions

You can play HLS videos that are encrypted by using Alibaba Cloud proprietary cryptography only by URL-based playback after you create a transcoding template and transcode the videos. Before you transcode the videos, you must bind a license to the same account (for more information, see Manage licenses). Then, use the EncryptType parameter to create a transcoding template group. The following sample code provides an example:

Important

After you create a template, you cannot modify or save the template in the ApsaraVideo VOD console. Otherwise, the encryption method is overwritten.

[{
        "TranscodeTemplateId": "",
	"TemplateName": "740PH264HLSLocalEncryption",
	"Type": "Normal",
	"Container": {
		"Format": "m3u8"
	},
	"TransConfig": {
		"IsCheckReso": false,
		"IsCheckResoFail": false,
		"IsCheckVideoBitrate": false,
		"IsCheckVideoBitrateFail": false,
		"IsCheckAudioBitrate": false,
		"IsCheckAudioBitrateFail": false
	},
	"Definition": "HD",
	"MuxConfig": {
		"Segment": {
			"Duration": 5
		}
	},
	"EncryptSetting": {
		"EncryptType": "AliyunVoDLicenseEncryption"
	},
	"Video": {
		"Height": 720,
		"Bitrate": 400,
		"Codec": "H.264",
		"Fps": 25,
		"Gop": 250,
		"Profile": "high"
	},
	"Audio": {
		"Bitrate": 64,
		"Codec": "AAC",
		"Channels": 2,
		"Samplerate": "44100"
	}
}]

Use VidAuth to play an on-demand video encrypted by using Alibaba Cloud proprietary cryptography (HLS and MP4 formats)

When playing HLS or MP4 videos encrypted by using Alibaba Cloud proprietary cryptography through VidAuth, if the current video also has other non-proprietary encrypted streams or regular transcoded streams, you can set the encryption type to AliyunVoDEncryption to filter and play only the proprietary encrypted streams.

VidAuth vidAuth = new VidAuth();
VidPlayerConfigGen vidPlayerConfigGen = new VidPlayerConfigGen();
vidPlayerConfigGen.setEncryptType(VidPlayerConfigGen.EncryptType.AliyunVoDEncryption);// Optional. If you set the encryption method to AliyunVoDEncryption, only videos that are encrypted by using Alibaba Cloud proprietary cryptography are returned.
vidAuth.setPlayConfig(vidPlayerConfigGen);
vidAuth.setVid("Video ID");// Required. The video ID.
vidAuth.setPlayAuth("<yourPlayAuth>");// Required. The playback credential. To obtain the playback credential, call the GetVideoPlayAuth operation in ApsaraVideo VOD.
vidAuth.setRegion("Access region");// This parameter is deprecated in ApsaraVideo Player SDK V5.5.5.0 or later. If you use ApsaraVideo Player SDK V5.5.5.0 or later, the player automatically parses the region information. If you use ApsaraVideo Player SDK V5.5.5.0 or earlier, this parameter is required. Specify the ID of the region in which ApsaraVideo VOD is activated for this parameter. Default value: cn-shanghai.
// vidAuth.setAuthTimeout(3600); // Optional. The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 3600 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.
aliPlayer.setDataSource(vidAuth);

Use VidSts to play an on-demand video encrypted by using Alibaba Cloud proprietary cryptography (HLS and MP4 formats)

When playing HLS or MP4 videos encrypted by using Alibaba Cloud proprietary cryptography through VidSts, if the current video also has other non-proprietary encrypted streams or regular transcoded streams, you can set the encryption type to AliyunVoDEncryption to filter and play only the proprietary encrypted streams.

VidSts vidSts = new VidSts();
VidPlayerConfigGen vidPlayerConfigGen = new VidPlayerConfigGen();
vidPlayerConfigGen.setEncryptType(VidPlayerConfigGen.EncryptType.AliyunVoDEncryption);// Optional. If you set the encryption method to AliyunVoDEncryption, only videos that are encrypted by using Alibaba Cloud proprietary cryptography are returned.
vidSts.setPlayConfig(vidPlayerConfigGen);
vidSts.setVid("Video ID"); // Required. The video ID.
vidSts.setAccessKeyId("<yourAccessKeyId>"); // Required. The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS.
vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required. The AccessKey secret that is issued together with the STS token. To generate the AccessKey secret, call the AssumeRole operation in STS.
vidSts.setSecurityToken("<yourSecurityToken>");// Required. The security token. To generate an STS token, call the AssumeRole operation in STS.
vidSts.setRegion("Access region"); // Required. The ID of the region in which ApsaraVideo VOD is activated. Default value: cn-shanghai.
// vidSts.setAuthTimeout(3600); // Optional. The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 3600 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.
aliPlayer.setDataSource(vidSts);

Use LiveStsSource to play a live stream encrypted by using Alibaba Cloud proprietary cryptography (HLS and FLV formats)

When playing HLS or FLV videos encrypted by using Alibaba Cloud proprietary cryptography through LiveStsSource, you need to provide the URL and STS token, and set the encryption type to AliEncryption. The following sample code provides examples on how to run perseusrun commands:

  1. You can create a DataSource.

    You must set AVPLiveStsSource as the playback source.

    // Create LiveSts, EncryptionType needs to be set to AliEncryption
    LiveSts liveSts = new LiveSts();
    liveSts.setUrl("<your live stream url>");// Required. The URL of the HLS live stream that is encrypted by using Alibaba Cloud proprietary cryptography.
    liveSts.setAccessKeyId("<your AccessKey ID>");// Required. The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS.
    liveSts.setAccessKeySecret("<your AccessKey Secret>");// Required. The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS.
    liveSts.setSecurityToken("<your STS token>");// Required. The STS token. To generate an STS token, call the AssumeRole operation in STS.
    liveSts.setDomain("<your Domain>");// Required. The streaming domain.
    liveSts.setApp("<your App Name>");// Required. The name of the application to which the live stream belongs.
    liveSts.setStream("<your Stream Name>");// Required. The name of the live stream.
    liveSts.setEncryptionType(LiveSts.LiveEncryptionType.AliEncryption);// Required. Set the encryption method to AliEncryption.
    liveSts.setRegion("<region of your video>");// Required. The region in which ApsaraVideo VOD is activated, such as cn-shanghai.
    // Configure the playback source
    aliPlayer.setDataSource(liveSts);
    // Prepare for playback
    aliPlayer.prepare();
  2. Check whether the STS token is valid.

    The encryption key may change during the playback of encrypted live streams. The player sends a request to obtain the latest key from STS. You must check whether the STS token is valid. If the token is invalid, the playback of encrypted live streams is affected.

    mAliyunVodPlayer.setOnVerifyTimeExpireCallback(new AliPlayer.OnVerifyTimeExpireCallback() {
    		@Override
        public AliPlayer.Status onVerifySts(StsInfo info) {
            if(The token can be used){
                return IPlayer.StsStatus.Valid;
            }
    
            if(A valid STS token can be obtained){
                Obtain STS();// This operation can be synchronously or asynchronously performed.
                return IPlayer.StsStatus.Pending;
            }
            // If the token is invalid and the latest STS token cannot be obtained, we recommend that you stop the playback to prevent screen flickers.
            mAliyunVodPlayer.stop();
            return IPlayer.StsStatus.Invalid;
        }
    
        @Override
        public AliPlayer.Status onVerifyAuth(VidAuth auth) {
            return AliPlayer.Status.Valid;
        }
    });
    Note

    After you obtain the STS token, you need to call the updateLiveStsInfo method to update the STS token. If the token failed to be obtained, we recommend that you stop the playback. If you do not update the STS token, the player uses the expired STS token to obtain the encryption key. If the STS token becomes invalid, the screen may flicker or the playback may fail.

    mAliyunVodPlayer.updateStsInfo(stsInfo);

Alibaba Cloud video encryption (License private encryption)

Notes

HLS format videos encrypted with Alibaba Cloud video encryption (License private encryption) can be played via URL after transcoding through a transcoding template. Before transcoding, you need to complete License attachment under the same account (for details, see Manage License), and then use the EncryptType parameter to create a transcoding template group. The following is an example:

Important

After you create a template, you cannot modify or save the template in the console. Otherwise, the encryption method is overwritten.

[{
        "TranscodeTemplateId": "",
	"TemplateName": "740PH264HLSLocalEncryption",
	"Type": "Normal",
	"Container": {
		"Format": "m3u8"
	},
	"TransConfig": {
		"IsCheckReso": false,
		"IsCheckResoFail": false,
		"IsCheckVideoBitrate": false,
		"IsCheckVideoBitrateFail": false,
		"IsCheckAudioBitrate": false,
		"IsCheckAudioBitrateFail": false
	},
	"Definition": "HD",
	"MuxConfig": {
		"Segment": {
			"Duration": 5
		}
	},
	"EncryptSetting": {
		"EncryptType": "AliyunVoDLicenseEncryption"
	},
	"Video": {
		"Height": 720,
		"Bitrate": 400,
		"Codec": "H.264",
		"Fps": 25,
		"Gop": 250,
		"Profile": "high"
	},
	"Audio": {
		"Bitrate": 64,
		"Codec": "AAC",
		"Channels": 2,
		"Samplerate": "44100"
	}
}]

License private encrypted playback-ApsaraVideo VOD UrlSource playback (HLS format + MP4 format)

Note

Only Android Player SDK version 6.8.0 and later supports playing MP4 format License private encrypted videos through UrlSource-based playback. Version 6.17.0 and later supports HLS format (single bitrate, multiple bitrate) License private encrypted videos.

When playing HLS format or MP4 format videos encrypted with License private encryption through UrlSource-based playback, you can call the GetPlayInfo - Obtain audio and video playback URLs operation to obtain the video playback URL. You need to manually append etavirp_nuyila=1 to the end of the URL according to the protocol (position is not limited) before passing it to the player (only MP4 requires this parameter, HLS can directly use the original video URL). The player SDK configuration is the same as that for playing regular videos, with no additional parameters required.

Playback URL example 1: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1

Playback URL example 2: https://example.aliyundoc.com/test.mp4?auth_key=xxxxx&etavirp_nuyila=1

// Playback URL
String playURL = "https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1";

// Player
UrlSource urlSource = new UrlSource();
urlSource.setUri(playURL);// Required. The playback URL of the video. You can call the GetPlayInfo operation to obtain the URL.
aliPlayer.setDataSource(urlSource);
aliPlayer.prepare();

// The short video player
AliListPlayer aliyunListPlayer = AliPlayerFactory.createAliListPlayer(getApplicationContext());
// Add an UrlSource playback source
aliyunListPlayer.addUrl(playURL,uid);
aliyunListPlayer.moveTo(uid);

// Preload the video
MediaLoader mediaLoader = MediaLoader.getInstance();
mediaLoader.load(playURL,"duration");

HLS encryption

Use VidAuth to play an HLS-encrypted on-demand video

When you use VidAuth to play an HLS-encrypted video, if the video has other non-HLS-encrypted streams or regular transcoded streams, you can set the video encryption type to HLSEncryption to filter HLS-encrypted streams for playback.

VidAuth vidAuth = new VidAuth();
VidPlayerConfigGen vidPlayerConfigGen = new VidPlayerConfigGen();
vidPlayerConfigGen.setEncryptType(VidPlayerConfigGen.EncryptType.HLSEncryption);// Optional. If you set the encryption method to HLSEncryption, only videos that are encrypted by using HLS encryption are returned.
vidAuth.setPlayConfig(vidPlayerConfigGen);
vidAuth.setVid("Vid");// Required. The video ID.
vidAuth.setPlayAuth("yourPlayAuth"); // Required. The playback credential. To obtain the playback credential, call the GetVideoPlayAuth operation in ApsaraVideo VOD.
vidAuth.setRegion("Access region"); // This parameter is deprecated in ApsaraVideo Player SDK V5.5.5.0 or later. If you use ApsaraVideo Player SDK V5.5.5.0 or later, the player automatically parses the region information. If you use ApsaraVideo Player SDK V5.5.5.0 or earlier, this parameter is required. Specify the ID of the region in which ApsaraVideo VOD is activated for this parameter. Default value: cn-shanghai.
// vidAuth.setAuthTimeout(3600); // Optional. The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 3600 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.
aliPlayer.setDataSource(vidAuth);

Use VidSts to play an HLS-encrypted on-demand video

When you use VidSts to play an HLS-encrypted video, if the video has other non-HLS-encrypted streams or regular transcoded streams, you can set the video encryption type to HLSEncryption to filter HLS-encrypted streams for playback.

VidSts vidSts = new VidSts();
VidPlayerConfigGen vidPlayerConfigGen = new VidPlayerConfigGen();
vidPlayerConfigGen.setEncryptType(VidPlayerConfigGen.EncryptType.HLSEncryption);// Optional. If you set the encryption method to HLSEncryption, only videos that are encrypted by using HLS encryption are returned.
vidSts.setPlayConfig(vidPlayerConfigGen);
vidSts.setVid("Vid");// Required. The video ID.
vidSts.setAccessKeyId("your AccessKey ID"); // Required. The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS.
vidSts.setAccessKeySecret("your AccessKey Secret"); // Required. The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS.
vidSts.setSecurityToken("your SecurityToken"); // Required. The STS token. To generate an STS token, call the AssumeRole operation in STS.
vidSts.setRegion("Access region"); // This parameter is deprecated in ApsaraVideo Player SDK V5.5.5.0 or later. If you use ApsaraVideo Player SDK V5.5.5.0 or later, the player automatically parses the region information. If you use ApsaraVideo Player SDK V5.5.5.0 or earlier, this parameter is required. Specify the ID of the region in which ApsaraVideo VOD is activated for this parameter. Default value: cn-shanghai.
// vidSts.setAuthTimeout(3600); // Optional. The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 3600 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.
aliPlayer.setDataSource(vidSts);

Use UrlSource to play an HLS-encrypted video

When you use UrlSource to play an HLS-encrypted live stream or on-demand video, the configuration is the same as that for playing a regular video. No additional parameters are required.

UrlSource urlSource = new UrlSource();
urlSource.setUri("your URL"); // Required. The URL of the video.
urlSource.setTitle("title"); // Optional. The title of the video.
urlSource.setCacheEnable(true); // Optional. Specifies whether to enable caching.
aliPlayer.setDataSource(urlSource);

DRM encryption

Note

If you use ApsaraVideo Player for Android, we recommend that you use SurfaceView to play videos with high security levels.

Use VidSts to play a DRM-encrypted on-demand video

When you play a DRM-encrypted video by using VidSts, the configuration is the same as playing a regular video. No additional parameters are required.

VidSts vidSts = new VidSts();
        vidSts.setVid("Video ID");// Required. The video ID.
        vidSts.setAccessKeyId("<yourAccessKeyId>");// Required. The AccessKey ID that is issued together with the STS token. To generate the AccessKey ID, call the AssumeRole operation in STS.
        vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required. The AccessKey secret that is issued together with the STS token. To generate the AccessKey secret, call the AssumeRole operation in STS.
        vidSts.setSecurityToken("<yourSecurityToken>");// Required. The security token. To generate an STS token, call the AssumeRole operation in STS.
        vidSts.setRegion("Access region");// Required. The ID of the region in which ApsaraVideo VOD is activated. Default value: cn-shanghai.
        // vidSts.setAuthTimeout(3600); // Optional. The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 3600 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.
        aliPlayer.setDataSource(vidSts);

Use LiveStsSource to play a DRM-encrypted live stream

When you play a DRM-encrypted video by using LiveStsSource, you need to specify the URL and STS credentials, and set the encryption type to WideVine_FairPlay. The following sample code provides examples on how to run perseusrun commands:

  1. You can create a DataSource.

    You must set AVPLiveStsSource as the playback source.

    // Create LiveSts and set EncryptionType to WideVine_FairPlay
    LiveSts liveSts = new LiveSts();
    liveSts.setUrl("<your live stream url>");// Required. The HLS URL of the live stream that is encrypted by DRM.
    liveSts.setAccessKeyId("<your AccessKey ID>");// Required. The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS.
    liveSts.setAccessKeySecret("<your AccessKey Secret>");// Required. The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS.
    liveSts.setSecurityToken("<your STS token>");// Required. The STS token. To generate an STS token, call the AssumeRole operation in STS.
    liveSts.setDomain("<your Domain>");// Required. The streaming domain.
    liveSts.setApp("<your App Name>");// Required. The name of the application to which the live stream belongs.
    liveSts.setStream("<your Stream Name>");// Required. The name of the live stream.
    liveSts.setEncryptionType(LiveSts.LiveEncryptionType.WideVine_FairPlay);// Required. Set the encryption method to WideVine_FairPlay.
    liveSts.setRegion("<region of your video>");// Required. The region in which ApsaraVideo VOD is activated, such as cn-shanghai.
    // Configure the playback source
    aliPlayer.setDataSource(liveSts);
    // Prepare for playback
    aliPlayer.prepare();
  2. Check whether the STS token is valid.

    The encryption key may change during the playback of encrypted live streams. When the key is changed, the player sends a request to obtain the latest key from STS. You must check whether the STS token is valid. If the token is invalid, the playback of encrypted live streams is affected.

    mAliyunVodPlayer.setOnVerifyTimeExpireCallback(new AliPlayer.OnVerifyTimeExpireCallback() {
    		@Override
        public AliPlayer.Status onVerifySts(StsInfo info) {
            if (The token can be used) {
                return IPlayer.StsStatus.Valid;
            }
    
            if(A valid STS token can be obtained){
                Obtain STS();// This operation can be synchronously or asynchronously performed.
                return IPlayer.StsStatus.Pending;
            }
            // If the token is invalid and the latest STS token cannot be obtained, we recommend that you stop the playback to prevent screen flickers.
            mAliyunVodPlayer.stop();
            return IPlayer.StsStatus.Invalid;
        }
    
        @Override
        public AliPlayer.Status onVerifyAuth(VidAuth auth) {
            return AliPlayer.Status.Valid;
        }
    });
    Note

    After you obtain the STS token, you must call the updateLiveStsInfo method to update the STS token. If the token failed to be obtained, we recommend that you stop the playback. If you do not update the STS token, the player uses the expired STS token to obtain the encryption key. If the STS token becomes invalid, the screen may flicker or the playback may fail.

    mAliyunVodPlayer.updateStsInfo(stsInfo);

IOS client

Procedure

You can integrate ApsaraVideo Player SDK for iOS into your application. The following content describes how to use ApsaraVideo Player SDK for iOS for playback and provides sample code:

  1. Integrate ApsaraVideo Player SDK for iOS.

    For information about how to integrate the iOS player SDK, see Quick integration.

  2. Create a player for playback.

    For the procedure to create a player, see Create a player. For Step 3. Create a DataSource, you can choose one of the following methods based on your actual requirements.

Alibaba Cloud video encryption (proprietary encryption)

Proprietary encrypted playback - ApsaraVideo VOD VidAuth (HLS format + MP4 format)

When playing HLS or MP4 format videos that have been encrypted using proprietary encryption through VidAuth, if the current video has other non-proprietary encrypted streams or regular transcoded streams, you can filter and play only the proprietary encrypted streams by setting the video encryption type to AliyunVodEncryption.

AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init];
authSource.vid = @"Vid"; // Required. The video ID.
authSource.playAuth = @"<yourPlayAuth>"; // Required. The playback credential. To obtain a playback credential, call the GetVideoPlayAuth operation in ApsaraVideo VOD.
authSource.region = @"Access region"; // This parameter is deprecated in Player SDK V5.5.5.0 or later. If you use Player SDK V5.5.5.0 or later, the player automatically parses the region information. If you use Player SDK V5.5.5.0 or earlier, this parameter is required. Specify the ID of the region in which ApsaraVideo VOD is activated for this parameter. Default value: cn-shanghai.
// authSource.authTimeout = 3600; // Optional. The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 3600 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.

// Build the config parameter based on VidPlayerConfigGenerator
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"AliyunVodEncryption"]; // Optional. If you set the encryption method to AliyunVodEncryption, only videos that are encrypted by using Alibaba Cloud proprietary cryptography are returned.
authSource.playConfig = [config generatePlayerConfig]; 
[self.player setAuthSource:authSource];

Proprietary encrypted playback - ApsaraVideo VOD VidSts (HLS format + MP4 format)

When playing HLS or MP4 format videos that have been encrypted using proprietary encryption through VidSts, if the current video has other non-proprietary encrypted streams or regular transcoded streams, you can filter and play only the proprietary encrypted streams by setting the video encryption type to AliyunVodEncryption.

AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
source.region = @"Access region"; // Required. The region in which ApsaraVideo VOD is activated. Default value: cn-shanghai.
source.vid = @"Vid"; // Required. The video ID.
source.securityToken = @"<yourSecurityToken>"; // Required. The STS token. To generate an STS token, call the AssumeRole operation in STS.
source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS.
source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS.
// source.authTimeout = 3600; // Optional. The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 3600 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.

// Build the config parameter based on VidPlayerConfigGenerator
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"AliyunVodEncryption"]; // Optional. If you set the encryption method to AliyunVodEncryption, only videos that are encrypted by using Alibaba Cloud proprietary cryptography are returned.
source.playConfig = [config generatePlayerConfig]; 

// Configure the playback source
[self.player setStsSource:source];

Proprietary encrypted playback - ApsaraVideo Live LiveStsSource (HLS format + FLV format)

When playing HLS or FLV format videos that have been encrypted using proprietary encryption through LiveStsSource, you need to provide the URL and STS credentials, and set the video encryption type to ENCRYPTION_TYPE_ALIVODENCRYPTION. The following sample code provides examples:

  1. Create a DataSource.

    You must set AVPLiveStsSource as the playback source.

    // Create LiveSts, encryptionType must be set to ENCRYPTION_TYPE_ALIVODENCRYPTION
    AVPLiveStsSource *liveStsSource = [[AVPLiveStsSource alloc] initWithUrl:@"Streaming URL" 
                                                                accessKeyId:@"Temporary AccessKey ID" 
                                                                accessKeySecret:@"Temporary AccessKey secret" 
                                                                securityToken:@"Security token" 
                                                                region:@"Region name" 
                                                                domain:@"Streaming domain" 
                                                                app:@"Application name" 
                                                                stream:@"Stream name" 
                                                                encryptionType:ENCRYPTION_TYPE_ALIVODENCRYPTION];// Required. Set the encryption method to ENCRYPTION_TYPE_ALIVODENCRYPTION. 
     // Configure the playback source
     [self.aliPlayer setLiveStsSource:liveStsSource];
     ......
     // Prepare for playback
     [self.aliPlayer prepare];
  2. Check whether the STS token is valid.

    The encryption key may change during the playback of encrypted live streams. When the key is changed, the player sends a request to obtain the latest key from STS. You must check whether the STS token is valid. If the token is invalid, the playback of encrypted live streams is affected.

     __weak typeof(self) weakSelf = self;
    [self.aliPlayer setVerifyStsCallback:^AVPStsStatus(AVPStsInfo info) {
        if (The token can be used) {
            return Valid;
        }
        if(A valid STS token can be obtained){
            Obtain STS();// This operation can be synchronously or asynchronously performed.
            return Pending;
        }
        [weakSelf.aliPlayer stop];
        return Invalid;
    }];
    Note

    After the STS token is successfully obtained, you need to call the updateLiveStsInfo method to update the STS token. If the token failed to be obtained, we recommend that you stop the playback. If you do not update the STS token, the player uses the expired STS token to obtain the encryption key. If the STS token becomes invalid, the screen may flicker or the playback may fail.

    [self.aliPlayer updateLiveStsInfo:self.liveStsSource.accessKeyId accKey:self.liveStsSource.accessKeySecret token:self.liveStsSource.securityToken region:self.liveStsSource.region];

Alibaba Cloud Video Encryption (License Private Encryption)

License private encrypted playback-ApsaraVideo VOD UrlSource playback (HLS format + MP4 format)

Note

Only iOS player SDK version 6.8.0 and later supports playback of MP4 format License private encrypted videos through the UrlSource-based playback method. Version 6.17.0 and later supports HLS format (single bitrate, multiple bitrate) License private encrypted videos.

When playing HLS format or MP4 format videos encrypted with License private encryption through the UrlSource-based playback method, you can call the GetPlayInfo - Obtain audio and video playback URLs operation to obtain the video playback URL. You need to manually append etavirp_nuyila=1 (position doesn't matter) to the end of the obtained video URL before passing it to the player (this parameter is required only for MP4, HLS can directly use the original video URL). The player SDK configuration is the same as that for playing regular videos, with no additional parameters required.

Playback URL example 1: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1

Playback URL example 2: https://example.aliyundoc.com/test.mp4?auth_key=xxxxx&etavirp_nuyila=1

//Playback URL
NSString *playURL = @"https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1";

//Player
AliPlayer *player = [[AliPlayer alloc] init];
AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:playURL]; // Required. The playback URL. You can call the GetPlayInfo operation to obtain the playback URL. The URL is required for MP4 videos only. Add etavirp_nuyila=1 to the end of the playback URL before you pass the URL to the player for playback. Sample URL: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1
[player setUrlSource:urlSource];
[player prepare];

// The video list player
AliListPlayer *listPlayer = [[AliListPlayer alloc] init];
[listPlayer addUrlSource:playURL uid:UUIDString];
[listPlayer moveTo:@"uid"];

// Preload the video
AliMedialoader *mediaLoader = [AliMediaLoader shareInstance];
[mediaLoader load:playURL duration:1000];

HTTP Live Streaming (HLS) encryption

Use VidAuth to play an HLS-encrypted on-demand video

When playing a video encrypted with HLS encryption using the VidAuth method, if the current video has other non-HLS encrypted streams or regular transcoded streams, you can filter and play only the HLS-encrypted streams by setting the video encryption type to HLSEncryption. The following sample code provides an example:

AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init];
authSource.vid = @"Vid"; // Required. The video ID.
authSource.playAuth = @"<yourPlayAuth>"; // Required. The playback credential. To obtain a playback credential, call the GetVideoPlayAuth operation in ApsaraVideo VOD.
authSource.region = @"Access region"; // This parameter is deprecated in ApsaraVideo Player SDK V5.5.5.0 or later. If you use ApsaraVideo Player SDK V5.5.5.0 or later, the player automatically parses the region information. If you use ApsaraVideo Player SDK V5.5.5.0 or earlier, this parameter is required. Specify the ID of the region in which ApsaraVideo VOD is activated for this parameter. Default value: cn-shanghai.
// authSource.authTimeout = 3600; // Optional. The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 3600 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.

// Build the config parameter based on VidPlayerConfigGenerator
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"HLSEncryption"]; // Optional. If you set the encryption method to HLSEncryption, only videos that are encrypted by using HLS encryption are returned.
[config setHlsUriToken: @"xxxxxxx"]; // Optional. You can pass this parameter if you want to verify MtsHlsUriToken.
source.playConfig = [config generatePlayerConfig];

// Configure the playback source
[self.player setAuthSource:authSource];

Use VidSts to play an HLS-encrypted on-demand video

When playing a video encrypted with HLS encryption using the VidSts method, if the current video has other non-HLS encrypted streams or regular transcoded streams, you can filter and play only the HLS-encrypted streams by setting the video encryption type to HLSEncryption. The following sample code provides an example:

AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
source.vid = @"Vid"; // Required. The video ID.
source.region = @"Access region"; // Required. The region in which ApsaraVideo VOD is activated. Default value: cn-shanghai.
source.securityToken = @"<yourSecurityToken>"; // Required. The STS token. To generate an STS token, call the AssumeRole operation in STS.
source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS.
source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS.
// source.authTimeout = 3600; // Optional. The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 3600 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.

// Build the config parameter based on VidPlayerConfigGenerator
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"HLSEncryption"]; // Optional. If you set the encryption method to HLSEncryption, only videos that are encrypted by using HLS encryption are returned.
[config setHlsUriToken: @"xxxxxxx"]; // Optional. You can pass this parameter if you want to verify MtsHlsUriToken.
source.playConfig = [config generatePlayerConfig]; 

// Configure the playback source
[self.player setStsSource:source];

UrlSource-based playback of HLS-encrypted videos

When playing an HLS-encrypted video using the UrlSource method for live streaming or video-on-demand, the process is the same as playing a regular video. No additional parameters need to be set.

AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:url]; // Required. The playback URL of an HLS-encrypted live stream or on-demand video.
[self.player setUrlSource:urlSource];

DRM encryption

Note

On iOS platform, you need to call the setFairPlayCertID method in AliPlayerGlobalSettings globally once before [self.player prepare] to set the certificate ID. You can obtain the certificate ID from ApsaraVideo VOD console > Configuration Management > Media Processing Configuration > DRM Certificate Management.

 [AliPlayerGlobalSettings setFairPlayCertID:@"Certificate ID obtained from the console"];

Use VidSts to play a DRM-encrypted on-demand video

When playing DRM-encrypted videos using the VidSts method, the configuration is the same as playing regular videos. No additional parameters are required.

AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
source.region = @"Access region"; // Required. The region in which ApsaraVideo VOD is activated. Default value: cn-shanghai.
source.vid = @"Vid"; // Required. The ID of the video.
source.securityToken = @"<yourSecurityToken>"; // Required. The STS token. To generate an STS token, call the AssumeRole operation in STS.
source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS.
source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS.
// source.authTimeout = 3600; // Optional. The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 3600 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.
 // Configure the playback source
 [self.player setStsSource:source]

Use LiveStsSource to play a DRM-encrypted live stream

When playing DRM-encrypted videos using the LiveStsSource method, you need to provide the URL and STS credentials, and set the video encryption type to ENCRYPTION_TYPE_FAIRPLAY. The following sample code provides examples:

  1. Create a DataSource.

    You must set AVPLiveStsSource as the playback source.

    // Create LiveSts, encryptionType needs to be set to ENCRYPTION_TYPE_FAIRPLAY
    AVPLiveStsSource *liveStsSource = [[AVPLiveStsSource alloc] initWithUrl:@"Streaming URL" 
                                                                accessKeyId:@"Temporary AccessKey ID" 
                                                                accessKeySecret:@"Temporary AccessKey secret" 
                                                                securityToken:@"Security token" 
                                                                region:@"Region name" 
                                                                domain:@"Streaming domain" 
                                                                app:@"Application name" 
                                                                stream:@"Stream name" 
                                                                encryptionType:ENCRYPTION_TYPE_FAIRPLAY];// Required. Set the encryption method to ENCRYPTION_TYPE_FAIRPLAY.
     // Configure the playback source
     [self.aliPlayer setLiveStsSource:liveStsSource];
     ......
     // Prepare for playback
     [self.aliPlayer prepare];

  2. Check whether the STS token is valid.

    The encryption key may change during the playback of encrypted live streams. When the key is changed, the player sends a request to obtain the latest key from STS. You must check whether the STS token is valid. If the token is invalid, the playback of encrypted live streams is affected.

     __weak typeof(self) weakSelf = self;
    [self.aliPlayer setVerifyStsCallback:^AVPStsStatus(AVPStsInfo info) {
        if (info can be used){
            return Valid;
        }
        if(A valid STS token can be obtained){
            Obtain STS();// This operation can be synchronously or asynchronously performed.
            return Pending;
        }
        [weakSelf.aliPlayer stop];
        return Invalid;
    }];
    Note

    After you obtain the STS token, you need to call the updateLiveStsInfo method to update the STS token. If the token failed to be obtained, we recommend that you stop the playback. If you do not update the STS token, the player uses the expired STS token to obtain the encryption key. If the STS token becomes invalid, the screen may flicker or the playback may fail.

    [self.aliPlayer updateLiveStsInfo:self.liveStsSource.accessKeyId accKey:self.liveStsSource.accessKeySecret token:self.liveStsSource.securityToken region:self.liveStsSource.region];

Flutter

Note

Flutter does not support DRM encryption.

Procedure

You can integrate ApsaraVideo Player SDK for Flutter into your application. The following content describes how to use ApsaraVideo Player SDK for Flutter for playback and provides sample code:

  1. Integrate ApsaraVideo Player SDK for Flutter into your project.

    For information about how to integrate ApsaraVideo Player SDK for Flutter, see Quick integration.

  2. Create a player for playback.

    For information about how to create a player, see Create a player. For Step 3: Create a playback source, select one of the following methods based on your requirements.

Alibaba Cloud proprietary cryptography

Use VidAuth to play an on-demand video encrypted by using Alibaba Cloud proprietary cryptography (HLS and MP4 formats)

When you use VidAuth to play an HLS or MP4 video encrypted by using Alibaba Cloud proprietary cryptography, if the video has other streams that are encrypted by using other encryption methods or streams that are not encrypted, you can set the encryption type to AliyunVoDEncryption to filter streams encrypted by using Alibaba Cloud proprietary cryptography for playback.

FlutterAliplayer.setEncryptType(EncryptType.AliyunVoDEncryption);// Optional. If you set the encryption type to AliyunVoDEncryption, only streams encrypted by using Alibaba Cloud proprietary cryptography are returned.
FlutterAliplayer.generatePlayerConfig().then((value) {
          this.fAliplayer.setVidAuth(
              vid: "Vid information",
              region: "Access region",// Required. The region in which ApsaraVideo VOD is activated. Default value: cn-shanghai.
              playAuth: "<yourPlayAuth>",// Required. The playback credential. To generate the playback credential, call the GetVideoPlayAuth operation in ApsaraVideo VOD.
              playConfig: value);
});

Use VidSts to play an on-demand video encrypted by using Alibaba Cloud proprietary cryptography (HLS and MP4 formats)

When you use VidSts to play an HLS or MP4 video encrypted by using Alibaba Cloud proprietary cryptography, if the video has other streams that are encrypted by using other encryption methods or streams that are not encrypted, you can set the encryption type to AliyunVoDEncryption to filter streams encrypted by using Alibaba Cloud proprietary cryptography for playback.

FlutterAliplayer.setEncryptType(EncryptType.AliyunVoDEncryption);// Optional. If you set the encryption type to AliyunVoDEncryption, only streams encrypted by using Alibaba Cloud proprietary cryptography are returned.
FlutterAliplayer.generatePlayerConfig().then((value) {
          this.fAliplayer.setVidSts(
              vid: "Vid information",
              region: "Access region",
              accessKeyId: "<yourAccessKeyId>",
              accessKeySecret: "<yourAccessKeySecret>",
              securityToken: "<yourSecurityToken>",
              playConfig: value);
        });

Alibaba Cloud License proprietary cryptography

Use UrlSource to play an on-demand video encrypted by using Alibaba Cloud License proprietary cryptography (HLS and MP4 formats)

Note

Only ApsaraVideo Player SDK for Flutter V6.8.0 and later support playing MP4 videos encrypted by using Alibaba Cloud License proprietary cryptography through UrlSource. V6.17.0 and later support playing HLS videos (single bitrate and multi-bitrate) encrypted by using Alibaba Cloud License proprietary cryptography.

When you use UrlSource to play an HLS or MP4 video encrypted by using Alibaba Cloud License proprietary cryptography, you can call the GetPlayInfo operation to obtain the playback URL of the video. You need to append etavirp_nuyila=1 to the end of the URL (position is not limited) before passing it to the player (only MP4 requires this parameter, HLS can use the original video URL directly). The configuration of the player SDK is the same as that for playing regular videos. No additional parameters need to be set.

Example 1 of a playback URL: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1

Example 2 of a playback URL: https://example.aliyundoc.com/test.mp4?auth_key=xxxxx&etavirp_nuyila=1

//Playback URL
String playURL = "https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1"

// Create a player instance
FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer();
fAliplayer.setUrl(playURL);
fAliplayer.prepare();

// The video list player
FlutterAliListPlayer fAliListPlayer = FlutterAliPlayerFactory.createAliListPlayer();
fAliListPlayer.addUrlSource(playURL,uid);
fAliListPlayer.moveTo("uid");

// Preload the video
FlutterAliPlayerMediaLoader fAliPlayerMediaLoader = FlutterAliPlayerMediaLoader();
fAliPlayerMediaLoader.load(playURL,"duration");

HTTP Live Streaming (HLS) encryption

Use VidAuth to play an HLS-encrypted on-demand video

When you use VidAuth to play an HLS-encrypted video, if the video has other streams that are encrypted by using other encryption methods or streams that are not encrypted, you can set the encryption type to HLSEncryption to filter HLS-encrypted streams for playback. The following sample code provides an example:

FlutterAliplayer.setEncryptType(EncryptType.HLSEncryption);// Optional. If you set the encryption type to HLSEncryption, only HLS-encrypted streams are returned.
FlutterAliplayer.setHlsUriToken("mtsHlsUriToken");// Optional. You can pass this parameter if you want to verify MtsHlsUriToken.
FlutterAliplayer.generatePlayerConfig().then((value) {
          this.fAliplayer.setVidAuth(
              vid: "Vid information",
              region: "Access region",// Required. The region in which ApsaraVideo VOD is activated. Default value: cn-shanghai.
              playAuth: "<yourPlayAuth>",// Required. The playback credential. To generate the playback credential, call the GetVideoPlayAuth operation in ApsaraVideo VOD.
              playConfig: value);
});

Use VidSts to play an HLS-encrypted on-demand video

When you use VidSts to play an HLS-encrypted video, if the video has other streams that are encrypted by using other encryption methods or streams that are not encrypted, you can set the encryption type to HLSEncryption to filter HLS-encrypted streams for playback. The following sample code provides an example:

FlutterAliplayer.setEncryptType(EncryptType.HLSEncryption);// Optional. If you set the encryption type to AliyunVoDEncryption, only streams encrypted by using Alibaba Cloud proprietary cryptography are returned.
FlutterAliplayer.setHlsUriToken("mtsHlsUriToken");// Optional. You can pass this parameter if you want to verify MtsHlsUriToken.
FlutterAliplayer.generatePlayerConfig().then((value) {
          this.fAliplayer.setVidSts(
              vid: "Vid information",
              region: "Access region",
              accessKeyId: "<yourAccessKeyId>",
              accessKeySecret: "<yourAccessKeySecret>",
              securityToken: "<yourSecurityToken>",
              playConfig: value);
        });

FAQ

For common issues and solutions during the encryption process, see Video encryption FAQ.

References