All Products
Search
Document Center

ApsaraVideo VOD:Common features

Last Updated:Oct 09, 2023

This topic describes the common features of ApsaraVideo Player SDK for Flutter and provides sample code.

Basic features

Create a player

This section describes how to use ApsaraVideo Player SDK for Flutter to play videos. Manual playback and autoplay are supported.

Note

Before you play streams over Alibaba Real-Time Communication (ARTC), you need to add RTS dependencies to your project when you integrate ApsaraVideo Player SDK for Flutter. You also need to call FlutterAliPlayerFactory.loadRtsLibrary() on Android devices to load the dynamic libraries for the RTS SDK.

  1. Create a player.

    Create a player instance.

    FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer();

    Create multiple player instances.

    You must configure the playerId parameter when you create a player at the Flutter layer. The playerId parameter that is returned in the callback indicates the ID of the player.

    FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer(playerId: playerId);
  2. Configure listeners.

    You can configure multiple listeners for your player.

    • You must configure OnPrepard because you need to call the play method in the OnPrepard callback to start manual playback.

    • We recommend that you configure OnTrackReady and OnError.

    The following code block shows the API operations for specific listeners:

    // The listener for successful preparation.
    fAliplayer.setOnPrepard((playerId) {});
    // The listener for the display of the first frame.
    fAliplayer.setOnRenderingStart((playerId) {});
    // The listener for changes in the width or height of a video.
    fAliplayer.setOnVideoSizeChanged((width, height,playerId) {});
    // The listener for changes in the player status.
    fAliplayer.setOnStateChanged((newState,playerId) {});
    // The listener for the loading status.
    fAliplayer.setOnLoadingStatusListener(
        loadingBegin: (playerId) {},
        loadingProgress: (percent, netSpeed,playerId) {},
        loadingEnd: (playerId) {});
    // The listener for seeking completed.
    fAliplayer.setOnSeekComplete((playerId) {});
    // The listener for event callbacks, such as the buffer and playback progress. You can obtain event information based on the value of the FlutterAvpdef.infoCode parameter.
    fAliplayer.setOnInfo((infoCode, extraValue, extraMsg,playerId) {});
    // The listener for playback completed.
    fAliplayer.setOnCompletion((playerId) {});
    // The listener for a stream that is ready.
    fAliplayer.setOnTrackReady((playerId) {});
    // The listener for a snapshot that is taken.
    fAliplayer.setOnSnapShot((path,playerId) {});
    // The listener for errors.
    fAliplayer.setOnError((errorCode, errorExtra, errorMsg,playerId) {});
    // The listener for stream switching.
    fAliplayer.setOnTrackChanged((value,playerId) {});
  3. Configure a playback source.

    • ApsaraVideo Player SDK for Flutter supports video-on-demand (VOD) playback based on UrlSource, VidAuth, VidSts. Encrypted VOD playback is also supported. We recommend that you play videos based on VidAuth in ApsaraVideo VOD.

    • ApsaraVideo Player SDK for Flutter supports only UrlSource-based live streaming.

    Play on-demand videos

    UrlSource-based playback

    If you play an on-demand video based on UrlSource, you must set the setUrl parameter to the playback URL of the video. The playback URL is generated by ApsaraVideo VOD or a third-party service.

    You can call the GetPlayInfo operation to obtain the playback URL of a media file stored in ApsaraVideo VOD. We recommend that you use ApsaraVideo VOD SDK to obtain media playback URLs in ApsaraVideo VOD. This frees you from complex signature calculations. For more information about the GetPlayInfo operation, visit OpenAPI Explorer.

    void onViewPlayerCreated(viewId) async {
      // Specify the render view for the player.
      fAliplayer.setPlayerView(viewId);
      // Configure the playback source.
      switch (_playMode) {
          // Specify the UrlSource-based playback method.
        case ModeType.URL:
          this.fAliplayer.setUrl("Playback URL"); // Required. The playback URL. You can specify a playback URL generated by ApsaraVideo VOD or a third-party service. 
          break;
        default:
      }
    }

    (Recommended) VidAuth-based playback

    If you play an on-demand video based on VidAuth, set the vid parameter to the ID of the media file and set the playAuth parameter to the playback credential.

    • After you upload an audio or video file, you can log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video to view the ID of the audio or video file. Alternatively, you can call the SearchMedia operation provided by ApsaraVideo VOD SDK to obtain the ID.

    • You can call the GetVideoPlayAuth operation to obtain the playback credential. We recommend that you use ApsaraVideo VOD SDK to obtain credentials for media playback. This frees you from complex signature calculations. For more information about the GetVideoPlayAuth operation, visit OpenAPI Explorer.

    We recommend that you use VidAuth for video playback in ApsaraVideo VOD. Compared with video playback based on Security Token Service (STS), VidAuth-based playback is easier to use and more secure. For more information about the differences between the two playback methods, see Comparison between credentials and STS.

    void onViewPlayerCreated(viewId) async {
      // Specify the render view for the player.
      fAliplayer.setPlayerView(viewId);
      // Configure the playback source.
      switch (_playMode) {
        // Specify the VidAuth-based playback method.
        case ModeType.AUTH:
          FlutterAliplayer.generatePlayerConfig().then((value) {
          this.fAliplayer.setVidAuth(
              vid: "Vid",// Required. The video ID. 
              region: "Access region",// Required. The region in which ApsaraVideo VOD is activated. Default value: cn-shanghai. 
              playAuth: "<yourPlayAuth>",// Required. The playback credential. To generate the playback credential, call the GetVideoPlayAuth operation in ApsaraVideo VOD. 
              playConfig: value);
            });
          break;
        default:
      }
    }

    VidSts-based playback

    If you play an on-demand video based on VidSts, a temporary STS token is used instead of a playback credential. In this case, you must obtain an STS token and AccessKey pair (AccessKey ID and AccessKey secret) before you play videos on demand. For more information about how to obtain an STS token, see Create a RAM role and grant temporary access permissions to the role by using STS.

    void onViewPlayerCreated(viewId) async {
      // Specify the render view for the player.
      fAliplayer.setPlayerView(viewId);
      // Configure the playback source.
      switch (_playMode) {
        // Specify the VidSts-based playback method.
        case ModeType.STS:
          FlutterAliplayer.generatePlayerConfig().then((value) {
          this.fAliplayer.setVidSts(
              vid: "Vid",// Required. The video ID. 
              region: "Access region",// Required. The region in which ApsaraVideo VOD is activated. Default value: cn-shanghai. 
              accessKeyId: "<yourAccessKeyId>",// Required. The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS. 
              accessKeySecret: "<yourAccessKeySecret>",// Required. The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS. 
              securityToken: "<yourSecurityToken>",// Required. The STS token. To generate an STS token, call the AssumeRole operation in STS. 
          	  playConfig: value);
        	});
          break;
        default:
      }
    }

    Encrypted playback

    ApsaraVideo VOD supports HTTP-Live-Streaming (HLS) encryption, Alibaba Cloud proprietary cryptography, and digital rights management (DRM) encryption. For more information, see Play an encrypted video.

    UrlSource-based live streaming

    If you play a live stream based on UrlSource, you must set the setUrl parameter to the streaming URL of the live stream. The streaming URL is generated by ApsaraVideo Live or a third-party service.

    You can generate a streaming URL for a live stream by using the URL generator in the ApsaraVideo Live console. For more information, see URL generator.

    void onViewPlayerCreated(viewId) async {
      // Specify the render view for the player.
      fAliplayer.setPlayerView(viewId);
      // Configure the playback source.
      switch (_playMode) {
        // Specify the UrlSource-based streaming method.
        case ModeType.URL:
          this.fAliplayer.setUrl("Enter the streaming URL"); // The streaming URL is generated by ApsaraVideo Live or a third-party service. 
          break;
        default:
      }
    }
  4. Configure the view.

    If the playback source contains video images, you must configure the view to display the video images in the player. Sample code:

    @override
    Widget build(BuildContext context) {
      var x = 0.0;
      var y = 0.0;
      Orientation orientation = MediaQuery.of(context).orientation;
      var width = MediaQuery.of(context).size.width;
    
      var height;
      if (orientation == Orientation.portrait) {
        height = width * 9.0 / 16.0;
      } else {
        height = MediaQuery.of(context).size.height;
      }
      AliPlayerView aliPlayerView = AliPlayerView(
          onCreated: onViewPlayerCreated,
          x: x,
          y: y,
          width: width,
          height: height);
      return OrientationBuilder(
        builder: (BuildContext context, Orientation orientation) {
          return Scaffold(
            body: Column(
              children: [
                Container(
                    color: Colors.black,
                    child: aliPlayerView,
                    width: width,
                    height: height),
              ],
            ),
          );
        },
      );
  5. (Optional) Enable the autoplay feature. By default, this feature is disabled.

    fAliplayer.setAutoPlay(true);
  6. Prepare the player.

    Call the prepare() method to prepare the player.

    fAliplayer.prepare();
  7. Start the playback.

    • If the autoplay feature is not enabled, you must call fAliplayer.play() in the OnPrepard callback to start the playback.

    • If the autoplay feature is enabled, you do not need to call fAliplayer.play(). After the data is parsed, the video is automatically played.

    fAliplayer.play();

Manage playback

ApsaraVideo Player SDK for Flutter allows you to manage media playback. For example, you can start or pause the playback, or start the playback from a specific point in time.

Start the playback

You can call the play method to start the playback. Sample code:

 fAliplayer.play();

Play a video from a specified point in time

You can call the seek method to play a video from a specified point in time. You can use this feature if you need to drag the process bar of a video or resume the playback. Sample code:

// The position parameter specifies the point in time when playback starts. Unit: milliseconds. Valid values of seekMode: FlutterAvpdef.ACCURATE (accurate seeking) and FlutterAvpdef.INACCURATE (inaccurate seeking).
fAliplayer.seek(position,seekMode);

Pause the playback

You can call the pause method to pause the playback. Sample code:

fAliplayer.pause();

Stop the playback

You can call the stop method to stop the playback. Sample code:

fAliplayer.stop();

Specify the display mode

ApsaraVideo Player SDK for Flutter allows you to configure display settings for playback. For example, you can specify how video images are scaled, rotated, or mirrored.

Scaling

You can call setScaleMode to scale in or scale out a video without changing the original aspect ratio, or stretch a video. Sample code:

// Scale in the video to fit the view. The aspect ratio of the video is maintained.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALEASPECTFIT);
// Scale out the video to fill the view. The aspect ratio of the video is maintained.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALEASPECTFILL);
// Stretch the video to fill the view. The aspect ratio of the video is not maintained. If the aspect ratios of the video and the view are different, image distortion may occur.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALETOFILL);

Rotating

You can call setRotateMode to specify a rotation angle for video images. After you rotate the image, you can also query the rotation angle. Sample code:

// Set the rotation angle to 0° in the clockwise direction.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_0);
// Set the rotation angle to 90° in the clockwise direction.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_90);
// Set the rotation angle to 180° in the clockwise direction.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_180);
// Set the rotation angle to 270° in the clockwise direction.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_270);
// Query the rotation angle.
fAliplayer.getRotateMode();

Mirroring

ApsaraVideo Player SDK for Flutter supports three image mirroring modes: no image mirroring, horizontal image mirroring, and vertical image mirroring. You can call setMirrorMode to set the image mirroring mode. Sample code:

// Specify no mirroring for the video images.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_NONE);
// Specify horizontal mirroring for the video images.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_HORIZONTAL);
// Specify vertical mirroring for the video images.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_VERTICAL);        

Query the playback information

ApsaraVideo Player SDK for Flutter allows you to obtain the playback progress and playback duration.

Obtain the current playback progress

You can obtain the playback progress from the onInfo callback. Unit: milliseconds. Sample code:

fAliplayer.setOnInfo((infoCode,extraValue,extraMsg,playerId){
        if(infoCode==FlutterAvpdef.CURRENTPOSITION){
        // The extraValue parameter indicates the current playback progress.
}
});

Query the playback duration

You can query the total duration of a video. You can obtain the total duration of a loaded video after the AVPEventPrepareDone event is complete. Sample code:

fAliplayer.getMediaInfo().then((value){
        _videoDuration=value['duration'];
});

Obtain the player status

You can obtain the player status from the onStateChanged callback. Sample code:

fAliplayer.setOnStateChanged((newState,playerId){
    // newState indicates the playback status.
switch(newState){
            caseFlutterAvpdef.AVPStatus_AVPStatusIdle:        // The player is idle.
                    break;
            caseFlutterAvpdef.AVPStatus_AVPStatusInitialzed: // The player is initialized.
                    break;
            caseFlutterAvpdef.AVPStatus_AVPStatusPrepared: // The player is prepared.
                    break;
            caseFlutterAvpdef.AVPStatus_AVPStatusStarted: // he player is playing a media stream.
                    break;
            caseFlutterAvpdef.AVPStatus_AVPStatusPaused: // The playback is paused.
break;
            caseFlutterAvpdef.AVPStatus_AVPStatusStopped: // The playback is stopped.
break;
            caseFlutterAvpdef.AVPStatus_AVPStatusCompletion: // The playback is complete.
break;
            caseFlutterAvpdef.AVPStatus_AVPStatusError: // A playback error occurs.
break;
default:
    }
});

Configure the volume

ApsaraVideo Player SDK for Flutter allows you to change the volume of a video or mute the video.

Change the volume

You can change the volume of a video to up to twice the original volume. However, noise may occur if you set the volume to a value higher than 1. Call setVolume to change the volume. You can also obtain the current volume. Sample code:

// Set the volume to a real number from 0 to 2. 
fAliPlayer.setVolume(1);
// Obtain the volume information. 
fAliPlayer.getVolume();

Configure the mute mode

Call setMute to mute a video being played. Sample code:

fAliplayer.setMute(true);

Configure the playback speed

ApsaraVideo Player SDK for Flutter allows you to call setRate to change the playback speed. Playback speeds ranging from 0.5x to 5x are supported. The audio pitch remains unchanged at different speeds. Sample code:

// Playback speeds ranging from 0.5x to 5x are supported. Common playback speeds are multiples of 0.5x, such as 0.5x, 1x, and 1.5x.
fAliplayer.setRate(1.0);

Configure multi-definition settings

If you play a video based on VidAuth or VidSts, you do not need to configure multi-definition settings for the playback. We recommend that you play videos based on VidAuth. ApsaraVideo Player SDK for Flutter obtains the list of definitions from ApsaraVideo VOD. The SDK allows you to obtain video definitions and switch between definitions. This feature is not supported for UrlSource-based playback.

Obtain video definitions

After you load a video, you can obtain the video definitions.

fAliplayer.getMediaInfo().then((value){
        AVPMediaInfoinfo=AVPMediaInfo.fromJson(value);
info.tracks.forEach((element){
                if(element.trackType==3){
        // The definition.
    Stringdefinition=element.trackDefinition;
// The index file of media streams.
intindex=element.trackIndex;
                }
        }
});

Switch between definitions

You can set the trackIdx parameter in the selectTrack method to switch the definition.

fAliplayer.selectTrack(trackIdx);

Set the callbacks for definition switching

Set the callbacks for the successful definition switching.

fAliplayer.setOnTrackChanged((value,playerId){
        // If the callback is returned, the video resolution is switched. Otherwise, the resolution fails to be switched. ApsaraVideo Player SDK for Flutter does not provide a method for you to configure notifications for switching failures.
});

Enable loop playback

ApsaraVideo Player SDK for Flutter supports loop playback. Call setLoop to enable loop playback. The loop playback feature allows you to play a video again from the beginning after the video playback ends. Sample code:

fAliplayer.setLoop(true);

The onInfo callback is returned when loop playback starts. Sample code:

fAliplayer.setOnInfo((infoCode, extraValue, extraMsg, playerId) {
      if(infoCode == FlutterAvpdef.LOOPINGSTART){
        // Notifies users when the loop playback starts.
      }
});

Advanced features

Enable list playback for short videos

  1. Create a list player.

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

    The list player can play videos only based on URLs or STS tokens.

    // uid 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 reduces the startup time. Sample code:

    // Specify the number of videos that you want to preload. The total number of loaded videos equals one plus twice the specified number. 
    fAliListPlayer.setPreloadCount(count);
  4. Play the video source.

    // The uid parameter is required. You only need to specify the UID for URL-based playback. You need to specify the UID and STS information for STS-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 the hardware decoding feature. By default, the hardware decoding feature 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) or DASH video streams. After the prepare method is called, call getMediaInfo to obtain the bitrate information that is indicated by TrackInfo. Sample code:

fAliplayer.getMediaInfo().then((value) {
// Valid value: 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 to the required bitrate.
fAliplayer.selectTrack(index);
// Enable adaptive bitrate streaming.
fAliplayer.selectTrack(-1);

Capture snapshots

ApsaraVideo Player SDK for Flutter provides setOnSnapShot for 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);

Configure video preview

ApsaraVideo Player SDK for Flutter supports the video preview feature based on ApsaraVideo VOD. Only videos played based on VidAuth or VidSts can be previewed. We recommend that you play videos based on VidAuth. 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 indicates 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 temporary AccessKey secret",
                securityToken: "Enter the security token."
        previewTime: "Enter the preview duration. Unit: seconds.");

Confgure 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. You can specify the latency only for live streams.
  mNetworkTimeout: _mNetworkTimeoutController.text,// The network timeout period. Unit: milliseconds.
  mNetworkRetryCount:_mNetworkRetryCountController.text,// The number of retires after a network timeout. Unit: milliseconds.
  'mMaxProbeSize': _mMaxProbeSizeController.text,// Specify the maximum probe size.
  'mReferrer': _mReferrerController.text,// Specify the Referer.
  'mHttpProxy': _mHttpProxyController.text,// Specify the HTTP proxy.
  'mEnableSEI': mEnableSEI,// Specify whether to use supplemental enhancement information (SEI).
  'mClearFrameWhenStop': !mShowFrameWhenStop,// Specify whether to clear the screen when the playback stops.
  'mDisableVideo': mDisableVideo,// Specify whether to disable video.
  'mDisableAudio': mDisableAudio// Specify whether to disable audio.
  'mUserAgent':mUserAgent,// Specify User-Agent.
};
// Configure the application.
fAliplayer.setConfig(configMap);

Configure the performance

Configure local caching

ApsaraVideo Player SDK for Flutter allows you to cache videos during playback. This saves your traffic during loop playback. To configure the play-and-cache feature, call setCacheConfig before you call the prepare method. Sample code:

var map = {
  "mMaxSizeMB": _mMaxSizeMBController.text,// The maximum space that can be occupied by the cache directory.
  "mMaxDurationS": _mMaxDurationSController.text,// The maximum duration of a single cached file.
  "mDir": _mDirController.text,// The cache directory.
  "mEnable": mEnableCacheConfig,// Specify whether to enable the cache feature.
};
fAliplayer.setCacheConfig(map);

Configure video download

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

  • Normal download

    Videos that are downloaded in the 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. You can only use ApsaraVideo Player SDK to play these videos.

Usage notes

  • You can download only 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 Secure download.

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

    FlutterAliPlayerFactory.initService(byteData);
  2. Create and set 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
      // Parameter description: Valid values of the type parameter include FlutterAvpdef.DOWNLOADTYPE_STS and FlutterAvpdef.DOWNLOADTYPE_AUTH. If type is set to DOWNLOADTYPE_STS, the required parameters are {vid,accessKeyId,accessKeySecret,securityToken}. If type is set to DOWNLOADTYPE_AUTH, the required parameters are {vid,playAuth}.
      downloader.prepare(type, vid).then((value) {
          // Valid value: map. This value corresponds to the custom download class DownloadModel in the demo.
          DownloadModel downloadModel = DownloadModel.fromJson(value);
          // 2. selectItem indicates the resolution of videos that you want to download based on trackInfo.
          List<TrackInfoModel> trackInfos = downloadModel.trackInfos;
          downloader.selectItem(vid,trackInfos[0].index);
          //3.start
          downloader.start(vid, trackInfos[0].index).listen((event) {
            // Note: event may contain various information. For more information, see FlutterAvpdef.EventChanneldef. The following code provides the details:
            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)

Play encrypted videos

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