All Products
Search
Document Center

ApsaraVideo VOD:Configure the preview feature

Last Updated:Dec 25, 2023

After you enable the preview feature, users can preview a predefined duration of the audio or video file. In most cases, this feature is used for paid media assets, such as lessons and TV series. This topic describes how to enable the preview feature and obtain the preview URL.

How it works

Alibaba Cloud ApsaraVideo VOD provides the preview feature. You can call the GetPlayInfo operation on the server side to specify the preview duration. This operation returns the preview URL. Alternatively, you can construct a signed preview URL that contains the preview information.

Important

If the preview duration that you specified exceeds the total duration of the video, you can use the preview URL that is returned by ApsaraVideo VOD to play the complete video.

The preview feature of Alibaba Cloud ApsaraVideo VOD is implemented based on Alibaba Cloud CDN. The basic principle of the preview feature is that the player uses a CDN-accelerated preview URL that contains information about the specified preview duration to access ApsaraVideo VOD. Before a file is returned, the system must verify the URL. If the preview URL passes the verification, the specified file is returned. Otherwise, access is denied and the HTTP 403 status code is returned. The following figure shows how the preview feature of ApsaraVideo VOD works.

流程提示

  1. You configure an accelerated domain name for CDN and enable the preview feature.

    Important

    Before you can use the preview feature, you must configure a domain name and enable the preview feature. For more information, see Enable the preview feature.

  2. The player sends a preview request to ApsaraVideo VOD.

  3. ApsaraVideo VOD generates a preview URL based on the domain name settings and the preview duration settings in the preview request.

    Note

    ApsaraVideo VOD allows you to call an API operation on the server side to generate a preview URL or construct a preview URL. For more information, see Call the GetPlayInfo operation to obtain the preview URL or Construct a preview URL.

  4. The player uses the preview URL to request the video from CDN.

Limits

  • ApsaraVideo VOD allows you to preview video files in the MP4 and HLS formats. The metadata of MP4 files must be contained in the file header. MP4 files whose metadata is contained in the file tail cannot be previewed. When ApsaraVideo VOD transcodes a video and converts its container format to MP4, the system places the metadata in the file header.

  • The preview duration is determined based on keyframes. We recommend that you do not use the preview feature for short videos. For long videos, we recommend that you set the preview duration to at least 30 seconds. By default, the keyframe interval of transcoded videos is 10 seconds.

    Note

    You can modify the keyframe interval in transcoding templates. For more information, see Configure regular transcoding templates.

  • The preview granularity of HLS files is the duration of each TS segment. The specified preview duration and the actual preview duration of the returned video may be different. The actual preview duration of the returned video is rounded up based on the specified preview duration. For example, if the TS segment duration is 10 seconds and the specified preview duration is 15 seconds, the preview duration of the returned video is 20 seconds.

Enable the preview feature

Before you call an operation to obtain the preview URL or you construct a preview URL, you must configure the domain name and enable the preview feature. To enable the preview feature, perform the following steps:

  1. Configure an accelerated domain name for CDN. For more information, see Add a domain name for CDN.

    Important

    To use the preview feature, an accelerated domain name for CDN must be configured.

  2. Enable URL signing and turn on Support Previewing. For more information, see URL signing.

    Important

    If the preview feature is not enabled for a domain name, requests for video playback cannot include preview parameters and the returned URL cannot be accessed. You must turn on Support Previewing when you configure URL signing.

    The following figure shows how to enable the preview feature in the VOD console.

    Note

    To manually construct a preview URL, you must specify the privateKey parameter to calculate the authentication value. The value is the Primary Key or Secondary Key value that is generated or entered in the console. Record the preceding values for subsequent use.

    开启试看功能

  3. Turn on Back-to-origin of Range and Drag/Drop Playback for the domain name. For more information, see Object chunking and Video seeking.

Call the GetPlayInfo operation to obtain the preview URL

ApsaraVideo VOD allows you to call the GetPlayInfo operation to obtain the preview URL of a video. For more information, see GetPlayInfo. You can integrate ApsaraVideo VOD SDKs and use the SDKs to call this operation to obtain the preview URL. To obtain the preview URL, perform the following steps.

Important

Before you call this operation, make sure that the preview feature is enabled. For more information, see Enable the preview feature.

  1. Integrate ApsaraVideo VOD SDKs based on your business requirements. For more information, see ApsaraVideo VOD SDK Quick Start.

  2. Use the SDKs to call the GetPlayInfo operation. You can specify the preview duration by using PreviewTime in PlayConfig when you call this operation. The server returns the preview URL based on the preview duration settings. For more information about the PlayConfig parameter, see Request parameters.

Show sample code in Java for obtaining a preview URL

Note
  • For more information about sample code in other languages, visit OpenAPI Explorer.

  • Obtain an AccessKey pair to complete identity verification so that you can call server API operations. For more information about how to obtain an AccessKey pair, see Obtain an AccessKey pair.


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;

/**
 * @date 2021/12/30
 */
public class VodPreviewTest {
    public static void main(String[] args) throws ClientException {
        // Specify the region in which ApsaraVideo VOD is activated. For more information, see Region IDs of ApsaraVideo VOD. 
        String regionId = "cn-shanghai";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. 
        // We recommend that you not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
        // In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
        // Specify your AccessKey ID.
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        // Specify your AccessKey secret.
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // Specify the ID of the video. Example: 533606af570e4db4961248d0978b****. If you upload a video by using the ApsaraVideo VOD console, you can choose Media Files > Audio/Video in the left-side navigation pane of the ApsaraVideo VOD console to view the ID of the video. If you upload a video by calling the CreateUploadVideo operation, the ID of the video is the value of VideoId in the response. 
        String videoId = "<your videoId>";
        DefaultAcsClient client = InitVodClient(regionId, accessKeyId, accessKeySecret);
        GetPlayInfoResponse response = null;
        try {
            response = getPlayInfo(client, videoId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("response = " + JSONObject.toJSONString(response));

    }

    /**
     * Initialize the client.
     *
     * @param regionId
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     * @throws ClientException
     */
    public static DefaultAcsClient InitVodClient(String regionId, String accessKeyId, String accessKeySecret) throws ClientException {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    /**
     * Obtain the preview URL.
     *
     * @param client
     * @param videoId
     * @return
     * @throws Exception
     */
    public static GetPlayInfoResponse getPlayInfo(DefaultAcsClient client, String videoId) throws Exception {
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        request.setVideoId(videoId);
        // Specify the validity period in seconds. Default value: 3600.
        request.setAuthTimeout(3600L);
        request.setFormats("mp4");
        JSONObject playConfig = new JSONObject();
        // Specify the preview duration in seconds. Minimum value: 1.
        playConfig.put("PreviewTime", "30");
        request.setPlayConfig(playConfig.toJSONString());
        return client.getAcsResponse(request);
    }
}
                

Construct a preview URL

ApsaraVideo VOD allows you to construct a signed URL that contains the preview information. To construct a signed URL, perform the following steps:

Important

Before you construct a preview URL, make sure that the preview feature is enabled. For more information, see Enable the preview feature.

  1. Construct a signed URL that contains the preview parameters. When you calculate the MD5 hash value for a signed preview URL, you must add previewTime that is used to calculate the preview duration.

    MD5 hash calculation for the URL of a video

    MD5 hash calculation for a preview URL

    MD5(uri-timestamp-rand-uid-PrivateKey)

    MD5(uri-timestamp-rand-uid-PrivateKey-previewTime)

    Note

    For more information about parameters in MD5 hash calculation and the methods that are used to construct a signed URL, see Configure URL signing. If you want to play the complete video, do not configure the previewTime parameter.

  2. Append &end=, followed by previewTime, to the end of the constructed signed URL.

Show sample code in Java for combining the dependencies required for JAR packages

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

Show sample code in Java for constructing a preview URL

    import java.util.UUID;
    import java.net.URL;
    import org.apache.commons.lang3.StringUtils;
    private String generateRand() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    private String md5(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(str.getBytes("UTF-8"));
            return bytesToHex(md5.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public String genAuthKey(String object, String privateKey, Long expireTime, Long previewTime) {
        String rand = "0";
        String uid = "0";
        if (StringUtils.isBlank(privateKey)) {
            return "";
        }
        rand = generateRand();
        long timestamp = System.currentTimeMillis() / 1000 + (expireTime == null ? 0 : expireTime);
        String authStr = timestamp + "-" + rand + "-" + uid;
        String md5Str = object + "-" + authStr + "-" + privateKey;
        if(previewTime!=0)
            md5Str = md5Str + "-" + previewTime;
        String auth_key = authStr + "-" + this.md5(md5Str);
        return auth_key;
    }

    public void previewTest() throws Exception {
        try {
            String key = "<Your PrivateKey>";// The primary key or secondary key that you configured in the VOD console. For more information, see Enable the preview feature. 
            String fileUrl = "<Your File URL>";// The URL of the file. Example: http://example.aliyundoc.com/test/bee21427ca3346848835c1bd786054c5-19bd8528c1d51576cd726cf86471ca0****.mp4.
            URL url = new URL(fileUrl);
            String file = url.getFile();
            Long previewTime = 120L;// The preview duration. 
            Long expireTime = 1800L;
            String auth_key =genAuthKey(file, key, expireTime, previewTime);
            fileUrl = fileUrl + "?auth_key=" + auth_key;
            if(previewTime != 0)
                fileUrl = fileUrl + "&end=" + previewTime;
            System.out.println(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }