This topic provides sample code to show you how to use ApsaraVideo Player SDK for Flutter.


This section describes how to use ApsaraVideo Player SDK for Flutter:

  1. Create a player.
    FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer();

    Create multiple instances of the player.

    You need to manage the playerId at the Flutter layer. The playerId is returned during the callback and is used to notify the Flutter layer.
    FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer(playerId: playerId);
  2. Set listeners.
    The following code block shows some listener operations:
    // Calls the listener when preparation is complete.
    fAliplayer.setOnPrepard((playerId) {});
    // Calls the listener when the first frame is rendered.
    fAliplayer.setOnRenderingStart((playerId) {});
    // Calls the listener when the width or height of the video is changed.
    fAliplayer.setOnVideoSizeChanged((width, height,playerId) {});
    // Calls the listener when player status is changed.
    fAliplayer.setOnStateChanged((newState,playerId) {});
    // Calls the listener at different stages of loading.
        loadingBegin: (playerId) {},
        loadingProgress: (percent, netSpeed,playerId) {},
        loadingEnd: (playerId) {});
    // Calls the listener when seek is complete.
    fAliplayer.setOnSeekComplete((playerId) {});
    // Calls the listener when player events occur, including the buffer and current playback progress. You can obtain the FlutterAvpdef.infoCode information from the infoCode.
    fAliplayer.setOnInfo((infoCode, extraValue, extraMsg,playerId) {});
    // Calls the listener when playback completes.
    fAliplayer.setOnCompletion((playerId) {});
    // Calls the listener when a stream is ready.
    fAliplayer.setOnTrackReady((playerId) {});
    // Calls the listener when a snapshot is taken.
    fAliplayer.setOnSnapShot((path,playerId) {});
    // Calls the listener when an error occurs.
    fAliplayer.setOnError((errorCode, errorExtra, errorMsg,playerId) {});
    // Calls the listener when the stream is switched.
    fAliplayer.setOnTrackChanged((value,playerId) {});
  3. Set the render view.
    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: [
                    child: aliPlayerView,
                    width: width,
                    height: height),
  4. Set the playback source.
    void onViewPlayerCreated(viewId) async {
      // Sets the render view for the player.
      // Sets the playback source.
      switch (_playMode) {
        // The URL playback mode.
        case ModeType.URL:
        // The STS playback mode.
        case ModeType.STS:
              vid: _dataSourceMap[DataSourceRelated.VID_KEY],
              region: _dataSourceMap[DataSourceRelated.REGION_KEY],
              accessKeyId: _dataSourceMap[DataSourceRelated.ACCESSKEYID_KEY],
              securityToken: _dataSourceMap[DataSourceRelated.SECURITYTOKEN_KEY],
              definitionList: _dataSourceMap[DataSourceRelated.DEFINITION_LIST],
              previewTime: _dataSourceMap[DataSourceRelated.PREVIEWTIME_KEY]);
        // The AUTH playback mode.
        case ModeType.AUTH:
              vid: _dataSourceMap[DataSourceRelated.VID_KEY],
              region: _dataSourceMap[DataSourceRelated.REGION_KEY],
              playAuth: _dataSourceMap[DataSourceRelated.PLAYAUTH_KEY],
              definitionList: _dataSourceMap[DataSourceRelated.DEFINITION_LIST],
              previewTime: _dataSourceMap[DataSourceRelated.PREVIEWTIME_KEY]);
  5. Set the autoplay feature.
    Note If you enable the autoplay feature, you can call the prepare() method to play videos automatically.

    If the autoplay feature is not enabled, you need to call the method to start playback when the setOnPrepard() listener is called.

  6. Pause the playback.

    After the playback is paused, you can call the play() method to resume the playback.

  7. Stop the playback.

    After the playback is stopped, you need to call the prepare() method and the play() method again to resume the playback.

  8. Destroy the playback.
  9. Specify the seek pointer.
    // Valid values of seekMode: FlutterAvpdef.ACCURATE (accurate seek) and FlutterAvpdef.INACCURATE (inaccurate seek).,seekMode);
  10. Set the loop playback feature.
  11. Set the mute mode and volume control.
    // Sets the player volume. Value range: 0 to 1.
  12. Set the playback speed.
    // Valid values: 0.5,1.0,1.5, and 2.0.
  13. Set variable bitrate switching and automatic bitrate switching.
    After the player is prepared, you can call the getMediaInfo method to obtain the value of the TrackInfo parameter. The TrackInfo parameter returns the bitrate information.
    fAliplayer.getMediaInfo().then((value) {
       // The value is map. You can use value['tracks'] to obtain the TrackInfos list information. 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 switch the bitrate. The parameter is trackIndex in TrackInfo. The switching result will be called back after OnTrackChangedListener is called.
    // Automatically switches the bitrate.
  14. Set video image rotation, scaling, and mirroring.
    // Sets the mirroring mode: horizontal mirroring, vertical mirroring, and no mirroring. 
    // Sets the rotation angel: 0°, 90°, 180°, and 270°.
    // Sets the scaling mode: aspect ratio-based padding, aspect ratio-based fitting, and stretching.
  15. Set the play-and-cache feature.

    You need to set this feature before the player is prepared.

    var map = {
      "mMaxSizeMB": _mMaxSizeMBController.text,/// The maximum size of the cache directory.
      "mMaxDurationS": _mMaxDurationSController.text,/// The maximum duration of a single cached file.
      "mDir": _mDirController.text,/// The cache directory.
      "mEnable": mEnableCacheConfig,/// Whether to enable the cache feature.
  16. Configure other settings for the player.

    You must set these features for the player before you call the prepare() method.

    var configMap = {
      'mStartBufferDuration':_mStartBufferDurationController.text,/// The loading duration before playback.
      'mHighBufferDuratio':_mHighBufferDurationController.text,/// The peak buffer duration.
      'mStartBufferDuration':_mStartBufferDurationController.text,/// The maximum buffer duration.
      'mMaxDelayTime': _mMaxDelayTimeController.text,/// The maximum delay. Note: This parameter is valid only for live streaming.
      'mNetworkTimeout': _mNetworkTimeoutController.text,/// The network timeout period.
      'mNetworkRetryCount':_mNetworkRetryCountController.text,/// The number of retries to perform when a timeout occurs.
      'mMaxProbeSize': _mMaxProbeSizeController.text,/// The maximum size of the probe.
      'mReferrer': _mReferrerController.text,///referrer
      'mHttpProxy': _mHttpProxyController.text,/// The HTTP proxy.
      'mEnableSEI': mEnableSEI,/// Whether to enable the use of supplemental enhancement information (SEI).
      'mClearFrameWhenStop': !mShowFrameWhenStop,/// Whether to clear video frames after the video playback stops.
      'mDisableVideo': mDisableVideo,/// Whether to disable video.
      'mDisableAudio': mDisableAudio/// Whether to disable audio.

List playback

  1. Create a list player.
    FlutterAliListPlayer fAliListPlayer = FlutterAliPlayerFactory.createAliListPlayer();
  2. Add and remove resources.

    The list player supports only two playback modes: URL and STS.

    // The uid parameter indicates the unique ID of a video, which is used to differentiate videos. Videos with the same unique ID are considered the same.
  3. Set the number of videos to be preloaded.
    You can significantly reduce the startup loading time by setting the number of videos to be preloaded to an appropriate value. The following code provides an example:
    // Sets the number of videos to be preloaded. The total number of loaded videos equals 1 plus twice the specified number. 
  4. Set the playback source.
    // The uid parameter is required. If the video is in URL playback mode, only the uid parameter is required. If the video is in STS playback mode, you also need to enter the STS information.

Video download

ApsaraVideo Player SDK for Flutter allows you to download videos from ApsaraVideo VOD by using VidSts and VidAuth. ApsaraVideo VOD supports the secure download mode and the normal download mode. You can set a download mode in the ApsaraVideo VOD console.

  1. Create and set a video downloader.
    FlutterAliDownloader donwloader = FlutterAliDownloader.init();
    /// Sets the save path.
    ApsaraVideo Player SDK for Flutter allows you to download videos that are encrypted by using Alibaba Cloud proprietary encryption. For security reasons, you must configure a security file for encryption verification in the SDK.
  2. Start the download.
    After you call the start method, listeners are automatically set and a callback message is returned. The following code provides an example:
      /// Parameter description: Valid values of type are FlutterAvpdef.DOWNLOADTYPE_STS and FlutterAvpdef.DOWNLOADTYPE_AUTH. When type is DOWNLOADTYPE_STS, Descriptionthe required parameters are {vid,accessKeyId,accessKeySecret,securityToken}. When type is DOWNLOADTYPE_AUTH, the required parameters are {vid,playAuth}.
      downloader.prepare(type, vid).then((value) {
          // The value is map, which corresponds to the custom download class DownloadModel in the demo.
          DownloadModel downloadModel = DownloadModel.fromJson(value);
          // 2.selectItem. This parameter determines the quality of videos to download.
          List<TrackInfoModel> trackInfos = downloadModel.trackInfos;
          downloader.start(vid, trackInfos[0].index).listen((event) {
            // Note: event may contain a variety of information. You can refer to information in FlutterAvpdef.EventChanneldef. The following provides details:
            if (event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_PROGRESS){
                // Indicates the percentage of the download progress. You can use event[EventChanneldef.DOWNLOAD_PROGRESS] to obtain the percentage of the download progress.
            }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_PROCESS){
                // Indicates progress in percentage. You can use event[EventChanneldef.DOWNLOAD_PROCESS] to obtain the percentage of the processing progress.
            }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 vid and index. vid and index are used to determine which video has been downloaded. You can use event['savePath'] to obtain the local path of downloaded videos.
            }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_ERROR){
                // Indicates download failed. You can use event['vid'] and event['index'] to obtain vid and index. vid and index are used to determine which video failed to download. 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 the downloaded content.
    When the delete process is complete, the downloaded file is deleted. The following code provides an example:
    downloader.delete(vid, index)
  5. Release a downloaded object.
    When you no longer need a downloaded object, you can call the release method to release it to prevent memory leaks. The following code provides an example:
    downloader.release(vid, index)