All Products
Search
Document Center

ApsaraVideo VOD:Preview videos

Last Updated:Jan 28, 2026

Video preview lets users watch or listen to content, such as videos and audio, for a limited time. This feature is common for paid services, such as paid courses and short-form dramas. This topic describes how to enable the video preview feature for ApsaraVideo VOD and obtain a preview URL.

How it works

Alibaba Cloud ApsaraVideo VOD (VOD) provides the preview feature. You can obtain a preview URL by setting a preview duration when you call the server-side GetPlayInfo API operation, or by manually constructing a signed URL that contains the preview information.

Important

If the specified preview duration exceeds the total duration of the original video, users can play the entire video using the preview URL that is returned by ApsaraVideo VOD.

The video preview feature of ApsaraVideo VOD is implemented based on Alibaba Cloud CDN. The basic principle is as follows: The player sends a request that contains a preview URL (a CDN-accelerated domain name) with the specified preview duration. The cloud authenticates the preview URL. If the authentication is successful, the specified file content is returned. Otherwise, access is denied and a 403 error is returned. The following figure shows the video preview workflow.

流程提示

  1. You configure a CDN-accelerated domain name and enable the video 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. Your player sends a preview request to ApsaraVideo VOD.

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

    Note

    You can call a server-side API operation to generate a preview URL or construct a preview URL. For more information, see Call an API operation to obtain a preview URL or Manually construct a preview URL.

  4. Your player sends a request to CDN to play the preview video.

Limits

  • The video preview feature supports the MP4 and HLS file formats. For MP4 videos, the metadata must be in the file header. MP4 videos with metadata at the end of the file are not supported. When you use ApsaraVideo VOD to transcode a video into the MP4 container format, the metadata is placed in the file header.

  • The preview duration depends on keyframes. By default, a keyframe is generated every 10 seconds for output files that are transcoded by ApsaraVideo VOD. Therefore, we recommend that you do not use the preview feature for short videos. For long videos, set the preview duration to at least 30 seconds.

    Note

    You can modify the keyframe interval in transcoding templates. For more information, see Transcoding Templates.

  • For HLS files, the preview precision is based on the duration of a TS segment. The preview duration is rounded up to the nearest multiple of the TS segment duration. For example, if a TS segment is 10 seconds long and you set the preview duration to 15 seconds, a 20-second preview is returned.

Enable the video preview feature

Before you can call an API operation or manually construct a URL to obtain a preview URL, you must configure a domain name and enable the video preview feature. Follow these steps:

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

    Important

    The video preview feature is available only for domain names that are configured as CDN-accelerated domain names.

  2. You can enable URL signing for a domain name and also enable the preview feature. For more information, see URL signing.

    Important

    If the video preview feature is disabled for a domain name, you cannot include preview parameters in requests to ApsaraVideo VOD. The returned URL will be inaccessible. Therefore, you must turn on the Support Previewing switch when you enable URL signing.

    The following figure shows the console interface for enabling the video preview feature.

    Note

    To manually construct a preview URL, you must use the privateKey parameter to calculate the authentication value. Set this parameter to the value of the Primary Key or Secondary Key that you obtain from the console. Record the key value for future use.

    开启试看功能

  3. Enable Range origin fetch and video seeking for the domain name. For more information, see Configure Range origin fetch and Video seeking.

Call an API operation to obtain a preview URL

ApsaraVideo VOD provides an API operation to obtain video playback URLs. For more information about the API operation, see Obtain audio and video playback URLs. You can integrate a server-side SDK and use the SDK to call this operation to obtain a preview URL. To obtain the preview URL, follow these 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 the appropriate server-side SDK. For more information, see Quick Start for ApsaraVideo VOD SDKs.

  2. Call the Get audio and video playback URL API operation using the SDK. When you call the API operation, set the PreviewTime parameter within the PlayConfig parameter to specify the preview duration. The server returns a preview URL based on the specified duration. For more information about the PlayConfig parameter, see PlayConfig.

Click to view sample code for obtaining a preview URL (Java)

Note
  • For sample code in other languages, see OpenAPI.

  • Obtain an AccessKey pair to complete identity verification so that you can call ApsaraVideo VOD API operations. For more information about how to obtain an AccessKey pair, see Create 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 where ApsaraVideo VOD is activated. For more information, see ApsaraVideo VOD regions.
        String regionId = "cn-shanghai";
        // An AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
        // We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.
        // In this example, the AccessKey pair is obtained from environment variables. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
        // Your AccessKey ID.
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        // Your AccessKey secret.
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // The video ID. Example: 533606af570e4db4961248d0978b****. If you upload a video in the ApsaraVideo VOD console, you can log on to the console and choose Media Library > Audio/Video to view the video ID. If you upload a video by calling the CreateUploadVideo operation, the value of the VideoId parameter in the response is the video ID.
        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 video playback 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);
        // The validity period of the URL. Unit: seconds. If you do not set this parameter, the default value 3600 is used.
        request.setAuthTimeout(3600L);
        request.setFormats("mp4");
        JSONObject playConfig = new JSONObject();
        // The preview duration. Unit: seconds. The minimum value is 1.
        playConfig.put("PreviewTime", "30");
        request.setPlayConfig(playConfig.toJSONString());
        return client.getAcsResponse(request);
    }
}
                

Manually construct a preview URL

You can manually construct a signed URL that contains preview information. Follow these 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. Unlike when you construct a signed URL for full playback, you must include the preview duration parameter previewTime in the MD5 hash calculation for URL signing.

    MD5 hash calculation for a full video URL

    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 the parameters for the MD5 hash calculation and how to manually construct a signed URL, see Configure URL signing. If you want to allow full playback of the video, do not include the previewTime parameter.

  2. Append &end= to the end of the constructed signed URL. Then, add the preview parameter previewTime after &end= to generate the complete preview URL.

Click to view the dependencies required for the JAR package for manual construction (Java)

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

Click to view sample code for manually constructing a preview URL (Java)

    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 or secondary key that you configured in the console. For more information about how to obtain the key, see Enable the video preview feature.
            String fileUrl = "<Your File URL>";// The file URL. 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();
        }
    }