Combine o pré-carregamento do SDK do ApsaraVideo Player com miniaturas de vídeo para obter inicialização em nível de milissegundos. Essa abordagem elimina o carregamento lento e os travamentos em cenários de vídeos curtos.
Visão geral da solução
A reprodução de vídeo pode apresentar uma tela preta durante o carregamento inicial. Para evitar isso, ative o pré-carregamento no ApsaraVideo Player a fim de buscar os dados do vídeo antecipadamente. Além disso, defina o primeiro quadro como miniatura para exibi-lo imediatamente enquanto o vídeo carrega no buffer. O resultado é uma reprodução contínua, sem atrasos visíveis.
Com essa solução, o tempo médio de inicialização cai para cerca de 300 milissegundos em ambientes Wi-Fi.
Limites
Apenas o SDK do ApsaraVideo Player para Android e iOS oferece suporte à reprodução em tela cheia com carregamento rápido.
Pré-carregue apenas um arquivo MP4, MP3, FLV ou HLS por vez.
Reproduza vídeos pré-carregados exclusivamente com UrlSource. VidAuth e VidSts não são compatíveis com reprodução pré-carregada.
Pré-requisitos
O ApsaraVideo VOD está ativado. Para mais informações, consulte Ativar o ApsaraVideo VOD.
O SDK do ApsaraVideo Player está integrado. Integração rápida do SDK do ApsaraVideo Player para Android | Integração rápida do SDK do ApsaraVideo Player para iOS
Um nome de domínio CDN está configurado para o recurso de pré-busca no ApsaraVideo VOD. Adicionar um nome de domínio para CDN
Etapa 1: Ativar o recurso de pré-carregamento no SDK do ApsaraVideo Player
O pré-carregamento busca os dados do vídeo para o dispositivo local antes do início da reprodução, o que reduz o tempo de inicialização.
Limites
Atualmente, há suporte para carregar arquivos de mídia individuais, como MP4, MP3, FLV e HLS.
Configuração do player para Android
-
Ative o recurso de cache local.
Para ativar o recurso de cache local, chame
AliPlayerGlobalSettings.enableLocalCacheno arquivo/app/src/main/java/com/aliyun/alivcsolution/MutiApplication.java.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"); } } -
Crie uma instância de pré-carregamento e configure um callback para o status do pré-carregamento durante a inicialização da instância.
Essa definição encontra-se em
/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. } }); } ... -
Ao responder a uma solicitação de dados, chame a função
loadpara pré-carregar e armazenar os dados no caminho de disco especificado.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); ...
Configurar o SDK do ApsaraVideo Player para iOS
-
Ative o recurso de cache local e configure um callback para o status do pré-carregamento durante a inicialização da instância.
- (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 { } -
Chame a função
loadao configurar a fonte de dados para pré-carregar os dados no caminho de disco especificado.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.
Etapa 2: Definir o primeiro quadro do vídeo como miniatura
Defina o primeiro quadro como miniatura do vídeo para eliminar telas pretas durante a inicialização.
Ao reproduzir vídeos em uma lista, aplique a seguinte lógica para acelerar a reprodução e reduzir o tráfego:
Solicite apenas miniaturas quando o usuário deslizar rapidamente entre os vídeos.
Exiba a miniatura pré-buscada quando metade da visualização do próximo vídeo aparecer.
Console
-
Crie um modelo de snapshot para capturar o primeiro quadro.
Faça login no console do ApsaraVideo for VOD.
No painel de navegação à esquerda, escolha Configuration Management > Media Processing > Snapshot Templates.
-
Clique em Create Snapshot Template e configure os parâmetros para capturar o primeiro quadro.
Defina um Template Name personalizado. Selecione Normal Snapshot para Snapshot Type. Defina Start Time como 00:00:00 e Snapshot Count: como 1. Configure outros parâmetros conforme necessário (Modelos de snapshot).
Clique em Save para criar o modelo de snapshot.
-
Envie um job de snapshot para capturar o primeiro quadro.
NotaPara enviar um job de snapshot pelo console, crie um workflow com um nó Snapshots e selecione o modelo de snapshot de primeiro quadro (Gerenciar workflows).
Configure uma notificação de evento SnapshotComplete para receber o status da tarefa e a URL da imagem capturada após a conclusão do job (Configurações de callback).
-
Cenário 1: Capturar um snapshot durante o upload do vídeo
No console do ApsaraVideo for VOD, escolha Media Files > Audio/Video.
Clique em Upload Audio/Video e, em seguida, clique em Add Audio/Video.
Defina o método de upload e o local de armazenamento, adicione o arquivo de vídeo e selecione Use Workflow. Escolha o workflow criado para capturar o primeiro quadro.
Clique em Upload.
-
Cenário 2: Capturar um snapshot após o upload do vídeo
No console do ApsaraVideo for VOD, escolha Media Files > Audio/Video.
Na lista de áudio/vídeo, localize o vídeo desejado e clique em Media Processing na coluna Actions.
Defina Processing Type como Use Workflow e defina o parâmetro Workflows como o workflow criado para capturar o primeiro quadro.
Clique em OK.
-
Obtenha o resultado do snapshot
Se você configurou uma notificação de evento SnapshotComplete, obtenha o status da tarefa e a URL da imagem capturada por meio do callback.
Caso não tenha configurado notificações de evento, chame periodicamente a operação ListSnapshots para consultar o status da tarefa e a URL da imagem capturada.
-
Defina a miniatura do vídeo como o snapshot do primeiro quadro.
NotaSalve o snapshot da Etapa 2 no seu computador local antes de fazer o upload dele como miniatura.
No console do ApsaraVideo for VOD, escolha Media Files > Audio/Video.
Na lista de áudio/vídeo, localize o vídeo desejado e clique em Manage na coluna Actions.
Na aba Basic information, clique em Editing Video Information.
Clique em Upload, selecione o snapshot do primeiro quadro salvo localmente e clique em Open.
-
Clique em Save para definir a miniatura do vídeo.
Verifique a lista de áudio/vídeo para confirmar a atualização da miniatura.
-
Crie um modelo de snapshot para capturar o primeiro quadro.
Chame a operação AddVodTemplate para criar 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 enviar 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 modifica a miniatura de um único vídeo após o upload. Outros métodos incluem: Definir uma miniatura durante o upload do vídeo e Atualizar uma miniatura após o upload do vídeo.
Chame a operação UpdateVideoInfo e passe o parâmetro
CoverURLpara especificar 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; } } Faça login no console do ApsaraVideo VOD.
No painel de navegação à esquerda, escolha Configuration Management > CDN Configuration > Refresh and Prefetch.
-
Na aba Purge Cache, configure as informações de pré-busca.
Em Operation type, selecione Prefetch.
Purge Type: Este parâmetro é fixo como URL.
URL: Insira a URL do recurso de vídeo que deseja pré-buscar. Cada URL deve começar com http:// ou https://. É possível pré-buscar recursos de até 500 URLs por dia, com um limite de 100 URLs por solicitação.
Clique em Submit para concluir a configuração de pré-busca.
Chame a operação PreloadVodObjectCaches para pré-buscar recursos de vídeo.
OpenAPI
Os exemplos a seguir usam o SDK da Alibaba Cloud para Java para chamar operações da API do ApsaraVideo for VOD.
Procedimento
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;
}
}
Etapa 3: (Opcional) Pré-buscar recursos de vídeo
A pré-busca armazena em cache os recursos de vídeo do servidor de origem nos pontos de presença (POPs) da CDN antecipadamente. Os usuários recuperam os recursos diretamente dos POPs, o que acelera a reprodução e complementa o pré-carregamento no lado do cliente.
O recurso de pré-busca gera cobranças de tráfego de origem. Utilize a pré-busca seletivamente, com base na popularidade do vídeo.
Configuração pelo console
Configuração com OpenAPI
Etapa 4: Usar o ApsaraVideo Player para reproduzir vídeos
Reproduza vídeos usando o ApsaraVideo Player com UrlSource.