All Products
Search
Document Center

:Basic features

更新時間:Nov 05, 2024

This topic describes the basic features of ApsaraVideo Player SDK for Flutter. This topic also provides examples on how to use the basic features. For more information about the advanced features and API operations of ApsaraVideo Player SDK for Flutter, see the "Advanced features" and "API description" topics.

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 Real-Time Streaming (RTS) SDK 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 RTS SDK.

  1. Create a player.

    Create a player instance.

    // Create a player instance.
    FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer();
    // We recommend that you specify the traceID parameter. 
    fAliplayer.setTraceID("traceID");

    Create multiple player instances.

    You must specify the playerId parameter when you create a player at the Flutter layer. The playerId parameter that is returned in the player 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 methods 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 state.
    fAliplayer.setOnLoadingStatusListener(
        loadingBegin: (playerId) {},
        loadingProgress: (percent, netSpeed,playerId) {},
        loadingEnd: (playerId) {});
    // The listener for seeking completion.
    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 completion.
    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, and 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 live streaming only based on UrlSource.

    VOD playback

    UrlSource

    If you use the UrlSource method for VOD playback, you must set the setUrl parameter to the streaming URL of an audio or video file. 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

    If you use the VidAuth method for VOD playback, you must set the vid parameter to the ID of the audio or video 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 the VidAuth method for video playback in ApsaraVideo VOD. Compared with VidSts-based playback, VidAuth-based playback is easier to use and more secure. For more information about the comparison 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);
      // Call the createVidPlayerConfigGenerator method.
      FlutterAliplayer.createVidPlayerConfigGenerator();
      // Configure the playback source.
      FlutterAliplayer.generatePlayerConfig().then((value) {
          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);
            });    
      }
    }

    VidSts

    If you use the VidSts method for VOD playback, a temporary Security Token Service (STS) token is used instead of a playback credential. In this case, you must obtain an STS token and an AccessKey pair (AccessKey ID and AccessKey secret) before you play videos on demand. For more information about how to obtain an STS token, see Use STS to upload videos.

    void onViewPlayerCreated(viewId) async {
      // Specify the render view for the player.
      fAliplayer.setPlayerView(viewId);
      // Call the createVidPlayerConfigGenerator method.
      FlutterAliplayer.createVidPlayerConfigGenerator();
      // Specify the VidSts-based playback method.
      FlutterAliplayer.generatePlayerConfig().then((value) {
         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);
        	});
           
    }

    Encrypted playback

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

    UrlSource-based live streaming

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

    The ApsaraVideo Live console provides a URL generator to help you generate live streaming URLs. 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 UI view.

    If the playback source contains video images, 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 disabled, 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();

Control the 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 at a specific point in time.

Start the playback

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

 fAliplayer.play();

Start the playback at a specific point in time

You can call the seek method to play a video at a specific point in time. This feature is used when you drag the slider on the progress bar or the video is resumed from a specific point in time. Sample code:

//// The position parameter specifies the point in time from which playback starts. Unit: milliseconds. Valid values of the seekMode parameter: FlutterAvpdef.ACCURATE and FlutterAvpdef.INACCURATE. A value of FlutterAvpdef.ACCURATE indicates accurate seeking. A value of FlutterAvpdef.INACCURATE indicates 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();

Set the display mode

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

Scale in, scale out, or stretch a video

You can call the setScaleMode method 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. This may change the aspect ratio of the video. If the aspect ratios of the video and the view are different, image distortion may occur.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALETOFILL);

Rotate video images

You can call the setRotateMode method to specify a rotation angle for video images. After you rotate an 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();

Specify a mirroring mode

You can call the setMirrorMode method to specify a mirroring mode. Horizontal mirroring, vertical mirroring, and no mirroring are supported. Sample code:

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

Obtain playback information

ApsaraVideo Player SDK for Flutter allows you to obtain playback information, such as the current playback progress and playback duration.

Obtain the 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 position.
}
});

Obtain the playback duration

You can obtain the total duration of a video. You can obtain the video duration only after the video is loaded. The total video duration is returned in the duration parameter after the AVPEventPrepareDone event is triggered. Sample code:

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

Listen to the playback status

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

fAliplayer.setOnStateChanged((newState, playerId) {
  // The newState parameter indicates the playback status.
  switch (newState) {
    case FlutterAvpdef.AVPStatus_AVPStatusIdle: // The player is idle.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusInitialzed: // The player is initialized.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusPrepared: // The player is prepared.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusStarted: // The playback is in progress.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusPaused: // The playback is paused.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusStopped: // The playback is stopped.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusCompletion: // The playback is complete.
      break;
    case FlutterAvpdef.AVPStatus_AVPStatusError: // The playback failed.
      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 change the volume of a video to up to twice the original volume. If you set the volume to a value higher than 1, noise may occur. We recommend that you do not set the volume to a value higher than 1. You can call the setVolume method to change the volume. You can also obtain the current volume of a video. Sample code:

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

Mute the video

You can call the setMute method to mute a video that is being played. Sample code:

fAliplayer.setMute(true);

Specify the playback speed

ApsaraVideo Player SDK for Flutter allows you to call the setRate method 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 playback

If you use the VidAuth or VidSts method to play a video, you do not need to configure multi-definition playback. We recommend that you use the VidAuth method to play videos. ApsaraVideo Player SDK for Flutter automatically obtains video 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 the definition

After a video is loaded, you can obtain the definition information of the video.

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

Switch between definitions

You can call the selectTrack method to set the TrackInfo parameter to the index that corresponds to the definition to which you want to switch.

fAliplayer.selectTrack(trackIdx);

Configure a callback for successful definition switching

You can configure a callback for successful definition switching.

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

Configure loop playback

ApsaraVideo Player SDK for Flutter supports loop playback. You can call the setLoop method 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 invoked when loop playback starts. Sample code:

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

Obtain playback logs

ApsaraVideo Player SDK for Flutter allows you to obtain playback logs. You can call the enableConsoleLog method to enable log printing. Sample code:

// Enable the log printing feature.
FlutterAliplayer.enableConsoleLog(true);
// Specify the log level. Default value: AF_LOG_LEVEL_INFO. To troubleshoot issues, set this parameter to AF_LOG_LEVEL_TRACE.
FlutterAliplayer.setLogLevel(FlutterAvpdef.AF_LOG_LEVEL_INFO);