Basic features

Updated at:
Copy as MD

Use the basic features of ApsaraVideo Player SDK for Flutter, including playback control, display settings, volume and speed adjustment, and definition switching. For more information, see Advanced features and API reference.

Set the data source (DataSource)

  • ApsaraVideo Player SDK for Flutter supports four VOD playback methods: VidAuth (recommended), VidSts, UrlSource, and encrypted playback.

  • ApsaraVideo Player SDK for Flutter supports only one live streaming playback method: UrlSource.

VOD playback

VOD playback using VidAuth (Recommended)

To play a VOD video using VidAuth, set `vid` to the audio or video ID and `playauth` to the playback credential.

  1. After an audio or video file is uploaded, you can obtain its ID in the ApsaraVideo VOD console by choosing Media Library > Audio/Video, or by calling the SearchMedia operation.

  2. You can obtain the playback credential by calling the GetVideoPlayAuth operation. We recommend using an SDK to obtain the playback credential to avoid the need for self-signing. For an example of how to call this operation, see Developer Portal.

We recommend that ApsaraVideo VOD users use this playback method. VidAuth is more secure and easier to use than VidSts. For a detailed comparison, see Comparison between the credential-based method and the STS-based method.

void onViewPlayerCreated(viewId) async {
  // Set the rendered view for the player.
  fAliplayer.setPlayerView(viewId);
  // Note: Before you call generatePlayerConfig, you must call createVidPlayerConfigGenerator() and setPreviewTime().
  FlutterAliplayer.createVidPlayerConfigGenerator();
  FlutterAliplayer.setPreviewTime(0);
  // Set the playback source.
  FlutterAliplayer.generatePlayerConfig().then((value) {
      fAliplayer.setVidAuth(
          vid: "Your Vid",// Required. The video ID (VideoId).
          region: "Your Region",// Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
          playAuth: "<yourPlayAuth>",// Required. The playback credential. You must call the GetVideoPlayAuth operation of ApsaraVideo VOD to generate the credential.
          playConfig: value);
        });    
  }
}

VOD playback using VidSts

To play a VOD video using VidSts, use a temporary Security Token Service (STS) credential instead of a VOD playback credential. Obtain the STS token and the temporary AccessKey pair (AccessKeyId and AccessKeySecret) beforehand. For more information, see Obtain an STS token.

void onViewPlayerCreated(viewId) async {
  // Set the rendered view for the player.
  fAliplayer.setPlayerView(viewId);
  // Note: Before you call generatePlayerConfig, you must call createVidPlayerConfigGenerator() and setPreviewTime().
  FlutterAliplayer.createVidPlayerConfigGenerator();
  FlutterAliplayer.setPreviewTime(0);
  // Playback using VidSts.
  FlutterAliplayer.generatePlayerConfig().then((value) {
     fAliplayer.setVidSts(
          vid: "Your Vid",// Required. The video ID (VideoId).
          region: "Your Region",// Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
          accessKeyId: "<yourAccessKeyId>",// Required. The AccessKey ID of the temporary AccessKey pair. You must call the AssumeRole operation of STS to generate the AccessKey ID.
          accessKeySecret: "<yourAccessKeySecret>",// Required. The AccessKey secret of the temporary AccessKey pair. You must call the AssumeRole operation of STS to generate the AccessKey secret.
          securityToken: "<yourSecurityToken>",// Required. The STS token. You must call the AssumeRole operation of STS to generate the token.
      	  playConfig: value);
    	});
       
}

VOD playback using UrlSource

To play a VOD video using UrlSource, set `setUrl` to the playback URL. The URL can be a third-party URL or a playback URL from ApsaraVideo VOD.

You can obtain an Alibaba Cloud playback URL by calling the GetPlayInfo operation. We recommend using an SDK to obtain the playback URL to avoid self-signing. For an example, see Developer Portal.

void onViewPlayerCreated(viewId) async {
  // Set the rendered view for the player.
  fAliplayer.setPlayerView(viewId);
  // Set the playback source.
  switch (_playMode) {
      // Playback using UrlSource.
    case ModeType.URL:
      this.fAliplayer.setUrl("Playback URL"); // Required. The playback URL. The URL can be a third-party VOD URL or a playback URL from ApsaraVideo VOD.
      break;
    default:
  }
}

Encrypted VOD playback

ApsaraVideo VOD supports HLS encryption, Alibaba Cloud proprietary cryptography, and DRM encryption. For more information about encrypted playback, see Play encrypted videos on Flutter.

Live stream playback

For more information, see ApsaraVideo Player for Flutter.

Note
  • UrlSource uses a URL for playback. VidSts and VidAuth use a video ID (VID) for playback.

  • For more information about how to set the region, see VOD regions.

Control playback

ApsaraVideo Player SDK for Flutter supports common operations such as starting, pausing, and seeking to a specific time.

Autoplay

Use the setAutoPlay method to enable autoplay. Autoplay is disabled by default. Example:

fAliplayer.setAutoPlay(true);

Prepare for playback

Call the prepare method to start reading and parsing data for playback. If autoplay is enabled, the video plays automatically after the data is parsed. Example:

fAliplayer.prepare();

Start playback

Use the play method to start playback. Example:

 fAliplayer.play();

Start playback from a specific time

Use the seek method to jump to a specific time. This is useful for progress bar dragging or resuming playback from a saved position. Example:

// position is the specified time in milliseconds. Valid values for seekMode: FlutterAvpdef.ACCURATE (accurate seek) and FlutterAvpdef.INACCURATE (inaccurate seek).
fAliplayer.seek(position,seekMode);

To start playback from a specific position, call this method before calling prepare. Example:

// Set the start time in milliseconds for the next player preparation. This setting is valid only for the immediately following prepare call.
// After prepare is called, this value is automatically reset to zero. If this method is not called again before the next prepare, playback starts normally.
// You can set seekMode to accurate or inaccurate mode.
fAliplayer.setStartTime(time, seekMode);

Pause playback

Use the pause method to pause playback. Example:

fAliplayer.pause();

Resume playback

Use the play method to resume playback. Example:

fAliplayer.play();

Stop playback

Use the stop method to stop playback. Example:

fAliplayer.stop();

Destroy the player

Destroy the player instance synchronously or asynchronously. Example:

// Synchronous destruction. The stop method is automatically called internally.
fAliplayer.destroy();
// Asynchronous destruction. The stop method is automatically called internally.
fAliplayer.releaseAsync();
Note

Synchronous destruction returns only after all player resources are released. For better UI responsiveness, use asynchronous destruction. Note the following points:

  1. Do not perform any other operations on the player object during asynchronous destruction.

  2. You do not need to manually stop the player before calling the asynchronous destruction method because it includes an asynchronous stop procedure.

Listen for player status

ApsaraVideo Player SDK for Flutter lets you set player listeners to monitor the player status.

Set player listeners

You can set multiple listeners for the player.

  1. For manual playback, you must set the OnPrepared listener. This is because you need to call the play method in the OnPrepared callback to start playback.

  2. The OnTrackReady and OnError listeners are important. We recommend that you set them.

The following example shows some of the available listeners:

// Preparation is successful.
fAliplayer.setOnPrepard((playerId) {});
// The first frame is displayed.
fAliplayer.setOnRenderingStart((playerId) {});
// The video width and height change.
fAliplayer.setOnVideoSizeChanged((width, height,playerId) {});
// The player status changes.
fAliplayer.setOnStateChanged((newState,playerId) {});
// Loading status.
fAliplayer.setOnLoadingStatusListener(
    loadingBegin: (playerId) {},
    loadingProgress: (percent, netSpeed,playerId) {},
    loadingEnd: (playerId) {});
// Seeking is complete.
fAliplayer.setOnSeekComplete((playerId) {});
// Callback for player event information, including buffer and current playback progress. The information is determined by infoCode, which corresponds to FlutterAvpdef.infoCode.
fAliplayer.setOnInfo((infoCode, extraValue, extraMsg,playerId) {});
// Playback is complete.
fAliplayer.setOnCompletion((playerId) {});
// The stream is ready.
fAliplayer.setOnTrackReady((playerId) {});
// Snapshot result.
fAliplayer.setOnSnapShot((path,playerId) {});
// Error result.
fAliplayer.setOnError((errorCode, errorExtra, errorMsg,playerId) {});
// The stream is switched.
fAliplayer.setOnTrackChanged((value,playerId) {});

Listen for playback status

Listen for changes in the player status. The `onStateChanged` callback provides the current status. Example:

fAliplayer.setOnStateChanged((newState, playerId) {
  // newState is the playback status.
  switch (newState) {
    case FlutterAvpdef.AVPStatus_AVPStatusIdle: // Idle
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusInitialzed: // Initialization is complete.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusPrepared: // Preparation is complete.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusStarted: // Playing.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusPaused: // Paused.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusStopped: // Stopped.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusCompletion: // Playback is complete.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusError: // An error occurred.
      break;
    default:
  }
});

Set the display mode

ApsaraVideo Player SDK for Flutter supports display settings such as fill, rotation, and mirroring.

Fill

The SDK supports three fill modes: aspect fit, aspect fill, and scale to fill. Use the setScalingMode method to set the fill mode. Example:

// Set the mode to aspect fit. The video is scaled down proportionally to fit within the view without distortion.
fAliplayer.setScalingMode(ScaleMode.SCALE_ASPECT_FIT);
// Set the mode to aspect fill. The video is scaled up proportionally to fill the view without distortion.
fAliplayer.setScalingMode(ScaleMode.SCALE_ASPECT_FILL);
// Set the mode to scale to fill. The video may be distorted if its aspect ratio does not match the view's aspect ratio.
fAliplayer.setScalingMode(ScaleMode.SCALE_TO_FILL);

Rotation

Use the setRotateMode method to rotate the video by a specified angle. You can also retrieve the rotation angle after setting it. Example:

// Rotate the video 0 degrees clockwise.
fAliplayer.setRotateMode(RotateMode.ROTATE_0);
// Rotate the video 90 degrees clockwise.
fAliplayer.setRotateMode(RotateMode.ROTATE_90);
// Rotate the video 180 degrees clockwise.
fAliplayer.setRotateMode(RotateMode.ROTATE_180);
// Rotate the video 270 degrees clockwise.
fAliplayer.setRotateMode(RotateMode.ROTATE_270);
// Get the rotation angle.
fAliplayer.getRotateMode();

Mirroring

The SDK supports horizontal mirroring, vertical mirroring, and no mirroring. Use the setMirrorMode method to configure mirroring. Example:

// Set no mirroring.
fAliplayer.setMirrorMode(MirrorMode.MIRROR_MODE_NONE);
// Set horizontal mirroring.
fAliplayer.setMirrorMode(MirrorMode.MIRROR_MODE_HORIZONTAL);
// Set vertical mirroring.
fAliplayer.setMirrorMode(MirrorMode.MIRROR_MODE_VERTICAL);

Get playback information

Retrieve the current playback progress and video duration using ApsaraVideo Player SDK for Flutter.

Obtain the current playback progress

Obtain the current playback time in milliseconds from the `onInfo` callback. Example:

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

Obtain the video duration

Obtain the total video duration after the video is loaded, such as after the `AVPEventPrepareDone` event. Example:

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

Set the volume

Volume settings include volume adjustment and muting.

Volume adjustment

Adjust the volume using the setVolume method. The supported range is 0 to 2. Values greater than 1 are not recommended because they may cause noise. Example:

// The value of volume is a real number from 0 to 2.
fAliPlayer.setVolume(1);
// Get the volume information.
fAliPlayer.getVolume();

Mute settings

Use the setMute method to mute the player. Example:

fAliplayer.setMute(true);

Change the playback speed

ApsaraVideo Player SDK for Flutter lets you change the playback speed. Use the setSpeed method to play at 0.5x to 5x the normal speed. The audio pitch remains unchanged. Example:

// Set the playback speed. Speeds from 0.5x to 5x are supported. The speed is usually set in multiples of 0.5, such as 0.5x, 1x, and 1.5x.
fAliplayer.setSpeed(1.0);

Multi-definition settings

If you use a VID-based method (VidAuth or VidSts) for playback, no extra settings are required. The SDK retrieves the definition list from ApsaraVideo VOD automatically. You can retrieve and switch definitions. This setting is not supported for UrlSource playback.

Retrieve the definition

After the video is loaded, retrieve the video definition.

fAliplayer.setOnPrepared((playerId) {
  fAliplayer.getMediaInfo().then((value){
        AVPMediaInfoinfo info=AVPMediaInfo.fromJson(value);
        info.tracks.forEach((element){
          if(element.trackType==3){
            // Definition
            String definition=element.trackDefinition;
            // Stream index
            int index=element.trackIndex;
          }
        });
      });    
});

Switch the definition

Use the selectTrack method to switch the definition. Pass the index of the corresponding TrackInfo.

fAliplayer.selectTrack(trackIdx);

Definition switch notification

This callback is triggered after a successful definition switch.

fAliplayer.setOnTrackChanged((value,playerId){
 // A callback indicates that the switch is successful. A method for a failed switch is not yet available.
});

Loop playback

ApsaraVideo Player SDK for Flutter provides loop playback. Call setLoop to enable loop playback. After the video finishes, it automatically restarts from the beginning. Example:

fAliplayer.setLoop(true);

The loop start callback sends notifications through onInfo. Example:

fAliplayer.setOnInfo((infoCode, extraValue, extraMsg, playerId) {
 if(infoCode == FlutterAvpdef.LOOPINGSTART){
 // Loop playback start notification
 }
});

Get playback logs

ApsaraVideo Player SDK for Flutter lets you obtain playback logs. Call enableConsoleLog to enable log printing. Example:

// Enable log printing.
FlutterAliplayer.enableConsoleLog(true);
// Set the log level. The default level is AF_LOG_LEVEL_INFO. To troubleshoot issues, you can set it to AF_LOG_LEVEL_TRACE.
FlutterAliplayer.setLogLevel(FlutterAvpdef.AF_LOG_LEVEL_INFO);

ApsaraVideo Player SDK for Flutter lets you obtain frame-level logs. Call `setLogOption` to configure frame-level log printing. Example:

/// Set the log level. To troubleshoot issues, set the log level to AF_LOG_LEVEL_TRACE.
FlutterAliplayer.setLogLevel(LogLevel.AF_LOG_LEVEL_INFO);
/// Enable or disable logs.
FlutterAliplayer.enableConsoleLog(true);
/// Log callback information.
FlutterAliplayer.setLogInfoCallBack((level, msg) {
   print("[LOG][LEVEL][$level] $msg");
});
/// Enable the frame log callback. This is typically enabled for troubleshooting.
/// Option value: 0 means disabled, 1 means enabled.
FlutterAliplayer.setLogOption(value);
Note

The frame-level log feature is mainly used for troubleshooting.