All Products
Search
Document Center

Apsara Video SDK:Advanced features

Last Updated:Nov 05, 2024

This topic describes how to use the advanced features of ApsaraVideo Player SDK for Flutter. For more information, see the "API description" topic.

Playback

Play short video lists

  1. Create a list player.

    FlutterAliListPlayer fAliListPlayer = FlutterAliPlayerFactory.createAliListPlayer();
  2. Add and remove resources.

    The list player can play videos only based on UrlSource or 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);
  3. Specify the number of videos that you want to preload.

    You can specify the number of videos that you want to preload based on your business requirements. This helps reduce the startup duration. Sample code:

    // Specify the number of videos that you want to preload. The total number of loaded videos can be calculated based on the following formula: 1 + 2 × Value specified for the count parameter. 
    fAliListPlayer.setPreloadCount(count);
  4. Play the video source.

    // The uid parameter is required. You need to specify only the UID for UrlSource-based playback. You need to specify the UID and Security Token Service (STS) information for VidSts-based playback.
    fAliListPlayer.moveTo();

Switch between hardware and software decoding

ApsaraVideo Player SDK for Flutter supports hardware decoding based on the H.264 and H.265 standards. You can call setEnableHardwareDecoder to enable or disable this feature. By default, hardware decoding is enabled. If hardware decoding fails to be initialized, software decoding is automatically used to ensure video playback. Sample code:

// Enable hardware decoding. By default, hardware decoding is enabled.
fAliplayer.setEnableHardwareDecoder(enable);

Enable adaptive bitrate streaming

ApsaraVideo Player SDK for Flutter supports adaptive bitrate streaming of HTTP-Live-Streaming (HLS) video streams and Dynamic Adaptive Streaming over HTTP (DASH) video streams. After the prepare method is called, call the getMediaInfo method to query the bitrate information, which is indicated by the TrackInfo parameter. Sample code:

fAliplayer.getMediaInfo().then((value) {
// Set the value parameter to map. You can use value['tracks'] to obtain information about the TrackInfos list. For more information about how to parse TrackInfo, see AVPMediaInfo info = AVPMediaInfo.fromJson(value) in the demo.

});

// During playback, you can call the selectTrack method to set the trackIndex parameter in TrackInfo to switch the bitrate. The switching result is returned in the OnTrackChangedListener callback.

// Switch the bitrate.
fAliplayer.selectTrack(index);
// Enable adaptive bitrate streaming.
fAliplayer.selectTrack(-1);

Capture snapshots

ApsaraVideo Player SDK for Flutter provides the setOnSnapShot method that allows you to capture snapshots from videos.

// The listener for snapshot capturing.
fAliplayer.setOnSnapShot((path,playerId) {

});
// The captured snapshot. path indicates the path to which the snapshot is stored.
fAliplayer.snapshot(path);

Preview videos

ApsaraVideo Player SDK for Flutter integrates specific configurations of ApsaraVideo VOD to support video preview. Only the VidAuth-based and VidSts-based playback methods are supported. We recommend that you preview videos by using the VidAuth-based playback method. For more information about how to configure and use the preview feature, see Configure the preview feature.

After you configure the preview feature, you can set previewTime in the setVidAuth method to specify the preview duration. Sample code:

// previewTime specifies the preview duration. Unit: seconds.
// Specify the VidAuth-based playback method.
fAliplayer.setVidAuth(
 vid: "Enter the video ID.",
 region: "Enter the region in which the resource resides.",
 playAuth: "Enter the playback credential of the resource.",
 previewTime: "Enter the preview duration. Unit: seconds.");

 // Specify the VidSts-based playback method.
 fAliplayer.setVidSts(
 vid: "Enter the video ID.",
 region: "Enter the region in which the resource resides.",
 accessKeyId: "Enter the AccessKey ID.",
 accessKeySecret: "Enter the AccessKey secret.",
 securityToken: "Enter the security token."
 previewTime: "Enter the preview duration. Unit: seconds.");

Other settings

You can configure other playback settings for ApsaraVideo Player SDK for Flutter. Before you call the prepare() method, you must set the following parameters for the player:

var configMap = {
 'mStartBufferDuration':_mStartBufferDurationController.text,// The buffer duration before playback. Unit: milliseconds.
 'mHighBufferDuration':_mHighBufferDurationController.text,// The duration of high buffer. Unit: milliseconds.
 'mMaxBufferDuration':_mMaxBufferDurationController.text,// The maximum buffer duration. Unit: milliseconds.
 'mMaxDelayTime': _mMaxDelayTimeController.text,// The maximum latency of live streaming. Unit: milliseconds. This parameter is valid only for live streaming.
 'mNetworkTimeout': _mNetworkTimeoutController.text,// The network timeout period. Unit: milliseconds.
 'mNetworkRetryCount':_mNetworkRetryCountController.text,// The number of retires after a network timeout.
 'mMaxProbeSize': _mMaxProbeSizeController.text,// The maximum probe size.
 'mReferrer': _mReferrerController.text,// The referer.
 'mHttpProxy': _mHttpProxyController.text,// The HTTP proxy.
 'mEnableSEI': mEnableSEI,// Specifies whether to use supplemental enhancement information (SEI).
 'mClearFrameWhenStop': !mShowFrameWhenStop,// Specifies whether to clear the view when the playback stops.
 'mDisableVideo': mDisableVideo,// Specifies whether to disable videos.
 'mDisableAudio': mDisableAudio,// Specifies whether to disable audio.
 'mUserAgent':mUserAgent,// The user agent.
};
// Apply the settings.
fAliplayer.setConfig(configMap);

Performance

Configure local caching

ApsaraVideo Player SDK for Flutter allows you to cache videos during playback. This saves your traffic during loop playback. To enable local caching, call the enableLocalCache method before you call the prepare method. Sample code:

/**
 *  Enable video preload. After this feature is enabled, a media file is cached on your device. 
 *
 *  @param enable - Specifies whether to enable the local caching feature. Valid values: true and false. A value of true indicates that the local caching feature is enabled. A value of false indicates that the local caching feature is disabled. Default value: false. 
 *  @param maxBufferMemoryKB - This parameter is discontinued in V5.4.7.1 and later.
 *  @param localCacheDir - The directory of the cached file, which is 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);

/**
  * Configure settings for clearing cached files. 
  *
  * @param expireMin - This parameter is discontinued in V5.4.7.1 or later. 
  * @param maxCapacityMB - The maximum cache size. Unit: MB. By default, the maximum cache size is 20 GB. If the specified maximum size is exceeded, the system deletes cached files based on the time when the file is cached until the cache size is less than or equal to the specified maximum size. The system preferentially deletes the earliest cache files. 
  * @param freeStorageMB - The minimum idle space of the disk. Unit: MB. Default value: 0. If the idle space of the disk is less than the specified minimum idle space, the system deletes cached files based on the time when the file is cached until the idle space of the disk is greater than or equal to the specified minimum idle space. The system preferentially deletes the earliest cache files. 
  */
FlutterAliplayer.setCacheFileClearConfig(String expireMin,String maxCapacityMB,String freeStorageMB);

Enable or disable local caching for a single URL

You can enable or disable local caching for a single URL by using the PlayerConfig class. Sample code:

// Obtain the settings.
fAliplayer.getPlayConfig().then((config){
  // Disable or enable the local caching feature.
  config.enableLocalCache = false;
  // Apply the settings.
  fAliplayer.setPlayConfig(config);
});

Preload videos

ApsaraVideo Player SDK for Flutter supports video preload, which is an upgrade of the local caching feature. The video preload feature allows you to specify the maximum size of memory that can be occupied by cached videos. This helps reduce the startup duration.

The video preload feature has the following 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 UrlSource. You cannot preload videos that are played based on VidAuth or VidSts.

  1. Enable the local caching feature. For more information, see the Configure local caching section of this topic.

  2. Obtain the FlutterAliPlayerMediaLoader instance.

    // The FlutterAliPlayerMediaLoader instance is a singleton object. You can create only one FlutterAliPlayerMediaLoader instance regardless of how many times you obtain the instance. 
    fAliPlayerMediaLoader = FlutterAliPlayerMediaLoader();
  3. Configure callbacks and start to load video files.

    /**
     * Configure callbacks for loading status.
     */
    fAliPlayerMediaLoader.setOnLoadStatusListener((completeURL) {
          // The callback for the end of loading.
        }, (cancelURL) {
          // The callback for the cancellation of loading.
        }, (String url, int code, String msg) {
          // The callback for the loading failure.
        });
    /**
     * Start to load video files. Asynchronous loading is supported. You can asynchronously load one or more video files at a time. 
     * @param url - The URL of the video file. 
     * @param duration - The loading duration. Unit: milliseconds. 
     */
    fAliPlayerMediaLoader.load("url","duration");

Configure video download settings

ApsaraVideo Player SDK for Flutter allows you to download on-demand videos to local devices for offline playback. The normal download mode and secure download mode are supported.

  • Normal download

    Videos that are downloaded in normal download mode are not encrypted by Alibaba Cloud and can be played by using third-party players.

  • Secure download

    Videos that are downloaded in the secure download mode are encrypted by Alibaba Cloud and can be played only by using ApsaraVideo Player SDK.

Usage notes

  • You can download videos that are played based on VidSts or VidAuth.

  • To use the video download feature, you must enable the feature and configure the download mode in the ApsaraVideo VOD console. For more information, see Configure download settings.

  • Resumable download is supported.

Procedure

  1. Optional. Configure the security file for encryption verification. You must configure the security file only when you use the secure download mode.

    Note

    Make sure that the information in the security file for encryption verification matches the application information. Otherwise, the video download fails.

    If you use the secure download mode, you must configure the key file generated in the ApsaraVideo VOD console in ApsaraVideo Player SDK. The key file is used to decrypt and verify the video for download and playback. For more information about how to generate the key file, see the "Enable secure download" section of the Configure download settings topic.

    You need to configure the key file only once. Sample code:

    FlutterAliPlayerFactory.initService(byteData);
  2. Create and configure a video downloader.

    Sample code:

    FlutterAliDownloader downloader = FlutterAliDownloader.init();
    /// Specify the path in which you want to save downloaded videos.
    downloader.setSaveDir(path)
  3. Start the download.

    After the download starts, listeners are automatically configured and a callback is returned. Sample code:

    ///1. Prepare for the download.
     /// Parameter description: Valid values of the type parameter are FlutterAvpdef.DOWNLOADTYPE_STS and FlutterAvpdef.DOWNLOADTYPE_AUTH. If the type parameter is set to DOWNLOADTYPE_STS, the vid, accessKeyId, accessKeySecret, and securityToken parameters are required. If the type parameter is set to DOWNLOADTYPE_AUTH, the vid and playAuth parameters are required.
     downloader.prepare(type, vid).then((value) {
     // Set the value parameter to map. This value corresponds to the custom download class DownloadModel in the demo.
     DownloadModel downloadModel = DownloadModel.fromJson(value);
     //2. Specify the resolution of the video that you want to download based on trackInfo.
     List<TrackInfoModel> trackInfos = downloadModel.trackInfos;
     downloader.selectItem(vid,trackInfos[0].index);
     //3. Start the download.
     downloader.start(vid, trackInfos[0].index).listen((event) {
     // Note: The event parameter may contain various information. You can refer to the settings of FlutterAvpdef.EventChanneldef. The following sample code provides an example:
     if (event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_PROGRESS){
     // event[EventChanneldef.DOWNLOAD_PROGRESS] indicates the download progress in percentage.
     }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_PROCESS){
     // event[EventChanneldef.DOWNLOAD_PROCESS] indicates the processing progress in percentage.
     }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_COMPLETION){
     // The download is complete. You can use event['vid'] and event['index'] to obtain the vid and index. vid and index are used to identify the downloaded video. You can use event['savePath'] to obtain the path of the downloaded video in local storage.
     }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_ERROR){
     // The download failed. You can use event['vid'] and event['index'] to obtain the vid and index. vid and index are used to identify the video that failed to be downloaded. You can use event['errorCode'] and event['errorMsg'] to obtain the error code and error message.
     }
     });
     });
  4. Stop the download.

    Sample code:

    downloader.stop(vid, index)
  5. Delete the downloaded file.

    After the method is called, the downloaded file is deleted. Sample code:

    downloader.delete(vid, index)
  6. Release the downloaded object.

    If you no longer need a downloaded object, you can call the release method to release the object to prevent memory leaks. Sample code:

    downloader.release(vid, index)

Encrypt videos for playback

ApsaraVideo VOD supports encrypted playback by using HLS encryption, Alibaba Cloud proprietary cryptography, or digital rights management (DRM) encryption. For more information about how to play encrypted videos, see Play an encrypted video.