O ApsaraVideo Player SDK for Flutter oferece recursos avançados, como reprodução em lista, streaming de taxa de bits adaptativa, captura de snapshot, cache local, pré-carregamento e download de vídeo. Para obter a lista completa de recursos, consulte a referência da API.
Reprodução
Reproduzir listas de vídeos curtos
-
Crie um reprodutor de lista.
FlutterAliListPlayer fAliListPlayer = FlutterAliPlayerFactory.createAliListPlayer(); -
Adicione e remova recursos.
O reprodutor de lista suporta reprodução apenas a partir de UrlSource ou VidSts.
// The uid parameter specifies the unique ID of a video. You can use the UID to identify videos. Videos that have the same UID are considered the same. fAliListPlayer.addUrlSource(url,uid); fAliListPlayer.addVidSource(vid,uid); fAliListPlayer.removeSource(uid); -
Defina a quantidade de vídeos para pré-carregar.
Configure um número adequado de vídeos para pré-carregamento e melhore a velocidade de início. O código a seguir mostra um exemplo:
// Set the number of videos to preload. The total number of loaded videos is calculated using the following formula: 1 + count * 2. fAliListPlayer.setPreloadCount(count); -
Reproduza a source de vídeo.
// The uid parameter is required. For URL-based playback, specify only the uid. For STS-based playback, specify the STS information. fAliListPlayer.moveTo();
Alternar entre decodificação por hardware e software
O ApsaraVideo Player SDK for Flutter suporta decodificação por hardware H.264 e H.265 pelo método setEnableHardwareDecoder, ativado por padrão. Se a inicialização da decodificação por hardware falhar, o reprodutor reverte automaticamente para a decodificação por software. O código a seguir mostra um exemplo:
// Enable hardware decoding. This feature is enabled by default.
fAliplayer.setEnableHardwareDecoder(enable);
Alternar adaptativamente a definição do vídeo conforme as condições da rede
O ApsaraVideo Player SDK for Flutter suporta streaming de taxa de bits adaptativa para fluxos de vídeo HLS e Dynamic Adaptive Streaming over HTTP (DASH). Após o êxito do método prepare, chame getMediaInfo para recuperar informações sobre cada fluxo como um objeto TrackInfo. O código a seguir mostra um exemplo:
fAliplayer.getMediaInfo().then((value) {
// The value is of the map type. You can use value['tracks'] to get the corresponding TrackInfos list. For more information about how to parse TrackInfo, see AVPMediaInfo info = AVPMediaInfo.fromJson(value); in the demo.
});
Durante a reprodução, chame o método selectTrack para alternar o fluxo ativo. Passe o valor trackIndex do objeto TrackInfo como parâmetro. O resultado da alternância retorna no callback após o acionamento do listener OnTrackChangedListener.
// Switch the bitrate.
fAliplayer.selectTrack(index);
// Switch the bitrate and enable adaptive streaming.
fAliplayer.selectTrack(-1);
Capturar snapshots
O ApsaraVideo Player SDK for Flutter permite a captura de snapshots pelo método setOnSnapShot.
// The listener for successful snapshot capturing.
fAliplayer.setOnSnapShot((path,playerId) {
});
// Capture a snapshot. path specifies the path where the image is saved.
fAliplayer.snapshot(path);
Visualizar vídeos
O ApsaraVideo Player SDK for Flutter suporta visualização de vídeo quando usado com o ApsaraVideo VOD. Os métodos de reprodução VidAuth (recomendado) e VidSts suportam esse recurso. Para mais informações, consulte Visualização de vídeo.
Após configurar a visualização, defina a duração da prévia usando o método previewTime da interface setVidAuth. O código a seguir mostra um exemplo:
// previewTime specifies the preview duration in seconds.
// VidAuth-based playback
fAliplayer.setVidAuth(
vid: "Enter the VID of the resource",
region: "Enter the region of the resource",
playAuth: "Enter the PlayAuth of the resource",
previewTime: "Enter the preview duration in seconds");
// VidSts-based playback
fAliplayer.setVidSts(
vid: "Enter the VID of the resource",
region: "Enter the region of the resource",
accessKeyId: "Enter the AccessKey ID of the resource",
accessKeySecret: "Enter the AccessKey secret of the resource",
securityToken: "Enter the security token of the resource",
previewTime: "Enter the preview duration in seconds");
Outras configurações
Configure definições adicionais de reprodução antes de chamar o método prepare().
var configMap = {
'mStartBufferDuration':_mStartBufferDurationController.text,// The buffer duration before playback starts. Unit: milliseconds.
'mHighBufferDuration':_mHighBufferDurationController.text,// The high buffer duration. Unit: milliseconds.
'mMaxBufferDuration':_mMaxBufferDurationController.text,// The maximum buffer duration. Unit: milliseconds.
'mMaxDelayTime': _mMaxDelayTimeController.text,// The maximum latency for live streaming. Unit: milliseconds. Note: This parameter is valid only for live streaming.
'mNetworkTimeout': _mNetworkTimeoutController.text,// The network timeout period. Unit: milliseconds.
'mNetworkRetryCount':_mNetworkRetryCountController.text,// The number of retries after a network timeout.
'mMaxProbeSize': _mMaxProbeSizeController.text,// The maximum probe size.
'mReferrer': _mReferrerController.text,// The referrer.
'mHttpProxy': _mHttpProxyController.text,// The HTTP proxy.
'mEnableSEI': mEnableSEI,// Specifies whether to enable Supplemental Enhancement Information (SEI).
'mClearFrameWhenStop': !mShowFrameWhenStop,// Specifies whether to clear the frame when playback stops.
'mDisableVideo': mDisableVideo,// Specifies whether to disable video.
'mDisableAudio': mDisableAudio,// Specifies whether to disable audio.
'mUserAgent':mUserAgent,// The User-Agent.
};
// Apply the configuration.
fAliplayer.setConfig(configMap);
Desempenho
Pré-renderização
O ApsaraVideo Player SDK for Flutter suporta renderização rápida do primeiro quadro de vídeo antes do início da reprodução.
Este recurso vem desativado por padrão.
Defina a
Viewantes de chamarPreparepara garantir que os quadros sejam renderizados naViewprontamente assim que estiverem prontos.A ativação deste recurso altera a ordem de disparo dos eventos de sucesso de preparação e de renderização do primeiro quadro. Quando desativado, o evento de sucesso de preparação ocorre antes da renderização do primeiro quadro. Quando ativado, a renderização do primeiro quadro pode ocorrer antes do sucesso de preparação devido a diferenças nas velocidades de decodificação e renderização. Isso não afeta a reprodução.
O código a seguir mostra um exemplo:
fAliplayer.setOption(FlutterAvpdef.ALLOW_PRE_RENDER, 1);
Cache local
O ApsaraVideo Player SDK for Flutter suporta cache local, armazenando vídeos durante a reprodução para reduzir o tráfego em reproduções subsequentes. Ative enableLocalCache antes de chamar prepare. O código a seguir mostra um exemplo:
/**
* Enable local caching. After this feature is enabled, videos are cached to local files.
*
* @param enable - The switch for the local caching feature. true: enables local caching. false: disables local caching. Default value: false.
* @param maxBufferMemoryKB - This parameter is deprecated and has no effect in v5.4.7.1 and later.
* @param localCacheDir - The directory of the cached file. This must be an absolute path.
* @param mDocTypeForIOS - The type of the sandbox directory on your iOS device.
*/
FlutterAliplayer.enableLocalCache(bool enable,String maxBufferMemoryKB,String localCacheDir,DocTypeForIOS mDocTypeForIOS);
/**
* Configurations for clearing local cache files.
*
* @param expireMin - This parameter is deprecated and has no effect in v5.4.7.1 and later.
* @param maxCapacityMB - The maximum cache size. Unit: MB. Default value: 20 GB. When the system clears the cache, if the total cache size exceeds this limit, the system sorts cache items by their last access time and deletes the oldest cached files one by one until the total cache size is less than or equal to the limit.
* @param freeStorageMB - The minimum free disk space. Unit: MB. Default value: 0. When the system clears the cache, if the current free disk space is less than this value, the system also deletes cached files one by one according to the rules until the free disk space is greater than or equal to this value or all cached files are cleared.
*/
FlutterAliplayer.setCacheFileClearConfig(String expireMin,String maxCapacityMB,String freeStorageMB);
Ativar ou desativar o cache local para uma única URL
Para ativar ou desativar o cache local de uma URL específica, defina o parâmetro correspondente na player config. O código a seguir mostra um exemplo:
// Get the configurations.
fAliplayer.getPlayConfig().then((config){
// Disable or enable local caching.
config.enableLocalCache = false;
// Apply the configurations.
fAliplayer.setPlayConfig(config);
});
Pré-carregamento
O ApsaraVideo Player SDK for Flutter suporta pré-carregamento, aprimorando o cache local ao permitir especificar o tamanho de memória para o cache de vídeo e melhorar a velocidade de início.
O recurso de pré-carregamento possui as seguintes limitações:
Suporta o carregamento de arquivos de mídia individuais, como MP4, MP3, FLV e HLS.
Compatível apenas com vídeos reproduzidos pelo método UrlSource. Não há suporte para pré-carregamento nos métodos VidAuth ou VidSts.
Ative o recurso de cache local. Para mais informações, consulte Cache local.
-
Crie uma instância de
FlutterAliMediaLoaderV2.FlutterAliMediaLoaderV2 loaderV2 = FlutterAliMediaLoaderV2(); -
Configure os listeners para a tarefa de pré-carregamento.
-
onError: Listener para erros.loaderV2.onError = (ErrorInfo error) { }; -
onCompleted: Listener para conclusão da tarefa.loaderV2.onCompleted = (taskId, urlOrVid) { }; -
onCanceled: Listener para cancelamento da tarefa.loaderV2.onCanceled = (taskId, urlOrVid) { };
-
-
Opcional: Defina parâmetros para a tarefa de pré-carregamento. Esta etapa aplica-se apenas ao streaming de taxa de bits adaptativa.
Basta definir um dos seguintes parâmetros:
defaultQuality,defaultBandWidthoudefaultResolution.PreloadConfig config = PreloadConfig(); config.duration = 1000; // Default value: 1000 config.defaultQuality = "FD"; config.defaultBandWidth = 200000; config.defaultResolution = 1920 * 1080; loaderV2.setPreloadConfig(config); -
Adicione uma tarefa de pré-carregamento e recupere o ID da tarefa.
VidAuth (Recommended)
VidAuth auth = VidAuth( vid: "your videoId", playAuth: "your playAuth", region: "your region", ); loaderV2.addTask(auth).then((taskId) { print("MediaLoaderV2: taskId: $taskId"); });VidSts
VidSts vidSts = VidSts( vid: "your vid", accessKeyId: "your accessKeyId", accessKeySecret: "your accessKeySecret", securityToken: "your securityToken", ); loaderV2.addTask(vidSts).then((taskId) { print("MediaLoaderV2: taskId: $taskId"); });UrlSource
loaderV2.addTask(UrlSource(videoUrl: "videoUrl")).then((taskId) { print("MediaLoaderV2: taskId: $taskId"); }); -
Pause a tarefa de pré-carregamento.
loaderV2.pauseTask(taskId); -
Retome a tarefa de pré-carregamento.
loaderV2.resumeTask(taskId); -
Cancele a tarefa de pré-carregamento.
loaderV2.cancelTask(taskId); -
Destrua a instância
FlutterAliMediaLoaderV2.loaderV2.dispose();
Download de vídeo
O ApsaraVideo Player SDK for Flutter permite baixar vídeos sob demanda para reprodução offline. Existem dois modos de download disponíveis: normal e seguro.
-
Download normal
Os vídeos baixados neste modo não são criptografados pela Alibaba Cloud e podem ser reproduzidos em players de terceiros.
-
Download seguro
Neste modo, os vídeos baixados são criptografados pela Alibaba Cloud e só podem ser reproduzidos com o ApsaraVideo Player SDK.
Instruções de uso
O recurso de download de vídeo está disponível apenas para os métodos VidSts e VidAuth.
Para utilizar o download de vídeo, ative-o e configure um modo de download no console do ApsaraVideo VOD. Para mais informações, consulte Download offline.
Há suporte para download retomável.
Procedimento
-
Opcional: Configure o arquivo de segurança para verificação de criptografia. Esta etapa é necessária apenas para download seguro. Pule-a se for usar o download normal.
NotaCertifique-se de que o arquivo de segurança configurado corresponda às informações do aplicativo. Caso contrário, o download do vídeo falhará.
Se você optar pelo download seguro, configure o arquivo de chave gerado no console do ApsaraVideo VOD no ApsaraVideo Player SDK. Esse arquivo é usado para descriptografia e verificação durante o download e a reprodução do vídeo. Para mais detalhes sobre a geração do arquivo de chave, consulte Download seguro.
Trata-se de uma configuração única:
FlutterAliPlayerFactory.initService(byteData); -
Crie e configure um downloader.
O código a seguir mostra um exemplo:
FlutterAliDownloader downloader = FlutterAliDownloader.init(); /// Set the save path. downloader.setSaveDir(path) -
Inicie o download.
Ao iniciar o download, os listeners são registrados automaticamente e as informações de callback retornam. O código a seguir mostra um exemplo:
/// 1. prepare /// Parameter description: The type parameter can be set to FlutterAvpdef.DOWNLOADTYPE_STS or FlutterAvpdef.DOWNLOADTYPE_AUTH. If you set type to DOWNLOADTYPE_STS, the vid, accessKeyId, accessKeySecret, and securityToken parameters are required. If you set type to DOWNLOADTYPE_AUTH, the vid and playAuth parameters are required. downloader.prepare(type, vid).then((value) { // The value is of the map type. It corresponds to the custom download class DownloadModel in the demo. DownloadModel downloadModel = DownloadModel.fromJson(value); // 2. selectItem. Select the definition of the video to download based on the trackInfo. List<TrackInfoModel> trackInfos = downloadModel.trackInfos; downloader.selectItem(vid,trackInfos[0].index); // 3. start downloader.start(vid, trackInfos[0].index).listen((event) { // Note: The event parameter may contain various types of information. For more information, see FlutterAvpdef.EventChanneldef. The following section describes the details. if (event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_PROGRESS){ // The download progress in percentage. Get the download progress: event[EventChanneldef.DOWNLOAD_PROGRESS]. }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_PROCESS){ // The processing progress in percentage. Get the processing progress: event[EventChanneldef.DOWNLOAD_PROCESS]. }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_COMPLETION){ // The download is complete. You can use event['vid'] and event['index'] to get the corresponding vid and index to identify which video is downloaded. You can use event['savePath'] to get the local path of the downloaded video. }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_ERROR){ // The download failed. You can use event['vid'] and event['index'] to get the corresponding vid and index to identify which video failed to download. You can use event['errorCode'] and event['errorMsg'] to get the error code and error message. } }); }); -
Interrompa o download.
O código a seguir mostra um exemplo:
downloader.stop(vid, index) -
Exclua o download.
A exclusão de um download também remove o arquivo local. O código a seguir mostra um exemplo:
downloader.delete(vid, index) -
Libere o objeto de download.
Chame o método
releasepara liberar um objeto de download desnecessário e evitar vazamentos de memória. O código a seguir mostra um exemplo:downloader.release(vid, index)
Reprodução de vídeo criptografado
O ApsaraVideo VOD suporta criptografia HLS, criptografia proprietária da Alibaba Cloud e criptografia Digital Rights Management (DRM). Para mais informações sobre reprodução criptografada, consulte Reproduzir um vídeo criptografado.