This topic provides examples of how to use the basic features of the ApsaraVideo Player SDK for Flutter. For more information, see Advanced features and API reference.
Set the data source (DataSource)
The ApsaraVideo Player SDK for Flutter supports four playback methods for video-on-demand (VOD): VidAuth (recommended), VidSts, UrlSource, and encrypted playback.
The ApsaraVideo Player SDK for Flutter supports only one playback method for live streaming: UrlSource.
VOD playback
VOD playback using VidAuth (Recommended)
To play a VOD video using VidAuth, set the `vid` property of the player to the audio or video ID and the `playauth` property to the playback credential.
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.
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. The PlayAuth method is more secure and easier to use than the STS method. 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, you must use a temporary Security Token Service (STS) credential instead of a VOD playback credential. You must 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 the `setUrl` property of the player to the playback URL. The playback 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 the need for self-signing. For an example of how to call this operation, 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.
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
The ApsaraVideo Player SDK for Flutter supports common operations such as starting, pausing, and seeking to a specific time.
Autoplay
You can use the setAutoPlay method to enable autoplay for videos. Autoplay is disabled by default. The following code provides an example:
fAliplayer.setAutoPlay(true);Prepare for playback
You can call the prepare method to start reading and parsing data for video playback. If autoplay is enabled, the video automatically starts playing after the data is parsed. The following code provides an example:
fAliplayer.prepare();Start playback
You can use the play method to start video playback. The following code provides an example:
fAliplayer.play();Start playback from a specific time
You can use the seek method to jump to a specific time for playback. This is useful for scenarios such as dragging the progress bar or resuming playback from a specific point. The following code provides an 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, you must call this method once before you call the prepare method. The following code provides an 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
You can use the pause method to pause video playback. The following code provides an example:
fAliplayer.pause();Resume playback
You can use the play method to resume video playback. The following code provides an example:
fAliplayer.play();Stop playback
You can use the stop method to stop video playback. The following code provides an example:
fAliplayer.stop();Destroy the player
You can destroy the player instance synchronously or asynchronously. The following code provides an example:
// Synchronous destruction. The stop method is automatically called internally.
fAliplayer.destroy();
// Asynchronous destruction. The stop method is automatically called internally.
fAliplayer.releaseAsync();The synchronous destruction method returns a value only after all player resources are released. If your UI requires high responsiveness, we recommend that you use the asynchronous destruction method. Note the following points:
Avoid performing any other operations on the player object during asynchronous destruction.
You do not need to manually stop the player before you call the asynchronous destruction method because the method includes an asynchronous stop procedure.
Listen for player status
The 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.
For manual playback, you must set the
OnPreparedlistener. This is because you need to call theplaymethod in theOnPreparedcallback to start playback.The
OnTrackReadyandOnErrorlisteners are important. We recommend that you set them.
The following example shows only 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
You can listen for changes in the player status. The `onStateChanged` callback provides the current status of the player. The following code provides an 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
The 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. You can use the setScalingMode method to set the fill mode. The following code provides an 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
You can use the setRotateMode method to rotate the video by a specified angle. After you set the rotation, you can also retrieve the rotation angle. The following code provides an 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. Call the setMirrorMode method to configure the mirror mode. The following code provides an 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
You can use the ApsaraVideo Player SDK for Flutter to obtain the current playback progress and video duration.
Obtain the current playback progress
You can obtain the current playback time in milliseconds from the `onInfo` callback. The following code provides an example:
fAliplayer.setOnInfo((infoCode,extraValue,extraMsg,playerId){
if(infoCode==FlutterAvpdef.CURRENTPOSITION){
// extraValue is the current playback progress.
}
});Obtain the video duration
You can obtain the total duration of the video after the video is loaded, such as after the `AVPEventPrepareDone` event. The following code provides an example:
fAliplayer.getMediaInfo().then((value){
_videoDuration=value['duration'];
});Set the volume
Volume settings include volume adjustment and muting.
Volume adjustment
You can adjust the volume using the setVolume method. The supported value range is 0 to 2. Setting the volume to a value greater than 1 is not recommended because it may cause noise. After setting the volume, you can also retrieve the volume information. The following code provides an example:
// The value of volume is a real number from 0 to 2.
fAliPlayer.setVolume(1);
// Get the volume information.
fAliPlayer.getVolume();Mute settings
You can use the setMute method to mute the playing video. The following code provides an example:
fAliplayer.setMute(true);Change the playback speed
The ApsaraVideo Player SDK for Flutter lets you change the video playback speed. You can use the setSpeed method to play the video at 0.5× to 5× the normal speed. The pitch of the audio remains unchanged. The following code provides an 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 (recommended) or VidSts) for playback, no extra settings are required. The ApsaraVideo Player SDK for Flutter obtains the definition list from ApsaraVideo VOD. The SDK lets you retrieve and switch the definition. This setting is not supported for the UrlSource playback method.
Retrieve the definition
After the video is loaded, you can 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
The ApsaraVideo Player SDK for Flutter provides a loop playback feature. Call setLoop to enable loop playback. After the video finishes playing, it automatically restarts from the beginning. The following code provides an example:
fAliplayer.setLoop(true);The loop start callback also sends notifications through onInfo. The following is an example:
fAliplayer.setOnInfo((infoCode, extraValue, extraMsg, playerId) {
if(infoCode == FlutterAvpdef.LOOPINGSTART){
// Loop playback start notification
}
});Get playback logs
The ApsaraVideo Player SDK for Flutter lets you obtain playback logs. Call enableConsoleLog to enable log printing. The following code provides an 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);The ApsaraVideo Player SDK for Flutter lets you obtain frame-level logs. Call `setLogOption` to configure frame-level log printing. The following code provides an 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);The frame-level log feature is mainly used for troubleshooting.