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.
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.
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 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);
Configure listeners.
You can configure multiple listeners for your player.
You must configure
OnPrepard
because you need to call theplay
method in theOnPrepard
callback to start manual playback.We recommend that you configure
OnTrackReady
andOnError
.
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) {});
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 to play an on-demand video, 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 streaming 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 Security Token Service (STS)-based playback, 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); // Call the createVidPlayerConfigGenerator and setPreviewTime methods. FlutterAliplayer.createVidPlayerConfigGenerator(); FlutterAliplayer.setPreviewTime(0); // 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 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 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 and setPreviewTime methods. FlutterAliplayer.createVidPlayerConfigGenerator(); FlutterAliplayer.setPreviewTime(0); // 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, 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: } }
Configure the 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), ], ), ); }, );
Optional. Enable the autoplay feature. By default, the autoplay feature is disabled.
fAliplayer.setAutoPlay(true);
Prepare the player.
Call the
prepare()
method to prepare the player.fAliplayer.prepare();
Start the playback.
If the autoplay feature is not enabled, you must call
fAliplayer.play()
in theOnPrepard
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 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 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 a user drags the slider on the progress bar or a 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);
You can call the setStartTime method to set the start time of a video. The configuration take effect only once. This feature is used when you start the playback of a video from a specific point in time. Sample code:
// Start the playback of a video from a specific position. You need to call this method before calling the prepare method. The configuration take effect only once. The time parameter specifies the start time. 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.setStartTime(time, seekMode);
Pause 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();
Destroy the player
You can synchronously or asynchronously destroy the player. Sample code:
// Synchronously destroy the player. The system automatically calls the stop method.
fAliplayer.destroy();
// Asynchronously destroy the player. The system automatically calls the stop method.
fAliplayer.releaseAsync();
The synchronous destroy method returns the result after the player resources are released. If you have high requirements on the response speed of the UI, we recommend that you call the asynchronous destroy method. Usage notes:
Do not perform any other operations on the player object during asynchronous destruction.
The asynchronous destroy method includes an asynchronous stop process. Therefore, you do not need to manually stop the player before calling the asynchronous destroy method.
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.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALEASPECTFIT);
// Scale out the video to fill the view.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALEASPECTFILL);
// Stretch the video to fill the view. If the aspect ratio of the video differs from that of the view, the image may be distorted.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALETOFILL);
Rotate video images
You can call the setRotateMode
method to specify a rotation angle for video images. You can query the rotation angle after it is set. Sample code:
// Does not rotate the video.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_0);
// Rotate the video 90 degrees clockwise.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_90);
// Rotate the video 180 degrees clockwise.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_180);
// Rotate the video 270 degrees clockwise.
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:
// Set no mirroring.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_NONE);
// Mirror the video horizontally.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_HORIZONTAL);
// Mirror the video vertically.
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'];
});
Monitor 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 call the setVolume
method to change the volume of a video to up to twice the original volume. Noise may occur if you set it to a value higher than 1. 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 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 settings
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 definitions 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 users when 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);
ApsaraVideo Player SDK for Flutter allows you to obtain frame-level playback logs. You can call setLogOption to set the printing of frame-level logs. Sample code:
// Configure frame-level log printing.
// Valid values of the value parameter: 0 and 1. A value of 0 indicates disabled. A value of 1 indicates enabled.
FlutterAliplayer.setLogOption(value);
This feature is used in troubleshooting scenarios.