Nota
Os exemplos a seguir usam o Alibaba Cloud SDK for Java para chamar operações da API do ApsaraVideo for VOD.
Procedimento
-
Crie um modelo de snapshot para capturar o primeiro quadro.
Chame a operação AddVodTemplate para crie um modelo de snapshot destinado à captura do primeiro quadro. O código a seguir fornece um exemplo:
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. This demo shows how to create a template to capture the first frame as a single snapshot.
* 2. We recommend using the ApsaraVideo for VOD console to create snapshot templates for a more convenient experience.
*/
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.
// Do not hard-code the AccessKey ID and AccessKey Secret in your project. Otherwise, the AccessKey pair may be leaked and the security of all your resources may be compromised.
// This example shows how to use environment variables to obtain the AccessKey pair for identity verification. Before you run the 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("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 where ApsaraVideo for VOD is activated.
String regionId = "cn-shanghai";
DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
return client;
}
}
-
Envie um job de snapshot para capturar o primeiro quadro.
Chame a operação SubmitSnapshotJob para envie um job de snapshot. O código a seguir fornece um exemplo:
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
/**
* Note:
* 1. This demo shows how to submit a snapshot job after a first-frame snapshot template is created.
* 2. For newly uploaded videos, we recommend performing this step after the `VideoAnalysisComplete` event succeeds. For existing videos with a Normal status, you can design your own process.
* 3. Snapshots are an asynchronous task. We recommend waiting for the `SnapshotComplete` event to succeed before you retrieve the snapshot URL.
* 4. You can infer the snapshot output URL from `SnapshotRegular` in the event callback. For more information about the URL generation rule, see the `SnapshotComplete` topic.
* 5. If you do not have a callback service, you can also call the `ListSnapshots` operation to poll for results. This operation returns only the latest snapshot result by default. For more information, see the `ListSnapshots` API reference.
*/
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.
// Do not hard-code the AccessKey ID and AccessKey Secret in your project. Otherwise, the AccessKey pair may be leaked and the security of all your resources may be compromised.
// This example shows how to use environment variables to obtain the AccessKey pair for identity verification. Before you run the 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");
// Optional. Custom pass-through parameters that are available in callbacks. Use this to identify the first-frame snapshot.
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 for VOD is activated.
String regionId = "cn-shanghai";
DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
return client;
}
// Call ListSnapshots 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);
}
}
-
Defina a miniatura do vídeo como o snapshot do primeiro quadro.
Este exemplo modifique a miniatura de um único vídeo após o upload. Outros métodos: Defina uma miniatura durante o upload do vídeo e Atualize uma miniatura após o upload do vídeo.
Chame a operação UpdateVideoInfo e passe o parâmetro CoverURL para especifique a miniatura do vídeo. O código a seguir fornece um exemplo:
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. This demo shows how to update the thumbnail of a single video. To modify other video parameters, see the `UpdateVideoInfo` API reference.
* 2. When updating a thumbnail, ensure that the image URL you provide is valid.
*/
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.
// Do not hard-code the AccessKey ID and AccessKey Secret in your project. Otherwise, the AccessKey pair may be leaked and the security of all your resources may be compromised.
// This example shows how to use environment variables to obtain the AccessKey pair for identity verification. Before you run the 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 setting the first-frame thumbnail, set `CoverURL` to the image URL that is output after the first-frame snapshot job succeeds.
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 for VOD is activated.
String regionId = "cn-shanghai";
DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
return client;
}
}
Exemplo completo
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. This demo provides the complete logic for taking a snapshot and updating a thumbnail. You must adapt parts of the code to your business logic.
* 2. This demo cannot be run directly. You must add the required logic.
* 3. This demo is for reference only and does not represent the only implementation method.
*/
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.
// Do not hard-code the AccessKey ID and AccessKey Secret in your project. Otherwise, the AccessKey pair may be leaked and the security of all your resources may be compromised.
// This example shows how to use environment variables to obtain the AccessKey pair for identity verification. Before you run the 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 use Message Service (MNS).
// If you set a thumbnail for a newly uploaded video, you must first receive the video analysis success event.
// If you set a thumbnail for an existing video, you can directly submit a snapshot job from this step.
submitSnapshotJob(vodClient,videoId);
// After you receive the `SnapshotComplete` event callback, determine the snapshot type and retrieve 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)){
// Replace the snapshot path logic here with your custom logic.
String coverUrl = callBackMessage.getJSONArray("SnapshotInfos").getJSONObject(0).getString("SnapshotRegular").replace("{SnapshotCount}","00001");
// Update the video thumbnail.
updateVideoInfo(vodClient,videoId,coverUrl);
}
// Scenario 2: You do not have a callback service or use MNS.
// If you set 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 set a thumbnail for an existing video, you can directly submit a 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);
}
// Update the video thumbnail.
updateVideoInfo(vodClient,videoId,coverUrl);
}catch (Exception e){
}
}
/**
* Submit a snapshot job.
*/
public static SubmitSnapshotJobResponse submitSnapshotJob(DefaultAcsClient vodClient, String vid) throws ClientException {
SubmitSnapshotJobRequest request = new SubmitSnapshotJobRequest();
request.setVideoId(vid);
request.setSnapshotTemplateId("1f27a7f*********70eba2756");
// Optional. Custom pass-through parameters that are available in callbacks. Use this to identify the first-frame snapshot.
request.setUserData("{\"Extend\":{\"SnapshotType\":\"FirstFrame\",\"VideoId\":\"a42bf540********33b79f0102\"}}");
return vodClient.getAcsResponse(request);
}
/**
* Update the video thumbnail.
*/
public static UpdateVideoInfoResponse updateVideoInfo(DefaultAcsClient vodClient, String vid, String coverUrl) throws ClientException {
UpdateVideoInfoRequest request = new UpdateVideoInfoRequest();
request.setVideoId(vid);
// When setting the first-frame thumbnail, set `CoverURL` to the image URL that is output after the first-frame snapshot job succeeds.
request.setCoverURL(coverUrl);
return vodClient.getAcsResponse(request);
}
/**
* Initialize the SDK instance.
*/
public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
// The region where ApsaraVideo for VOD is activated.
String regionId = "cn-shanghai";
DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
return client;
}
/**
* Query 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 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;
}
}