All Products
Search
Document Center

ApsaraVideo VOD:Use ApsaraVideo Player to perform instant loading in full screen mode

Last Updated:Dec 19, 2023

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 by 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

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

  • You can preload only videos that are played based on URLs. You cannot preload videos that use VidAuth or VidSts for playback.

Configure ApsaraVideo Player SDK for Android

  1. Enable the local caching feature.

    Enable the local caching feature by calling 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.

    Create a prefetch instance in the /AliyunListPlayer/src/main/java/com/aliyun/player/aliyunlistplayer/AliyunListPlayerActivity.java file.

    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 preload instance.
        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();
    
    
            // Configure a callback for the prefetch status.
            medialoader.setOnLoadStatusListener(new MediaLoader.OnLoadStatusListener() {
                @Override
                public void onError(String url, int code, String msg) {
                    // Listen for a loading error.
                }
    
                @Override
                public void onCompleted(String s) {
                    // Listen for the end of loading.
                }
    
                @Override
                public void onCanceled(String s) {
                    // Listen for the cancellation of loading.
                }
            });
        }
        ...
  3. 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.
                    // You can preload videos only by using URLs. You cannot use video IDs to preload video data.
                    // The following sample code provides an example on how to preload videos based on URLs by using medialoader.
                    String url="";// Obtain the video URL.
                    medialoader.load(url,10000);// Save the preloaded data to the specified disk path. The loading time is set to 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 the local caching feature. The path that the cache is stored must be a sandbox path. The maxBufferMemoryKB parameter is deprecated in ApsaraVideo Player SDK V5.4.7.1 and later and does not take 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];
            // Specify the callback methods.
            [AliPlayerGlobalSettings setCacheUrlHashCallback:hashCallback];
            
            // Configure a callback delegate to make sure that the preload URL and playback URL are the same. This prevents preload failures.
            [[AliMediaLoader shareInstance] setAliMediaLoaderStatusDelegate:self];
    
        }
        return _aliPlayer;
    }
    
    // Specify a callback method for video playback.
    NSString* hashCallback(NSString* url){
        NSString *md5Str = [NSString aliyun_MD5:url];
        return md5Str;
    }
    
    // Specify a callback method for video preload.
    #pragma mark -- AliMediaLoaderStatusDelegate
    /**
     @brief The callback that is invoked when an error occurs.
     @ param url The URL.
     @param code The error code.
     @ param msg The error description.
     */
    - (void)onError:(NSString *)url code:(int64_t)code msg:(NSString *)msg {
        
    }
    
    /**
     @ brief The callback that is invoked when the loading is complete.
     @ param url The URL.
     */
    - (void)onCompleted:(NSString *)url {
        
    }
    
    /**
     @ brief The callback that is invoked when the loading is canceled.
     @ param url The URL.
     */
    - (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.

Use the ApsaraVideo VOD console

  1. Create a snapshot template for capturing the first frame of a video.

    1. Log on to the ApsaraVideo VOD console.

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

    3. On the Snapshot Templates page, click Add Template. On the page that appears, configure the parameters for capturing the first frame of a video.

      Specify a custom template name for Template Name, set Snapshot Type to Normal Snapshot, Start Time to 00:00:00, and Snapshot Count to 1. Specify other parameters based on your business requirements. For more information about the parameters, see Manage snapshot templates.首帧截图1.png

    4. Click Save.

  2. Create a snapshot task to capture the first frame of the video.

    Note
    • To create a snapshot task in the ApsaraVideo VOD console, you must create a workflow, add a Snapshots node in the workflow, and then specify the snapshot template that you created to capture the first frame of a video. For more information about how to create a workflow, see Manage workflows.

    • We recommend that you configure the SnapshotComplete event notification before you create a snapshot task. This way, you can obtain information such as the task status and snapshot URL from the callback after the task is complete. For more information about how to configure event notifications, see Configure callbacks.

    • Scenario 1: Capture a snapshot during upload

      1. Log on to the ApsaraVideo VOD console. In the left-side navigation pane, choose Media Files > Audio/Video.

      2. On the Video and Audio page, click Upload. On the Upload Media page, click Add Media.

      3. In the Add Media dialog box, specify the upload method, storage address, and the file that you want to upload. Then, select Use Workflow from the drop-down list and the workflow that you created for capturing the first frame of a video.

      4. Click Upload.

    • Scenario 2: Capture a snapshot after upload

      1. Log on to the ApsaraVideo VOD console. In the left-side navigation pane, choose Media Files > Audio/Video.

      2. On the Video and Audio page, find the file for which you want to capture snapshots and click Media Processing in the Actions column.

      3. In the Media Processing dialog box, set Processing Type to Use Workflow and Workflow to the workflow that you created for capturing the first frame of a video.

      4. Click OK.

    • Obtain the results of the snapshot task

      • If you configure the SnapshotComplete event notification before you create a snapshot task, you can obtain information such as the task status and snapshot URL from the callback after the task is complete.

      • If you do not configure the SnapshotComplete event notification before you create a snapshot task, you can use the round-robin method to call the ListSnapshots operation to obtain information such as the task status and snapshot URL.

  3. Change the video thumbnail to the first frame of the video.

    Note

    You can change the thumbnail of a video in the ApsaraVideo VOD console only after the video is uploaded. To use the first frame of a video as the thumbnail, you must save the snapshot that you captured in Step 2 to your local device.

    1. Log on to the ApsaraVideo VOD console. In the left-side navigation pane, choose Media Files > Audio/Video.

    2. On the Video and Audio page, find the video for which you want to change the thumbnail and click Manage in the Actions column.

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

    4. On the page that appears, click Upload, select the snapshot that you captured in Step 2 from your local device, and then click Open.

    5. Click Save.

      You can check whether the video thumbnail is changed on the Video and Audio page.

Use the ApsaraVideo VOD API

Note

The following section describes how to call API operations to set the thumbnail of a video and provides sample code. ApsaraVideo VOD SDK for Java is used as an example.

Procedure

  1. Create a snapshot template for capturing the first frame of a video.

    Call the AddVodTemplate operation to create a snapshot template for capturing the first frame of a video. Sample code:

    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;
    
    
    /**
     * Note:
     * 1. The following sample code is used to create a snapshot template for capturing the first frame of a video and export an image. 
     * 2. We recommend that you create a snapshot template in the ApsaraVideo VOD console. 
     */
    public class AddSnapshotTemplate {
    
        // 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 do 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. 
        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("First-frame snapshot template");
            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 in which ApsaraVideo VOD is activated.
            String regionId = "cn-shanghai";  
            DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
    
            return client;
        }
    }
    
  2. Create a snapshot task to capture the first frame of the video.

    Call the SubmitSnapshotJob operation to submit a snapshot task. Sample code:

    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.profile.DefaultProfile;
    import com.aliyuncs.vod.model.v20170321.*;
    
    /**
     * Note:
     * 1. The following sample code is used to create a snapshot task after you create a snapshot template for capturing the first frame of a video. 
     * 2. After you upload a video to ApsaraVideo VOD, you can create a snapshot task for the video only after the VideoAnalysisComplete event callback is returned. This is not required for existing videos that are in the normal state. 
     * 3. Snapshot tasks are asynchronously processed. We recommend that you query the snapshot URL after the SnapshotComplete event callback is returned. 
     * 4. You can obtain the output URL of the snapshot from the SnapshotRegular parameter in the callback. For more information, see the "Generation of snapshot URLs" section of the SnapshotComplete topic. 
     * 5. If you do not enable the callback feature, you can call the ListSnapshots operation to query the most recent snapshot information. For more information, see ListSnapshots. 
     */
    public class SubmitSnapshotJob {
    
        // 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 do 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. 
        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");
            // Optional. The custom pass-through parameters. This parameter is used to identify the snapshot of the first frame. You can use the parameter in event callbacks.
            request.setUserData("{\"Extend\":{\"SnapshotType\":\"FirstFrame\",\"VideoId\":\"a42bf540********33b79f0102\"}}");
            return vodClient.getAcsResponse(request);
        }
    
        public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
            // The region in which ApsaraVideo VOD is activated.
            String regionId = "cn-shanghai";  
            DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
    
            return client;
        }
    
        // Call the ListSnapshots operation to 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 of the video.

    The following content describes how to change the video thumbnail after the video is uploaded. For more information about how to set the video thumbnail in other scenarios, see Set a thumbnail during upload and Change the thumbnail after the video is uploaded.

    To change the thumbnail of an uploaded video, call the UpdateVideoInfo operation and configure the CoverURL parameter. Sample code:

    package com.alibaba.bltest.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;
    
    /**
     * Note:
     * 1. The following sample code is used to change the thumbnail of a video. For more information about how to modify other video parameters, see the documentation of the UpdateVideoInfo operation. 
     * 2. Make sure that the thumbnail URL that you specify is accessible. 
     */
    public class UpdateVideoInfo {
    
        // 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 do 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. 
        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");
            // Set CoverURL to the URL of the image that is generated by the snapshot task for capturing the first frame of the video.
            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 {
            // Specify the region in which ApsaraVideo VOD is activated.
            String regionId = "cn-shanghai";  
            DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            return client;
        }
    }
    

Complete sample code

package com.alibaba.bltest.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;

/**
 * Note:
 * 1. The following sample code is used to capture a video snapshot and change the video thumbnail. You can modify the code based on your business requirements. 
 * 2. You must add specific logic to the following sample code before you can use the code. 
 * 3. The following sample code is for reference only. You can use other methods to capture a video snapshot and modify the video thumbnail. 
 */
public class SnapshotAndUpdateCover {

    // 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 do 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. 
    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);
            // The video ID.
            String videoId = "a42bf540b1b37*******b79f0102";

            // Scenario 1: The callback feature is enabled or Message Service (MNS) is activated
            // You can set the thumbnail of a newly uploaded video only after the VideoAnalysisComplete callback is returned.
            // To set the thumbnail of an existing video, call the submitSnapshotJob operation.
            submitSnapshotJob(vodClient,videoId);

            // After the SnapshotComplete callback is returned, obtain the snapshot type and the snapshot URL.
            JSONObject callBackMessage = new JSONObject();  // Specify the callback message.
            String snapshotType = callBackMessage.getJSONObject("UserData").getJSONObject("Extend").getString("SnapshotType");
            if("FirstFrame".equals(snapshotType)){

                // Specify the path in which the snapshot is stored based on your business requirements.
                String coverUrl = callBackMessage.getJSONArray("SnapshotInfos").getJSONObject(0).getString("SnapshotRegular").replace("{SnapshotCount}","00001");
                // Change the video thumbnail.
                updateVideoInfo(vodClient,videoId,coverUrl);
            }

            // Scenario 2: The callback feature is not enabled and MNS is not activated
            // To set the thumbnail of a newly uploaded video, use the round-robin method to obtain the video status.
            String videoStatus = "";
            while(!"Normal".equals(videoStatus)){
                videoStatus = getVideoInfo(vodClient,videoId);
                Thread.sleep(1000);
            }

            // To set the thumbnail of an existing video, call the submitSnapshotJob operation.
            submitSnapshotJob(vodClient,videoId);

            // Use the round-robin method to obtain the result of the snapshot task.
            String coverUrl = "";
            while(StringUtils.isBlank(coverUrl)){
                coverUrl = listSnapshots(vodClient,videoId);
                Thread.sleep(1000);
            }

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

        }
    }

    /**
     * Submit a snapshot task
     */
    public static SubmitSnapshotJobResponse submitSnapshotJob(DefaultAcsClient vodClient, String vid) throws ClientException {
        SubmitSnapshotJobRequest request = new SubmitSnapshotJobRequest();
        request.setVideoId(vid);
        request.setSnapshotTemplateId("1f27a7f*********70eba2756");
        // Optional. The custom pass-through parameters. This parameter is used to identify the snapshot of the first frame. You can use the parameter in event callbacks.
        request.setUserData("{\"Extend\":{\"SnapshotType\":\"FirstFrame\",\"VideoId\":\"a42bf540********33b79f0102\"}}");

        return vodClient.getAcsResponse(request);
    }

    /**
     * Change the video thumbnail
     */
    public static UpdateVideoInfoResponse updateVideoInfo(DefaultAcsClient vodClient, String vid, String coverUrl) throws ClientException {
        UpdateVideoInfoRequest request = new UpdateVideoInfoRequest();
        request.setVideoId(vid);
        // Set CoverURL to the URL of the image that is generated by the snapshot task for capturing the first frame of the video.
        request.setCoverURL(coverUrl);

        return vodClient.getAcsResponse(request);
    }

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

        return client;
    }

    /**
     * Query the captured 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;
    }

    /**
     * Query information about a 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.

Use the ApsaraVideo VOD console

  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 Refresh Cache tab, configure the prefetch information.

    • Set Operation to Prefetch.

    • Set Object 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.

Use the ApsaraVideo VOD API

  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.