All Products
Search
Document Center

ApsaraVideo VOD:Fast-loading full-screen playback

Last Updated:Jan 28, 2026

You can use features of ApsaraVideo Player SDK such as preloading and video thumbnails to reduce the startup duration to milliseconds. This solves problems that may occur during short video playback such as long startup duration and video stuttering. This also provides an imperceptible loading experience and ensures smooth playback. This topic describes how to use ApsaraVideo Player to perform instant loading in full screen mode.

Solution overview

When you play a video, a black screen may be displayed as the loading takes a while. To reduce the startup time, you can enable the preload feature in ApsaraVideo Player to preload video resources. You can also specify a video thumbnail and display the thumbnail before video content is loaded. This prevents black screens. If you set the first frame of a video as the thumbnail, the first frame is displayed before the video is actually played. This delivers a quick and seamless playback experience.

You can use the solution to shorten the average startup time to about 300 milliseconds in a Wi-Fi environment.

Limits

  • Only ApsaraVideo Player SDKs for Android and iOS support instant loading in full screen mode.

  • You can preload only one MP4, MP3, FLV, or HLS file at a time.

  • You can play the preloaded video only using UrlSource. You cannot use VidAuth or VidSts to play preloaded videos.

Prerequisites

Step 1: Enable the preload feature in ApsaraVideo Player SDK

After you enable the preload feature in ApsaraVideo Player SDK, video data is loaded to your local device in advance. This reduces the startup time.

Limits

  • It currently supports loading single media files such as MP4, MP3, FLV, and HLS.

Android player configuration

  1. Enable the local caching feature.

    To enable the local caching feature, call AliPlayerGlobalSettings.enableLocalCache in the /app/src/main/java/com/aliyun/alivcsolution/MutiApplication.java file.

    public class MutiApplication extends Application {
    
        @Override
        protected void attachBaseContext(Context base) {
            super.attachBaseContext(base);
            MultiDex.install(this);
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            // Enable the local caching feature. The path that the cache is stored must be an absolute path. Example: /tmp. The maxBufferMemoryKB parameter in the following sample code is deprecated in ApsaraVideo Player SDK V5.4.7.1 and later and does not take effect.
            AliPlayerGlobalSettings.enableLocalCache(true,10240,"/tmp");
    
          
        }
    
    }
  2. Create a preload instance. Configure a callback for the preload status during instance initialization.

    This is defined in /AliyunListPlayer/src/main/java/com/aliyun/player/aliyunlistplayer/AliyunListPlayerActivity.java.

    public class AliyunListPlayerActivity extends AppCompatActivity {
    
        private AliyunListPlayerView mListPlayerView;
        private NetWatchdog mNetWatchDog;
        private String mUserToken;
        private boolean mIsLoadMore = false;
        private int mLastVideoId = -1;
        private ImageView mBackImageView;
        
        // Create a singleton for preloading.
        private MediaLoader medialoader=MediaLoader.getInstance();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_aliyun_list_player);
            mUserToken = getIntent().getStringExtra("list_player_user_token");
    
            initView();
            initSts(true);
            initListener();
    
    
            // Set the callback for the loading status.
            medialoader.setOnLoadStatusListener(new MediaLoader.OnLoadStatusListener() {
                @Override
                public void onError(String url, int code, String msg) {
                    // An error occurred during loading.
                }
    
                @Override
                public void onCompleted(String s) {
                    // The loading is complete.
                }
    
                @Override
                public void onCanceled(String s) {
                    // The loading is canceled.
                }
            });
        }
        ...
  3. When you respond to a data request, call the load function to preload and store data to the specified disk path.

    private void getDatas(int id){
            GetVideoInfomation getVideoInfomation = new GetVideoInfomation();
            getVideoInfomation.getListPlayerVideoInfos(this, "1", mUserToken, id, new GetVideoInfomation.OnGetListPlayerVideoInfosListener() {
                private SparseArray<String> mSparseArray;
                @Override
                public void onGetSuccess(Request request, String result) {
                    // The demo list player uses only video IDs to request video data.
                    // However, you can preload videos only using URLs, not video IDs.
                    // The following code provides an example of how to use medialoader to preload a video after you obtain its URL.
                    String url="";// Assume that you have obtained the video URL.
                    medialoader.load(url,10000);// Preload data and save it to a specified disk path. The loading duration is 10,000 milliseconds.
    
                    Gson gson = new Gson();
                    AliyunVideoListBean aliyunVideoListBean = gson.fromJson(result, AliyunVideoListBean.class);
                    
                    ...

Configure ApsaraVideo Player SDK for iOS

  1. Enable the local caching feature and configure a callback for the preload status during instance initialization.

    - (AliPlayer *)aliPlayer{
        if (!_aliPlayer && UIApplicationStateActive == [[UIApplication sharedApplication] applicationState]) {
            _aliPlayer = [[AliPlayer alloc] init];
            _aliPlayer.scalingMode =  AVP_SCALINGMODE_SCALEASPECTFIT;
            _aliPlayer.rate = 1;
            _aliPlayer.delegate = self;
            _aliPlayer.playerView = self.playerView;
    
            // Enable local caching. The local cache file path must be a sandbox path. The maxBufferMemoryKB parameter is deprecated in v5.4.7.1 and later and has no effect.
            NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
            [AliPlayerGlobalSettings enableLocalCache:YES maxBufferMemoryKB:10*1024 localCacheDir:[docDir stringByAppendingPathComponent:@"alivcCache"]];
            [AliPlayerGlobalSettings setCacheFileClearConfig:30*60*24 maxCapacityMB:20480 freeStorageMB:0];
            // Set the URL callback method to prevent preload failures that occur when the preload URL and playback URL are inconsistent due to parameter changes.
            [AliPlayerGlobalSettings setCacheUrlHashCallback:hashCallback];
            
            // Set the callback delegate.
            [[AliMediaLoader shareInstance] setAliMediaLoaderStatusDelegate:self];
    
        }
        return _aliPlayer;
    }
    
    // The URL callback method.
    NSString* hashCallback(NSString* url){
        NSString *md5Str = [NSString aliyun_MD5:url];
        return md5Str;
    }
    
    // Callback methods for preloading.
    #pragma mark -- AliMediaLoaderStatusDelegate
    /**
     @brief The error callback.
     @param url The URL to load.
     @param code The error code.
     @param msg The error description.
     */
    - (void)onError:(NSString *)url code:(int64_t)code msg:(NSString *)msg {
        
    }
    
    /**
     @brief The completion callback.
     @param url The loaded URL.
     */
    - (void)onCompleted:(NSString *)url {
        
    }
    
    /**
     @brief The cancellation callback.
     @param url The URL whose loading was canceled.
     */
    - (void)onCanceled:(NSString *)url {
        
    }

  2. Call the load function when you configure the data source to preload data to the specified disk path.

    NSString *urlString = @"<URL>";
    AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:urlString];
    [_aliPlayer setUrlSource:urlSource];
    [[AliMediaLoader shareInstance] load:urlString duration:10000];// Save the preloaded data to the specified disk path. The loading time is set to 10,000 milliseconds.

Step 2: Set the first frame of a video as the thumbnail

You can set the first frame of a video as the thumbnail to deliver a quick and seamless playback experience.

Note

If you use ApsaraVideo Player to play videos in a list, you can use the following logic to deliver a quick playback experience and reduce traffic usage.

  • Only video thumbnails are requested when a user switches videos in a quick manner.

  • The prefetched video thumbnail is displayed when half of the view of the next video is displayed.

Configure using the console

  1. Create a snapshot template to capture the first frame of the video.

    1. Log on to the ApsaraVideo VOD console.

    2. In the left-side navigation pane, choose Configuration Management > Media Processing > Snapshot Templates.

    3. Click Create Snapshot Template and configure the first-frame snapshot template parameters.

      Set Template Name to a custom name and Snapshot Type to Normal Snapshot. Set Start Time to 00:00:00 and Snapshot Count: to 1. You can configure other parameters as needed. For more information about snapshot template parameters, see Snapshot templates.首帧截图1.png

    4. Click Save to create the snapshot template.

  2. Start a snapshot job to capture the first frame of the video.

    Note
    • Starting a snapshot job in the console requires a workflow. First, create a workflow that includes a Snapshots node. Then, set the snapshot template to the first-frame snapshot template. For more information about how to create a workflow, see Workflow management.

    • Before you start a snapshot job, configure event notifications for ApsaraVideo VOD. Set a notification for the SnapshotComplete event. This lets you retrieve the job status and the snapshot URL after the job is complete. For more information about how to configure event notifications, see Callback settings.

    • Scenario 1: Capture a snapshot during video upload

      1. In the ApsaraVideo VOD console, in the navigation pane on the left, choose Media Files > Audio/Video.

      2. Click Upload Audio/Video, and then click Add Audio/Video.

      3. Set the upload method and storage address, and add the video. Then, select Use Workflow and choose the pre-created workflow that includes the first-frame snapshot job.

      4. Click Upload.

    • Scenario 2: Capture a snapshot after video upload

      1. In the ApsaraVideo VOD console, choose Media Files > Audio/Video in the navigation pane on the left.

      2. On the Audio and Video page, click Media Processing in the row for the target video.

      3. Set Processing Type to Use Workflow. For the Workflows parameter, select the pre-created workflow that includes the first-frame snapshot job.

      4. Click OK.

    • Retrieve the snapshot result

      • If you have configured an event notification for the SnapshotComplete event in ApsaraVideo VOD, you can retrieve the job status and the URL of the snapshot from the callback event.

      • If you have not configured event notifications, you can use polling to call the ListSnapshots operation to query the job status and the URL of the snapshot.

  3. Change the video thumbnail to the first-frame snapshot.

    Note

    You can use the console to change a video thumbnail only after the video is uploaded. First, save the first-frame snapshot that you obtained in the previous step to your local computer to prepare for the upload.

    1. In the left navigation pane of the ApsaraVideo VOD console, choose Media Files > Audio/Video.

    2. On the Audio and Video List page, click Manage in the row for the target video.

    3. On the Basic information tab, click Editing Video Information .

    4. Click Upload, select the first-frame snapshot from your computer, and click Open.

    5. Click Save to set the video thumbnail.

      After the configuration is complete, you can verify that the thumbnail is updated on the audio and video list page.

Configure using an OpenAPI

Note

This topic uses the Alibaba Cloud SDK for Java as an example to demonstrate how to call ApsaraVideo VOD OpenAPI operations.

Procedure

  1. Create a snapshot template to capture the first frame of the video.

    Call the AddVodTemplate operation to create a snapshot template for capturing the first frame. The following sample code shows how to call the operation:

    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.profile.DefaultProfile;
    import com.aliyuncs.vod.model.v20170321.AddVodTemplateRequest;
    import com.aliyuncs.vod.model.v20170321.AddVodTemplateResponse;
    
    
    /**
     * Description:
     * 1. This demo shows how to create a first-frame snapshot template. The output is one image.
     * 2. Creating snapshot templates in the ApsaraVideo VOD console is more convenient.
     */
    public class AddSnapshotTemplate {
    
        // An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a RAM user to call API operations or perform routine O&M.
        // Do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account.
        // This example shows how to read the AccessKey pair from environment variables to verify identity. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
        public static String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        public static String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    
        public static void main(String[] args) {
    
            try{
                DefaultAcsClient vodClient = initVodClient(accessKeyId, accessKeySecret);
                AddVodTemplateResponse response = addSnapshotTemplate(vodClient);
                System.out.println("RequestId is:" + response.getRequestId());
                System.out.println("TemplateId is:" + response.getVodTemplateId());
            }catch (Exception e){
    
            }
        }
    
        public static AddVodTemplateResponse addSnapshotTemplate(DefaultAcsClient vodClient) throws ClientException {
            AddVodTemplateRequest request = new AddVodTemplateRequest();
            request.setName("FirstFrameSnapshotTemplate");
            request.setTemplateType("Snapshot");
            request.setTemplateConfig("{\"SnapshotType\":\"NormalSnapshot\",\"SnapshotConfig\":{\"FrameType\":\"normal\",\"Count\":1,\"Interval\":1,\"SpecifiedOffsetTime\":0}}");
    
            return vodClient.getAcsResponse(request);
        }
    
        public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
            // The region where ApsaraVideo VOD is activated.
            String regionId = "cn-shanghai";  
            DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
    
            return client;
        }
    }
    
  2. Start a snapshot job to capture the first frame of the video.

    Call the SubmitSnapshotJob operation to start a snapshot job. The following sample code shows how to call the operation:

    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.profile.DefaultProfile;
    import com.aliyuncs.vod.model.v20170321.*;
    
    /**
     * Description:
     * 1. This demo shows how to submit a first-frame snapshot job after you create a first-frame snapshot template.
     * 2. For newly uploaded videos, perform this step after the MediaProcessFinished event is successful. For existing videos that are in the Normal state, design your own process.
     * 3. Snapshotting is an asynchronous task. Wait for the SnapshotComplete event to succeed to get the snapshot URL.
     * 4. You can infer the snapshot output URL from the SnapshotRegular parameter in the callback event. For more information, see the snapshot URL generation rule in the SnapshotComplete topic.
     * 5. If you do not have a callback service, you can also call the ListSnapshots operation to query the result. By default, this operation returns only the latest snapshot result. For more information, see the ListSnapshots topic.
     */
    public class SubmitSnapshotJob {
    
        // An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a RAM user to call API operations or perform routine O&M.
        // Do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account.
        // This example shows how to read the AccessKey pair from environment variables to verify identity. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
        public static String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        public static String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    
        public static void main(String[] args) {
    
            try{
                DefaultAcsClient vodClient = initVodClient(accessKeyId, accessKeySecret);
                SubmitSnapshotJobResponse response = submitSnapshotJob(vodClient);
                System.out.println("RequestId is:" + response.getRequestId());
                System.out.println("JobId is:" + response.getSnapshotJob().getJobId());
            }catch (Exception e){
    
            }
        }
    
        public static SubmitSnapshotJobResponse submitSnapshotJob(DefaultAcsClient vodClient) throws ClientException {
            SubmitSnapshotJobRequest request = new SubmitSnapshotJobRequest();
            request.setVideoId("a42b**********633b79f0102");
            request.setSnapshotTemplateId("1f27a7**********eba2756");
            // Custom pass-through parameter. It is available in callbacks and is optional. It is used to distinguish the first-frame snapshot for the thumbnail.
            request.setUserData("{\"Extend\":{\"SnapshotType\":\"FirstFrame\",\"VideoId\":\"a42bf540********33b79f0102\"}}");
            return vodClient.getAcsResponse(request);
        }
    
        public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
            // The region where ApsaraVideo VOD is activated.
            String regionId = "cn-shanghai";  
            DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
    
            return client;
        }
    
        // ListSnapshots: Query snapshots
        public static ListSnapshotsResponse listSnapshots(DefaultAcsClient vodClient) throws ClientException {
            ListSnapshotsRequest request = new ListSnapshotsRequest();
            request.setVideoId("a42bf540b1b371ed804a6633b79****");
            request.setSnapshotType("NormalSnapshot");
    
            ListSnapshotsResponse response = vodClient.getAcsResponse(request);
            System.out.println("RequestId is:" + response.getRequestId());
            System.out.println("SnapshotUrl is:" + response.getMediaSnapshot().getSnapshots().get(0).getUrl());
            return vodClient.getAcsResponse(request);
        }
    
    }
    
  3. Change the video thumbnail to the first-frame snapshot.

    This section provides an example of how to modify the thumbnail of a single video after it is uploaded. For more information about other scenarios, see Set a thumbnail during video upload and Update a thumbnail after video upload.

    Call the UpdateVideoInfo operation and pass the CoverURL parameter to specify the video thumbnail. The following sample code shows how to call the operation:

    package com.alibaba.cloud.test.transcode;
    
    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.profile.DefaultProfile;
    import com.aliyuncs.vod.model.v20170321.UpdateVideoInfoRequest;
    import com.aliyuncs.vod.model.v20170321.UpdateVideoInfoResponse;
    
    /**
     * Description:
     * 1. This demo shows how to modify the thumbnail of a single video. To modify other video parameters, see the UpdateVideoInfo topic.
     * 2. When you modify a thumbnail, make sure that the image URL you use is valid.
     */
    public class UpdateVideoInfo {
    
        // An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a RAM user to call API operations or perform routine O&M.
        // Do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account.
        // This example shows how to read the AccessKey pair from environment variables to verify identity. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
        public static String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        public static String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    
        public static void main(String[] args) {
    
            try{
                DefaultAcsClient vodClient = initVodClient(accessKeyId, accessKeySecret);
                UpdateVideoInfoResponse response = updateVideoInfo(vodClient);
                System.out.println("RequestId is:" + response.getRequestId());
            }catch (Exception e){
    
            }
        }
    
        public static UpdateVideoInfoResponse updateVideoInfo(DefaultAcsClient vodClient) throws ClientException {
            UpdateVideoInfoRequest request = new UpdateVideoInfoRequest();
            request.setVideoId("a42b***********33b79f0102");
            // When you set the first-frame thumbnail, CoverURL is the image URL that is returned after the first-frame snapshot job is successful.
            request.setCoverURL("http://demo.aliyuncdn.com/a42bf5******40b1b37/snapshots/normal/41B7AF54-18672BB301D-1748-0984-309-112420****.jpg");
    
            return vodClient.getAcsResponse(request);
        }
    
        public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
            // The region where ApsaraVideo VOD is activated.
            String regionId = "cn-shanghai";  
            DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            return client;
        }
    }
    

Complete example

package com.alibaba.cloud.test.transcode;


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import org.apache.commons.lang3.StringUtils;

/**
 * Description:
 * 1. This demo shows the complete logic for taking a snapshot and modifying a thumbnail. You need to modify some of the code based on your business logic.
 * 2. This demo cannot be used directly. You need to add some logic yourself.
 * 3. This demo is for reference only and does not represent the only implementation method.
 */
public class SnapshotAndUpdateCover {

    // An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a RAM user to call API operations or perform routine O&M.
    // Do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account.
    // This example shows how to read the AccessKey pair from environment variables to verify identity. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
    public static String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    public static String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

    public static void main(String[] args) {


        try{
            DefaultAcsClient vodClient = initVodClient(accessKeyId, accessKeySecret);
            // Video ID
            String videoId = "a42bf540b1b37*******b79f0102";

            // Scenario 1: You have a callback service or MNS.
            // If you are setting a thumbnail for a newly uploaded video, you must first get the media analysis success event.
            // If you are setting a thumbnail for an existing video, you can start submitting the snapshot job from this step.
            submitSnapshotJob(vodClient,videoId);

            // Get the video snapshot success event, determine the snapshot type, and get the required image URL.
            JSONObject callBackMessage = new JSONObject();  // Replace this with the message received by the callback service.
            String snapshotType = callBackMessage.getJSONObject("UserData").getJSONObject("Extend").getString("SnapshotType");
            if("FirstFrame".equals(snapshotType)){

                // The snapshot path logic here needs to be replaced with your custom snapshot path logic.
                String coverUrl = callBackMessage.getJSONArray("SnapshotInfos").getJSONObject(0).getString("SnapshotRegular").replace("{SnapshotCount}","00001");
                // Modify the video thumbnail.
                updateVideoInfo(vodClient,videoId,coverUrl);
            }

            // Scenario 2: You do not have a callback service or MNS.
            // If you are setting a thumbnail for a newly uploaded video, poll the video status after the upload.
            String videoStatus = "";
            while(!"Normal".equals(videoStatus)){
                videoStatus = getVideoInfo(vodClient,videoId);
                Thread.sleep(1000);
            }

            // If you are setting a thumbnail for an existing video, you can start submitting the snapshot job from this step.
            submitSnapshotJob(vodClient,videoId);

            // Poll for the snapshot result.
            String coverUrl = "";
            while(StringUtils.isBlank(coverUrl)){
                coverUrl = listSnapshots(vodClient,videoId);
                Thread.sleep(1000);
            }

            // Modify the video thumbnail.
            updateVideoInfo(vodClient,videoId,coverUrl);
        }catch (Exception e){

        }
    }

    /**
     * Submits a snapshot job.
     */
    public static SubmitSnapshotJobResponse submitSnapshotJob(DefaultAcsClient vodClient, String vid) throws ClientException {
        SubmitSnapshotJobRequest request = new SubmitSnapshotJobRequest();
        request.setVideoId(vid);
        request.setSnapshotTemplateId("1f27a7f*********70eba2756");
        // Custom pass-through parameter. It is available in callbacks and is optional. It is used to distinguish the first-frame snapshot for the thumbnail.
        request.setUserData("{\"Extend\":{\"SnapshotType\":\"FirstFrame\",\"VideoId\":\"a42bf540********33b79f0102\"}}");

        return vodClient.getAcsResponse(request);
    }

    /**
     * Modifies the video thumbnail.
     */
    public static UpdateVideoInfoResponse updateVideoInfo(DefaultAcsClient vodClient, String vid, String coverUrl) throws ClientException {
        UpdateVideoInfoRequest request = new UpdateVideoInfoRequest();
        request.setVideoId(vid);
        // When you set the first-frame thumbnail, CoverURL is the image URL that is returned after the first-frame snapshot job is successful.
        request.setCoverURL(coverUrl);

        return vodClient.getAcsResponse(request);
    }

    /**
     * Initializes the SDK instance.
     */
    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        // The region where ApsaraVideo VOD is activated.
        String regionId = "cn-shanghai";  
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        return client;
    }

    /**
     * Queries snapshots.
     */
    public static String listSnapshots(DefaultAcsClient vodClient, String vid) throws ClientException {
        ListSnapshotsRequest request = new ListSnapshotsRequest();
        request.setVideoId(vid);
        request.setSnapshotType("NormalSnapshot");

        ListSnapshotsResponse response = vodClient.getAcsResponse(request);
        String coverUrl = "";
        System.out.println("RequestId is:" + response.getRequestId());
        try{
            coverUrl = response.getMediaSnapshot().getSnapshots().get(0).getUrl();
            System.out.println("SnapshotUrl is:" + response.getMediaSnapshot().getSnapshots().get(0).getUrl());
        }catch (NullPointerException e){

        }
        return coverUrl;
    }

    /**
     * Queries a single video.
     */
    public static String getVideoInfo(DefaultAcsClient vodClient, String vid) throws ClientException {
        GetVideoInfoRequest request = new GetVideoInfoRequest();
        request.setVideoId(vid);

        GetVideoInfoResponse response = vodClient.getAcsResponse(request);
        System.out.println("RequestId is:" + response.getRequestId());
        String videoStatus = "";
        try{
            videoStatus = response.getVideo().getStatus();
            System.out.println("Video Status is:" + response.getVideo().getStatus());
        }catch (NullPointerException e){

        }

        return videoStatus;
    }
}

Step 3: (Optional) Prefetch video resources

The prefetch feature allows ApsaraVideo VOD to prefetch video resources from the origin server and cache them on Alibaba Cloud CDN points of presence (POPs) in advance. This way, users can obtain the most recent resources from POPs without the need to retrieve them from the origin server. This accelerates video playback and facilitates video preloading on ApsaraVideo Player.

Note

You are charged for the origin traffic when you use the refresh and prefetch feature. You can use the prefetch feature based on the popularity of videos.

Console configuration

  1. Log on to the ApsaraVideo VOD console.

  2. In the left-side navigation pane, choose Configuration Management > CDN Configuration > Refresh and Prefetch.

  3. On the Purge Cache tab, configure the prefetch information.

    • For Operation type, select Prefetch.

    • Purge Type: This parameter is fixed to URL.

    • URL: Enter the URL of the video resource that you want to prefetch. Each URL must start with http:// or https://. You can prefetch resources from up to 500 URLs per day. You can specify up to 100 URLs in a request.

  4. Click Submit to complete the prefetch configuration.

Configuration with OpenAPI

  1. Call the PreloadVodObjectCaches operation to prefetch video resources.

Step 4: Use ApsaraVideo Player to play videos

Use ApsaraVideo Player to play videos based on UrlSource.