This topic describes the frequently used 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 in an easy-to-use way. You can manually play videos or enable autoplay.

  1. Create a player.
    Creates an instance of the player.
    FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer();

    Create multiple instances of the player.

    You must manage the playerId parameter at the Flutter layer. The value of the playerId parameter is returned during the callback to notify the Flutter layer.
    FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer(playerId: playerId);
  2. Configure listeners.
    You can configure multiple listeners for your player.
    • If you manually play videos, you must configure the OnPrepard callback. After the OnPrepard callback is invoked, you can call the play method to manually play a video.
    • We recommend that you configure the following important listeners: OnTrackReady and OnError.
    The following code block shows the methods for specific listeners:
    // Listens to successful preparation.
    fAliplayer.setOnPrepard((playerId) {});
    // Listens to the display of the first frame.
    fAliplayer.setOnRenderingStart((playerId) {});
    // Listens to changes in the width or height of a video.
    fAliplayer.setOnVideoSizeChanged((width, height,playerId) {});
    // Listens to changes of the player status.
    fAliplayer.setOnStateChanged((newState,playerId) {});
    // Listens to the loading status.
    fAliplayer.setOnLoadingStatusListener(
        loadingBegin: (playerId) {},
        loadingProgress: (percent, netSpeed,playerId) {},
        loadingEnd: (playerId) {});
    // Listens to the completion of seeking.
    fAliplayer.setOnSeekComplete((playerId) {});
    // Listens to event callbacks, such as the buffer callback and the playback progress callback. You can obtain event information based on the value of the FlutterAvpdef.infoCode parameter.
    fAliplayer.setOnInfo((infoCode, extraValue, extraMsg,playerId) {});
    // Listens to the completion of playback.
    fAliplayer.setOnCompletion((playerId) {});
    // Listens to a stream that is ready.
    fAliplayer.setOnTrackReady((playerId) {});
    // Listens to a snapshot that is captured.
    fAliplayer.setOnSnapShot((path,playerId) {});
    // Listens to an error.
    fAliplayer.setOnError((errorCode, errorExtra, errorMsg,playerId) {});
    // Listens to stream switching.
    fAliplayer.setOnTrackChanged((value,playerId) {});
  3. Add playback resources.
    • ApsaraVideo Player SDK for Flutter allows you to play on-demand videos based on URLs, playback credentials, Security Token Service (STS) tokens, or ApsaraVideo Media Processing (MPS), and play encrypted on-demand videos. We recommend that you play on-demand videos in ApsaraVideo VOD based on playback credentials.
    • ApsaraVideo Player SDK for Flutter allows you to play live streams only based on URLs.
    Notice Check the key that you entered in the dictionary. Make sure that the key in the dictionary has the same name as the key that you specified in the preceding code. If the keys do not have the same name, ApsaraVideo Player SDK for Flutter may fail to obtain your data.

    Play on-demand videos

    If you play an on-demand video based on the streaming URL, set the setUrl parameter of the player to the streaming URL of the video. The streaming URL can be the URL of a video in ApsaraVideo VOD or on a third-party video-on-demand (VOD) platform. You can call the GetPlayInfo operation to obtain the streaming URL of a video in ApsaraVideo VOD. We recommend that you integrate the server SDK to obtain the URL. This way, you do not need to calculate the signature value. For more information, see GetPlayInfo in OpenAPI Explorer.

    Sample code

    void onViewPlayerCreated(viewId) async {
      // Specify the render view for the player.
      fAliplayer.setPlayerView(viewId);
      // Configure the playback source.
      switch (_playMode) {
        // Specify the URL playback mode.
        case ModeType.URL:
          this.fAliplayer.setUrl("Enter the streaming URL."); // The streaming URL can be a URL in ApsaraVideo VOD or on a third-party VOD platform. 
          break;
        this.fAliplayer.setVidMps(authInfo);
        default:
      }
    }

    If you play an on-demand video based on the video ID and playback credential, set the vid parameter of the player to the video ID and the playauth parameter to the playback credential. To obtain the video ID, you can log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video in the left-side navigation pane. Alternatively, you can call the SearchMedia operation. To obtain the playback credential, you can call the GetVideoPlayAuth operation. We recommend that you integrate the server SDK to obtain the playback credential. This way, you do not need to calculate the signature value. For more information, see GetVideoPlayAuth in OpenAPI Explorer.

    We recommend that you use this playback mode for on-demand videos in ApsaraVideo VOD. Compared with playback based on STS tokens, this playback mode is easier to use and more secure. For more information, see Comparison between credentials and STS.

    Sample code

    void onViewPlayerCreated(viewId) async {
      // Specify the render view for the player.
      fAliplayer.setPlayerView(viewId);
      // Configure the playback source.
      switch (_playMode) {
        // Specify the AUTH playback mode.
        case ModeType.AUTH:
          this.fAliplayer.setVidAuth(
              vid: "Enter the video ID of the resource.",
              region: "Enter the region ID.", // The ID of the region in which the resource resides and ApsaraVideo VOD is activated. The default value is cn-shanghai.
              playAuth: "Enter the playback credential.",
          break;
        this.fAliplayer.setVidMps(authInfo);
        default:
      }
    }

    If you play an on-demand video based on the STS token, you do not need the playback credential. You must obtain the STS token in advance. For more information about how to obtain the STS token, see Create a role and grant temporary access permissions to the role by using STS. If you use this playback mode, set the securityToken parameter of the player to the STS token, the accessKeyId parameter to the temporary AccessKey ID, and the accessKeySecret parameter to the temporary AccessKey secret.

    Sample code

    void onViewPlayerCreated(viewId) async {
      // Specify the render view for the player.
      fAliplayer.setPlayerView(viewId);
      // Configure the playback source.
      switch (_playMode) {
        // Specify the STS playback mode.
        case ModeType.STS:
          this.fAliplayer.setVidSts(
              vid: "Enter the video ID of the resource.",
              region: "Enter the region ID.", // The ID of the region in which the resource resides and ApsaraVideo VOD is activated. The default value is cn-shanghai.
              accessKeyId: "Enter the temporary AccessKey ID generated for the STS token.",
              accessKeySecret: "Enter the temporary AccessKey secret generated for the STS token.",
              securityToken: "Enter the STS token of the resource.",
          break;
        this.fAliplayer.setVidMps(authInfo);
        default:
      }
    }

    Playback based on MPS is tailored for media assets in MPS. If you use this playback mode, you must obtain the following information in advance:

    • vid: the ID of the media asset in MPS.
    • AcessKeyId and AccessKeySecret: the temporary AccessKey ID and AccessKey secret generated for the STS token.
    • SecurityToken: the STS token.
    • domainRegion: the region in which the media asset resides.
    • authInfo: the authorization information.

    For more information about how to obtain the information about a media asset in MPS, see Play videos.

    Sample code

    void onViewPlayerCreated(viewId) async {
      // Specify the render view for the player.
      fAliplayer.setPlayerView(viewId);
      // Configure the playback source.
      switch (_playMode) {
        // Specify the MPS playback mode.
        case ModeType.MPS:
            this.fAliplayer.setVidMps(_dataSourceMap);
                Map<String, dynamic> authInfo = {
                 "vid": "Enter the video ID of the resource.",
                 "region": "Enter the region ID.", // The ID of the region in which the resource resides and ApsaraVideo VOD is activated. The default value is cn-shanghai.
                 "accessKeyId": "Enter the temporary AccessKey ID generated for the STS token.",
                 "accessKeySecret": "Enter the temporary AccessKey secret generated for the STS token.",
                 "playDomain": "Enter the domain name that is used to play the resource.",
                 "authInfo": "Enter the authorization information about the resource.",
                 "hlsUriToken": "Enter the HlsUriToken of the resource.",
                 "securityToken": "Enter the STS token of the resource.",
                    };
        this.fAliplayer.setVidMps(authInfo);
        default:
      }
    }

    ApsaraVideo Player SDK for Flutter allows you to play on-demand videos encrypted based on HTTP-Live-Streaming (HLS) encryption, Alibaba Cloud proprietary cryptography, or digital rights management (DRM) encryption. For more information about how to play encrypted on-demand videos, see Encrypt videos for playback.

    Play live streams based on URLs

    If you play a live stream based on the source URL, set the setUrl parameter to the source URL. The source URL can be the URL of a live stream source in ApsaraVideo Live or on a third-party live streaming platform. You can generate the URL of a live stream source in ApsaraVideo Live 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 URL-based playback mode.
        case ModeType.URL:
          this.fAliplayer.setUrl("Enter the source URL."); // The source URL can be the URL of a live stream source in ApsaraVideo Live or on a third-party live streaming platform. 
          break;
        this.fAliplayer.setVidMps(authInfo);
        default:
      }
    }
  4. Configure the UI view.
    If the playback source contains video images, you must set the UI view to display the video images in the player. The following sample code provides an example:
    @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 autoplay. By default, autoplay is disabled.
    fAliplayer.setAutoPlay(true);
  6. Prepare the playback.
    Call the prepare() method to prepare the playback.
    fAliplayer.prepare();
  7. Start the playback.
    • If you do not enable autoplay, call the fAliplayer.play(); method to start the playback after the OnPrepard callback is invoked.
    • If you enable autoplay, you do not need to call the fAliplayer.play(); method. The video is automatically played after the data about it is parsed.
    fAliplayer.play();

Manage the playback

ApsaraVideo Player SDK for Flutter allows you to manage the playback of a video. For example, you can start or pause the playback, or start the playback at a specified point in time.

Start the playback

You can call the play method to start the playback. The following sample code provides an example:
 fAliplayer.play();

Start the playback at a specified point in time

You can call the seek method to start the playback at 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. The following sample code provides an example:
// Set the position parameter to a point in time. Unit: milliseconds. Valid values of the seekMode parameter: FlutterAvpdef.ACCURATE and FlutterAvpdef.INACCURATE. A value of FlutterAvpdef.ACCURATE indicates precise seeking. A value of FlutterAvpdef.INACCURATE indicates imprecise seeking.
fAliplayer.seek(position,seekMode);

Pause the playback

You can call the pause method to pause the playback. The following sample code provides an example:
fAliplayer.pause();

Stop the playback

You can call the stop method to stop the playback. The following sample code provides an example:
fAliplayer.stop();

Set the video display mode

ApsaraVideo Player SDK for Flutter allows you to set the video display mode, such as image display mode, image rotation mode, and image mirroring mode.

Set the image display mode

ApsaraVideo Player SDK for Flutter supports three image display modes: aspect ratio-based padding, aspect ratio-based fitting, and stretching. You can call the setScalingMode method to set the image display mode. The following sample code provides an example:
// Indicates that the video image is scaled down into the UI view without changing the aspect ratio. This prevents image distortion.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALEASPECTFIT);
// Indicates that the video image is scaled up to fill the UI view without changing the aspect ratio. This prevents image distortion.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALEASPECTFILL);
// Indicates that the video image is stretched to fill the UI view. This may cause image distortion if the video image and the UI view do not match in the aspect ratio.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALETOFILL);

Set the image rotation mode

You can call the setRotateMode method to specify the angle at which the video image is rotated. After you rotate the image, you can also query the rotation angle. The following sample code provides an example:
// Indicates that the rotation angle is 0°, in the clockwise direction.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_0);
// Indicates that the rotation angle is 90°, in the clockwise direction.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_90);
// Indicates that the rotation angle is 180°, in the clockwise direction.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_180);
// Indicates that the rotation angle is 270°, in the clockwise direction.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_270);
// Query the rotation angle.
fAliplayer.getRotateMode();

Set the image mirroring mode

ApsaraVideo Player SDK for Flutter supports three image mirroring modes: no image mirroring, horizontal image mirroring, and vertical image mirroring. You can call the setMirrorMode method to set the image mirroring mode. The following sample code provides an example:
// Indicates no image mirroring.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_NONE);
// Indicates horizontal image mirroring.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_HORIZONTAL);
// Indicates vertical image mirroring.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_VERTICAL);        

Query the playback information

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

Query the playback progress

You can obtain the playback progress from the onInfo callback. The value is returned in milliseconds. The following sample code provides an example:
fAliplayer.setOnInfo((infoCode, extraValue, extraMsg, playerId) {
        if (infoCode == FlutterAvpdef.CURRENTPOSITION) {
            // The extraValue parameter indicates the playback progress.
    }
});

Query the playback duration

You can query the total duration of a video. You can obtain the total duration after the AVPEventPrepareDone event is complete, which means that the video is loaded. The following sample code provides an example:
fAliplayer.getMediaInfo().then((value) {
        _videoDuration = value['duration'];
});

Listen to the playback status

When you listen to the playback status, the playback status is returned after the onStateChanged callback is invoked. The following sample code provides an example:
fAliplayer.setOnStateChanged((newState, playerId) {
    // The playback status is indicated by the newState parameter.
  switch (newState) {
            case FlutterAvpdef.AVPStatus_AVPStatusIdle:        // Indicates that the player is idle.
                    break;
            case FlutterAvpdef.AVPStatus_AVPStatusInitialzed:  // Indicates that the player is initialized.
                    break;
            case FlutterAvpdef.AVPStatus_AVPStatusPrepared:    // Indicates that the player is prepared.
                    break;
            case FlutterAvpdef.AVPStatus_AVPStatusStarted:     // Indicates that the playback is in progress.
                    break;
            case FlutterAvpdef.AVPStatus_AVPStatusPaused:      // Indicates that the playback is paused.
          break;
            case FlutterAvpdef.AVPStatus_AVPStatusStopped:     // Indicates that the playback is stopped.
          break;
            case FlutterAvpdef.AVPStatus_AVPStatusCompletion:  // Indicates that the playback is complete.
          break;
            case FlutterAvpdef.AVPStatus_AVPStatusError:       // Indicates that an error occurs in the playback.
          break;
        default:
    }
});

Set 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 call the setVolume method to change the volume. After you change the volume, you can query the volume information. The following sample code provides an example:
// The value of the volume is a number from 0 to 2. 
fAliPlayer.setVolume(1);
// Query the volume information. 
fAliPlayer.getVolume();

Mute the video

You can call the setMute method to mute a video. The following sample code provides an example:
fAliplayer.setMute(true);

Set the playback speed

ApsaraVideo Player SDK for Flutter allows you to set the playback speed. You can call the setRate method to change the playback speed from 0.5x to 5x. The audio pitch remains unchanged at different speeds. The following sample code provides an example:
// Set the playback speed. You can change the playback speed from 0.5x to 5x. We recommend that you set the playback speed to a multiple of 0.5, such as 0.5x, 1x, or 1.5x.
fAliplayer.setRate(1.0);

Set the definition

If a video is played based on the playback credential or STS token, you do not need to set the definition of the video. We recommend that you play the video based on the playback credential. ApsaraVideo Player SDK for Flutter can obtain a list of available definitions from ApsaraVideo VOD. ApsaraVideo Player SDK for Flutter allows you to query and switch the definition of a video. This feature is not supported for videos played based on URLs.

Query the definition

After you load a video, you can query the definition of the video.
fAliplayer.getMediaInfo().then((value) {
        AVPMediaInfo info = AVPMediaInfo.fromJson(value);
    info.tracks.forEach((element) {
                if(element.trackType == 3){
                // The definition.
              String definition = element.trackDefinition;
            // The index of the streams.
            int index = element.trackIndex;
                }
        }
});

Switch the definition

You can set the trackIdx parameter in the selectTrack method to switch the definition.
fAliplayer.selectTrack(trackIdx);

Configure notifications of definition switching

If the OnTrackChanged callback is invoked, the definition is switched.
fAliplayer.setOnTrackChanged((value, playerId) {
        // If the callback is invoked, the definition is switched. Otherwise, the definition fails to be switched. ApsaraVideo Player SDK for Flutter does not provide a method for you to configure notifications of switching failure.
});

Enable loop playback

ApsaraVideo Player SDK for Flutter supports loop playback. To configure the loop playback feature, call the setLoop method. The loop playback feature allows the player to play a video again when the player plays the video to the end position. The following sample code provides an example:
fAliplayer.setLoop(true);
Loop playback is started after the onInfo callback is invoked. The following sample code provides an example:
fAliplayer.setOnInfo((infoCode, extraValue, extraMsg, playerId) {
      if(infoCode == FlutterAvpdef.LOOPINGSTART){
        // Notifies that 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.
    // The uid parameter specifies the unique ID (UID) 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 set the number of videos to be preloaded based on your business requirements. This way, the startup loading duration can be reduced. The following sample code provides an example:
    // Specify the number of videos that you want to preload. The total number of loaded videos is equal to one plus twice the specified number. 
    fAliListPlayer.setPreloadCount(count);
  4. Play the video source.
    // The uid parameter is required. If you play videos based on URLs, you do not need to set other parameters. If you play videos based on STS tokens, you must enter the STS information.
    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 the setEnableHardwareDecoder method to enable or disable the hardware decoding feature. By default, the hardware decoding feature is enabled. If hardware decoding fails to be initialized, it is switched to software decoding to ensure normal playback. The following sample code provides an example:
// Enable hardware decoding. By default, hardware decoding is enabled.
fAliplayer.setEnableHardwareDecoder(enable);

Switch the video bitrate

ApsaraVideo Player SDK for Flutter supports adaptive bitrate streaming of HLS or DASH video streams. After the player is prepared by using the prepare method, you can call the getMediaInfo method to query the bitrate information, which is indicated by the TrackInfo parameter. The following sample code provides an example:

fAliplayer.getMediaInfo().then((value) {
// The value is of the MAP type. 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 after the OnTrackChangedListener callback is invoked.

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

Capture snapshots

ApsaraVideo Player SDK for Flutter provides the setOnSnapShot method for you to capture snapshots of videos.
// Listens to snapshot capturing.
fAliplayer.setOnSnapShot((path,playerId) {

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

Configure video preview

ApsaraVideo Player SDK for Flutter integrates other configurations of ApsaraVideo VOD to support previews of videos. Only videos played based on playback credentials or STS tokens can be previewed. We recommend that you play videos based on playback credentials. 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 the previewTime parameter in the setVidAuth method to specify the preview duration. The following sample code provides an example:
// The previewTime parameter specifies the preview duration. Unit: seconds.
// The video is played based on the playback credential.
fAliplayer.setVidAuth(
        vid: "Enter the video ID of the resource.",
        region: "Enter the region in which the resource resides.",
        playAuth: "Enter the playback credential of the resource",
        previewTime: "Enter the preview duration. Unit: seconds.");

 // The video is played based on the STS token.
 fAliplayer.setVidSts(
        vid: "Enter the video ID of the resource.",
        region: "Enter the region in which the resource resides.",
        accessKeyId: "Enter the temporary AccessKey ID generated for the STS token.",
                accessKeySecret: "Enter the temporary AccessKey secret generated for the STS token.",
                securityToken: "Enter the STS token of the resource.",
        previewTime: "Enter the preview duration. Unit: seconds.");

Configure other settings

ApsaraVideo Player SDK for Flutter allows you to configure other settings. Before you call the prepare() method, you must set the following parameters for the player to configure these settings:
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,// 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 screen when the playback stops.
  'mDisableVideo': mDisableVideo,// Specifies whether to disable video.
  'mDisableAudio': mDisableAudio,// Specifies whether to disable audio.
  'mUserAgent':mUserAgent,// The 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 the setCacheConfig method before you call the prepare method. The following sample code provides an example:
var map = {
  "mMaxSizeMB": _mMaxSizeMBController.text,// The maximum space that can be occupied by the cache directory.
  "mMaxDurationS": _mMaxDurationSController.text,// The maximum cache duration of a single file.
  "mDir": _mDirController.text,// The cache directory.
  "mEnable": mEnableCacheConfig,// Specifies whether to enable the cache feature.
};
fAliplayer.setCacheConfig(map);

Configure video download

ApsaraVideo Player SDK for Flutter allows you to download videos from ApsaraVideo VOD based on playback credentials or STS tokens. You can download videos in secure download mode or normal download mode. To configure the download mode, log on to the ApsaraVideo VOD console and choose Configuration Management > CDN Configuration > Download in the left-side navigation pane.
  • Normal download

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

  • Secure download

    Videos that are downloaded in secure download mode are encrypted by Alibaba Cloud. You cannot use third-party players to play the downloaded videos. You can play them only by using ApsaraVideo Player SDK.

  1. Create and configure a downloader.
    FlutterAliDownloader donwloader = FlutterAliDownloader.init();
    // Specify the path in which you want to save downloaded videos.
    donwloader.setSaveDir(path)
    ApsaraVideo Player SDK for Flutter allows you to download videos that are encrypted by using Alibaba Cloud proprietary cryptography. For security reasons, you must configure a security file for encryption verification in the SDK.
    FlutterAliPlayerFactory.initService(byteData);
  2. Start the download.
    After you call the method to start the download, listeners are automatically configured and a callback message is returned. The following sample code provides an example:
    ///1.prepare
      // Parameter description: Valid values of the type parameter include FlutterAvpdef.DOWNLOADTYPE_STS and FlutterAvpdef.DOWNLOADTYPE_AUTH. If the type parameter is set to DOWNLOADTYPE_STS, the required parameters are {vid,accessKeyId,accessKeySecret,securityToken}. If the type parameter is set to DOWNLOADTYPE_AUTH, the required parameters are {vid,playAuth}.
      downloader.prepare(type, vid).then((value) {
          // The value is of the MAP type. This value corresponds to the custom download class DownloadModel in the demo.
          DownloadModel downloadModel = DownloadModel.fromJson(value);
          // 2. The selectItem parameter determines the quality of videos that you want to download.
          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 information. You can refer to information in 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){
                // Indicates that the download is complete. You can use event['vid'] and event['index'] to obtain the video ID and index. You can determine the video that is downloaded based on the video ID and index. You can use event['savePath'] to obtain the on-premises path of downloaded videos.
            }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_ERROR){
                // Indicates that the download failed. You can use event['vid'] and event['index'] to obtain the video ID and index. You can determine the video that failed to download based on the video ID and index. You can use event['errorCode'] and event['errorMsg'] to obtain the error code and error message.
            }
          });
      });
  3. Stop the download.
    downloader.stop(vid, index)
  4. Delete a downloaded file.
    When the deletion process is complete, the downloaded file is deleted. The following sample code provides an example:
    downloader.delete(vid, index)
  5. Release a downloaded file.
    If you no longer need a downloaded file, you can call the downloader.release method to release the file to prevent memory leaks. The following sample code provides an example:
    downloader.release(vid, index)

Play encrypted videos

ApsaraVideo Player SDK for Flutter allows you to play on-demand videos encrypted based on HLS encryption, Alibaba Cloud proprietary cryptography, or DRM encryption. For more information, see Encrypt videos for playback.