All Products
Search
Document Center

ApsaraVideo VOD:Advanced features

Last Updated:Nov 25, 2025

This topic provides examples of how to use the advanced features of ApsaraVideo Player SDK for Flutter. For a full description of all features, see the API reference.

Playback

Play short video lists

  1. Create a list player.

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

    The list player supports playback only from UrlSource and VidSts.

    // The uid parameter specifies the unique ID of a video. 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. Set the number of videos to preload.

    Setting a reasonable number of videos to preload can effectively reduce the startup time. The following code provides an example:

    // 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);
  4. Play the video source.

    // The uid parameter is required. For URL-based playback, specify only the UID. For STS-based playback, specify the STS information.
    fAliListPlayer.moveTo();

Switch between software and hardware decoding

ApsaraVideo Player SDK for Flutter supports hardware decoding for H.264 and H.265. This feature is enabled by default and can be controlled using the setEnableHardwareDecoder method. If hardware decoding fails to initialize, the player automatically switches to software decoding to ensure uninterrupted playback. The following code provides an example:

// Enable hardware decoding. This feature is enabled by default.
fAliplayer.setEnableHardwareDecoder(enable);

Switch video definition based on network conditions

ApsaraVideo Player SDK for Flutter supports adaptive bitrate streaming for HLS and DASH video streams. After the prepare method is successfully called, you can call the getMediaInfo method to retrieve the information for each stream, which is returned as TrackInfo. The following code provides an example:

fAliplayer.getMediaInfo().then((value) {
// The value is a map. You can use value['tracks'] to get the list of TrackInfos. To learn how to parse TrackInfo, see AVPMediaInfo info = AVPMediaInfo.fromJson(value); in the demo.

});

During playback, you can call the player's selectTrack method to switch the playback stream. This method uses the trackIndex from TrackInfo as its parameter. The result of the switch is returned in the callback when the OnTrackChangedListener listener is triggered.

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

Take snapshots

ApsaraVideo Player SDK for Flutter lets you take snapshots of the current video frame. This feature is implemented using the setOnSnapShot method.

// Listener for successful snapshots.
fAliplayer.setOnSnapShot((path,playerId) {

});
// Take a snapshot. path is the path where the image is saved.
fAliplayer.snapshot(path);

Preview videos

ApsaraVideo Player SDK for Flutter can be configured with ApsaraVideo VOD to enable the video preview feature. The preview feature is supported for VidAuth-based playback (recommended) and VidSts-based playback. For more information about how to configure and use the preview feature, see Video preview.

After you configure the preview feature, you can set the preview duration for the player using the previewTime parameter in the setVidAuth method. The following code provides an example:

// previewTime is 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");

Other configurations

ApsaraVideo Player SDK for Flutter provides other playback configurations. You must apply these configurations to the player before you call the prepare() method.

var configMap = {
 'mStartBufferDuration':_mStartBufferDurationController.text,// The buffer duration before playback starts, in milliseconds.
 'mHighBufferDuration':_mHighBufferDurationController.text,// The high-water mark for the buffer, in milliseconds.
 'mMaxBufferDuration':_mMaxBufferDurationController.text,// The maximum buffer duration, in milliseconds.
 'mMaxDelayTime': _mMaxDelayTimeController.text,// The maximum latency for live streaming, in milliseconds. Note: This parameter is valid only for live streaming.
 'mNetworkTimeout': _mNetworkTimeoutController.text,// The network timeout period, in 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 SEI.
 'mClearFrameWhenStop': !mShowFrameWhenStop,/// Specifies whether to clear the last 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 configurations.
fAliplayer.setConfig(configMap);

Performance

Pre-rendering

ApsaraVideo Player SDK for Flutter supports pre-rendering to display the first frame of a video quickly before playback starts.

Here is an example:

fAliplayer.setOption(FlutterAvpdef.ALLOW_PRE_RENDER, 1);

Local caching

ApsaraVideo Player SDK for Flutter provides a local caching feature to cache videos during playback. This helps reduce data traffic consumption when users play a video repeatedly. To use this feature, you must set enableLocalCache for the player before you call the prepare method. The following code provides an example:

/**
 *  Enable local caching. If 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 files. This must be an absolute path.
 *  @param mDocTypeForIOS - The sandbox directory type for iOS.
 */
FlutterAliplayer.enableLocalCache(bool enable,String maxBufferMemoryKB,String localCacheDir,DocTypeForIOS mDocTypeForIOS);

/**
  * Configurations for clearing cached files.
  *
  * @param expireMin - This parameter is deprecated and has no effect in v5.4.7.1 and later.
  * @param maxCapacityMB - The maximum cache size in MB. Default value: 20 GB. When the system clears the cache, if the total size of cached files exceeds this limit, the system sorts the cache items by their last access time and deletes the oldest files one by one until the total size is less than or equal to the limit.
  * @param freeStorageMB - The minimum free disk space in 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 the oldest cached files one by one until the free disk space is greater than or equal to this value or until all cached files are deleted.
  */
FlutterAliplayer.setCacheFileClearConfig(String expireMin,String maxCapacityMB,String freeStorageMB);

Enable or disable local caching for a single URL

To enable or disable local caching for a single URL, you can configure this setting in the player config. The following code provides an example:

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

Preloading

ApsaraVideo Player SDK for Flutter provides a preloading feature, which is an enhancement of the local caching feature. It improves video startup speed by allowing you to specify the size of the video cache in memory.

The preloading feature has the following limitations:

  • It supports loading single media files, such as MP4, MP3, FLV, and HLS files.

  • It supports preloading for videos played from UrlSource. Preloading is not supported for videos played from VidAuth or VidSts.

  1. Enable the local caching feature. For more information, see Local caching.

  2. Create a FlutterAliMediaLoaderV2 instance.

    FlutterAliMediaLoaderV2 loaderV2 = FlutterAliMediaLoaderV2();
  3. Set listeners for the preload task.

    1. onError: Listener for errors.

      loaderV2.onError = (ErrorInfo error) {
      };
    2. onCompleted: Listener for task completion.

      loaderV2.onCompleted = (taskId, urlOrVid) {
      };
    3. onCanceled: Listener for task cancellation.

      loaderV2.onCanceled = (taskId, urlOrVid) {
      };
  4. Set parameters for the preload task. This step is optional and applies only to multi-bitrate videos.

    You can set one of the following parameters: defaultQuality, defaultBandWidth, or defaultResolution.

    PreloadConfig config = PreloadConfig();
    config.duration = 1000;  // Default value: 1000
    config.defaultQuality = "FD";
    config.defaultBandWidth = 200000;
    config.defaultResolution  = 1920 * 1080;
    loaderV2.setPreloadConfig(config);
  5. Add a preload task and retrieve the task ID.

    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");
    });
  6. Pause the preload task.

    loaderV2.pauseTask(taskId);
  7. Resume the preload task.

    loaderV2.resumeTask(taskId);
  8. Cancel the preload task.

    loaderV2.cancelTask(taskId);
  9. Destroy the FlutterAliMediaLoaderV2 instance.

    loaderV2.dispose();

Video download

ApsaraVideo Player SDK for Flutter lets you download on-demand videos to local devices for offline playback. It supports both normal and secure download modes.

  • Normal download

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

  • Secure download

    Videos downloaded in this mode are encrypted by Alibaba Cloud. They can be played only using ApsaraVideo Player SDK.

Usage notes

  • You can download only videos that are played using 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 Offline download.

  • Resumable download is supported.

Procedure

  1. Optional: Configure the encryption and verification file for secure downloads. This step is required only for secure downloads and can be skipped for normal downloads.

    Note

    Ensure that the configured encryption and verification file matches the app information. Otherwise, the video download will fail.

    If you use the secure download mode, you must configure the key file that is generated in the ApsaraVideo VOD console for the ApsaraVideo Player SDK. This key file is used to decrypt and verify the video during download and playback. For more information about how to generate the key file, see Secure download.

    You only need to configure the key file once. The following code provides an example:

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

    The following code provides an example:

    FlutterAliDownloader downloader = FlutterAliDownloader.init();
    /// Set the save path.
    downloader.setSaveDir(path)
  3. Start the download.

    After you start the download, listeners are automatically set to return callback information. The following code provides an example:

    /// 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 a map that 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 may contain various types of information. For more information, see FlutterAvpdef.EventChanneldef. The following code provides 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 the downloaded video. 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 the video that failed to download. You can use event['errorCode'] and event['errorMsg'] to get the error code and error message.
     }
     });
     });
  4. Stop the download.

    The following code provides an example:

    downloader.stop(vid, index)
  5. Delete the download.

    This deletes the download task. If the task is deleted successfully, the corresponding local file is also deleted. The following code provides an example:

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

    When you no longer need a download object, call the release method to release it and prevent memory leaks. The following code provides an example:

    downloader.release(vid, index)

Encrypted video playback

ApsaraVideo VOD supports HLS encryption, Alibaba Cloud proprietary cryptography, and DRM encryption. For more information about playing encrypted videos, see Play an encrypted video.