This topic describes the frequently used features of ApsaraVideo Player SDK for Flutter and provides sample code.
Basic features
Create a player
This section describes how to use ApsaraVideo Player SDK for Flutter to play videos in an easy-to-use way. You can manually play videos or enable autoplay.
Manage the playback
ApsaraVideo Player SDK for Flutter allows you to manage the playback of a video. For example, you can start or pause the playback, or start the playback at a specified point in time.
Start the playback
play
method to start the playback. The following sample code provides an example: fAliplayer.play();
Start the playback at a specified point in time
seek
method to start the playback at a specified point in time. You can use this feature
if you need to drag the process bar of a video or resume the playback. The following
sample code provides an example:// Set the position parameter to a point in time. Unit: milliseconds. Valid values of the seekMode parameter: FlutterAvpdef.ACCURATE and FlutterAvpdef.INACCURATE. A value of FlutterAvpdef.ACCURATE indicates precise seeking. A value of FlutterAvpdef.INACCURATE indicates imprecise seeking.
fAliplayer.seek(position,seekMode);
Pause the playback
pause
method to pause the playback. The following sample code provides an example:fAliplayer.pause();
Stop the playback
stop
method to stop the playback. The following sample code provides an example:fAliplayer.stop();
Set the video display mode
ApsaraVideo Player SDK for Flutter allows you to set the video display mode, such as image display mode, image rotation mode, and image mirroring mode.
Set the image display mode
setScalingMode
method to set the image display mode. The following sample code provides an example:// Indicates that the video image is scaled down into the UI view without changing the aspect ratio. This prevents image distortion.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALEASPECTFIT);
// Indicates that the video image is scaled up to fill the UI view without changing the aspect ratio. This prevents image distortion.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALEASPECTFILL);
// Indicates that the video image is stretched to fill the UI view. This may cause image distortion if the video image and the UI view do not match in the aspect ratio.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALETOFILL);
Set the image rotation mode
setRotateMode
method to specify the angle at which the video image is rotated. After you rotate
the image, you can also query the rotation angle. The following sample code provides
an example:// Indicates that the rotation angle is 0°, in the clockwise direction.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_0);
// Indicates that the rotation angle is 90°, in the clockwise direction.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_90);
// Indicates that the rotation angle is 180°, in the clockwise direction.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_180);
// Indicates that the rotation angle is 270°, in the clockwise direction.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_270);
// Query the rotation angle.
fAliplayer.getRotateMode();
Set the image mirroring mode
setMirrorMode
method to set the image mirroring mode. The following sample code provides an example:// Indicates no image mirroring.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_NONE);
// Indicates horizontal image mirroring.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_HORIZONTAL);
// Indicates vertical image mirroring.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_VERTICAL);
Query the playback information
ApsaraVideo Player SDK for Flutter allows you to query the playback progress and playback duration.
Query the playback progress
fAliplayer.setOnInfo((infoCode, extraValue, extraMsg, playerId) {
if (infoCode == FlutterAvpdef.CURRENTPOSITION) {
// The extraValue parameter indicates the playback progress.
}
});
Query the playback duration
fAliplayer.getMediaInfo().then((value) {
_videoDuration = value['duration'];
});
Listen to the playback status
fAliplayer.setOnStateChanged((newState, playerId) {
// The playback status is indicated by the newState parameter.
switch (newState) {
case FlutterAvpdef.AVPStatus_AVPStatusIdle: // Indicates that the player is idle.
break;
case FlutterAvpdef.AVPStatus_AVPStatusInitialzed: // Indicates that the player is initialized.
break;
case FlutterAvpdef.AVPStatus_AVPStatusPrepared: // Indicates that the player is prepared.
break;
case FlutterAvpdef.AVPStatus_AVPStatusStarted: // Indicates that the playback is in progress.
break;
case FlutterAvpdef.AVPStatus_AVPStatusPaused: // Indicates that the playback is paused.
break;
case FlutterAvpdef.AVPStatus_AVPStatusStopped: // Indicates that the playback is stopped.
break;
case FlutterAvpdef.AVPStatus_AVPStatusCompletion: // Indicates that the playback is complete.
break;
case FlutterAvpdef.AVPStatus_AVPStatusError: // Indicates that an error occurs in the playback.
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
setVolume
method to change the volume. After you change the volume, you can query the volume
information. The following sample code provides an example:// The value of the volume is a number from 0 to 2.
fAliPlayer.setVolume(1);
// Query the volume information.
fAliPlayer.getVolume();
Mute the video
setMute
method to mute a video. The following sample code provides an example:fAliplayer.setMute(true);
Set the playback speed
setRate
method to change the playback speed from 0.5x to 5x. The audio pitch remains unchanged
at different speeds. The following sample code provides an example:// Set the playback speed. You can change the playback speed from 0.5x to 5x. We recommend that you set the playback speed to a multiple of 0.5, such as 0.5x, 1x, or 1.5x.
fAliplayer.setRate(1.0);
Set the definition
If a video is played based on the playback credential or STS token, you do not need to set the definition of the video. We recommend that you play the video based on the playback credential. ApsaraVideo Player SDK for Flutter can obtain a list of available definitions from ApsaraVideo VOD. ApsaraVideo Player SDK for Flutter allows you to query and switch the definition of a video. This feature is not supported for videos played based on URLs.
Query the definition
fAliplayer.getMediaInfo().then((value) {
AVPMediaInfo info = AVPMediaInfo.fromJson(value);
info.tracks.forEach((element) {
if(element.trackType == 3){
// The definition.
String definition = element.trackDefinition;
// The index of the streams.
int index = element.trackIndex;
}
}
});
Switch the definition
selectTrack
method to switch the definition. fAliplayer.selectTrack(trackIdx);
Configure notifications of definition switching
fAliplayer.setOnTrackChanged((value, playerId) {
// If the callback is invoked, the definition is switched. Otherwise, the definition fails to be switched. ApsaraVideo Player SDK for Flutter does not provide a method for you to configure notifications of switching failure.
});
Enable loop playback
setLoop
method. The loop playback feature allows the player to play a video again when the
player plays the video to the end position. The following sample code provides an
example:fAliplayer.setLoop(true);
onInfo
callback is invoked. The following sample code provides an example:fAliplayer.setOnInfo((infoCode, extraValue, extraMsg, playerId) {
if(infoCode == FlutterAvpdef.LOOPINGSTART){
// Notifies that the loop playback starts.
}
});
Advanced features
Enable list playback for short videos
Switch between hardware and software decoding
setEnableHardwareDecoder
method to enable or disable the hardware decoding feature. By default, the hardware
decoding feature is enabled. If hardware decoding fails to be initialized, it is switched
to software decoding to ensure normal playback. The following sample code provides
an example:// Enable hardware decoding. By default, hardware decoding is enabled.
fAliplayer.setEnableHardwareDecoder(enable);
Switch the video bitrate
ApsaraVideo Player SDK for Flutter supports adaptive bitrate streaming of HLS or DASH
video streams. After the player is prepared by using the prepare
method, you can call the getMediaInfo
method to query the bitrate information, which is indicated by the TrackInfo
parameter. The following sample code provides an example:
fAliplayer.getMediaInfo().then((value) {
// The value is of the MAP type. You can use value['tracks'] to obtain information about the TrackInfos list. 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 set the trackIndex
parameter in TrackInfo
to switch the bitrate. The switching result is returned after the OnTrackChangedListener
callback is invoked.
// Switch the bitrate.
fAliplayer.selectTrack(index);
// Enable adaptive bitrate streaming.
fAliplayer.selectTrack(-1);
Capture snapshots
setOnSnapShot
method for you to capture snapshots of videos. // Listens to snapshot capturing.
fAliplayer.setOnSnapShot((path,playerId) {
});
// The captured snapshot. The path parameter indicates the storage path to which the snapshot is stored.
fAliplayer.snapshot(path);
Configure video preview
ApsaraVideo Player SDK for Flutter integrates other configurations of ApsaraVideo VOD to support previews of videos. Only videos played based on playback credentials or STS tokens can be previewed. We recommend that you play videos based on playback credentials. For more information about how to configure and use the preview feature, see Configure the preview feature.
previewTime
parameter in the setVidAuth
method to specify the preview duration. The following sample code provides an example:// The previewTime parameter specifies the preview duration. Unit: seconds.
// The video is played based on the playback credential.
fAliplayer.setVidAuth(
vid: "Enter the video ID of the resource.",
region: "Enter the region in which the resource resides.",
playAuth: "Enter the playback credential of the resource",
previewTime: "Enter the preview duration. Unit: seconds.");
// The video is played based on the STS token.
fAliplayer.setVidSts(
vid: "Enter the video ID of the resource.",
region: "Enter the region in which the resource resides.",
accessKeyId: "Enter the temporary AccessKey ID generated for the STS token.",
accessKeySecret: "Enter the temporary AccessKey secret generated for the STS token.",
securityToken: "Enter the STS token of the resource.",
previewTime: "Enter the preview duration. Unit: seconds.");
Configure other settings
prepare()
method, you must set the following parameters for the player to configure these settings:
var configMap = {
'mStartBufferDuration':_mStartBufferDurationController.text,// The buffer duration before playback. Unit: milliseconds.
'mHighBufferDuration':_mHighBufferDurationController.text,// The duration of high buffer. Unit: milliseconds.
'mMaxBufferDuration':_mMaxBufferDurationController.text,// The maximum buffer duration. Unit: milliseconds.
'mMaxDelayTime': _mMaxDelayTimeController.text,// The maximum latency of live streaming. Unit: milliseconds. You can specify the latency only for live streams.
'mNetworkTimeout': _mNetworkTimeoutController.text,// The network timeout period. Unit: milliseconds.
'mNetworkRetryCount':_mNetworkRetryCountController.text,// The number of retires after a network timeout. Unit: milliseconds.
'mMaxProbeSize': _mMaxProbeSizeController.text,// The maximum probe size.
'mReferrer': _mReferrerController.text,// The referer.
'mHttpProxy': _mHttpProxyController.text,// The HTTP proxy.
'mEnableSEI': mEnableSEI,// Specifies whether to use supplemental enhancement information (SEI).
'mClearFrameWhenStop': !mShowFrameWhenStop,// Specifies whether to clear the screen when the playback stops.
'mDisableVideo': mDisableVideo,// Specifies whether to disable video.
'mDisableAudio': mDisableAudio,// Specifies whether to disable audio.
'mUserAgent':mUserAgent,// The user agent.
};
// Configure the application.
fAliplayer.setConfig(configMap);
Configure the performance
Configure local caching
setCacheConfig
method before you call the prepare
method. The following sample code provides an example:var map = {
"mMaxSizeMB": _mMaxSizeMBController.text,// The maximum space that can be occupied by the cache directory.
"mMaxDurationS": _mMaxDurationSController.text,// The maximum cache duration of a single file.
"mDir": _mDirController.text,// The cache directory.
"mEnable": mEnableCacheConfig,// Specifies whether to enable the cache feature.
};
fAliplayer.setCacheConfig(map);
Configure video download
- Normal download
Videos that are downloaded in normal download mode are not encrypted by Alibaba Cloud and can be played by third-party players.
- Secure download
Videos that are downloaded in secure download mode are encrypted by Alibaba Cloud. You cannot use third-party players to play the downloaded videos. You can play them only by using ApsaraVideo Player SDK.
- Create and configure a downloader.
FlutterAliDownloader donwloader = FlutterAliDownloader.init(); // Specify the path in which you want to save downloaded videos. donwloader.setSaveDir(path)
ApsaraVideo Player SDK for Flutter allows you to download videos that are encrypted by using Alibaba Cloud proprietary cryptography. For security reasons, you must configure a security file for encryption verification in the SDK.FlutterAliPlayerFactory.initService(byteData);
- Start the download.
After you call the method to start the download, listeners are automatically configured and a callback message is returned. The following sample code provides an example:
///1.prepare // Parameter description: Valid values of the type parameter include FlutterAvpdef.DOWNLOADTYPE_STS and FlutterAvpdef.DOWNLOADTYPE_AUTH. If the type parameter is set to DOWNLOADTYPE_STS, the required parameters are {vid,accessKeyId,accessKeySecret,securityToken}. If the type parameter is set to DOWNLOADTYPE_AUTH, the required parameters are {vid,playAuth}. downloader.prepare(type, vid).then((value) { // The value is of the MAP type. This value corresponds to the custom download class DownloadModel in the demo. DownloadModel downloadModel = DownloadModel.fromJson(value); // 2. The selectItem parameter determines the quality of videos that you want to download. List<TrackInfoModel> trackInfos = downloadModel.trackInfos; downloader.selectItem(vid,trackInfos[0].index); //3.start downloader.start(vid, trackInfos[0].index).listen((event) { // Note: The event parameter may contain various information. You can refer to information in FlutterAvpdef.EventChanneldef. The following code provides the details: if (event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_PROGRESS){ // event[EventChanneldef.DOWNLOAD_PROGRESS] indicates the download progress in percentage. }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_PROCESS){ // event[EventChanneldef.DOWNLOAD_PROCESS] indicates the processing progress in percentage. }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 the video ID and index. You can determine the video that is downloaded based on the video ID and index. You can use event['savePath'] to obtain the on-premises path of downloaded videos. }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_ERROR){ // Indicates that the download failed. You can use event['vid'] and event['index'] to obtain the video ID and index. You can determine the video that failed to download based on the video ID and index. You can use event['errorCode'] and event['errorMsg'] to obtain the error code and error message. } }); });
- Stop the download.
downloader.stop(vid, index)
- Delete a downloaded file.
When the deletion process is complete, the downloaded file is deleted. The following sample code provides an example:
downloader.delete(vid, index)
- Release a downloaded file.
If you no longer need a downloaded file, you can call the
downloader.release
method to release the file to prevent memory leaks. The following sample code provides an example:downloader.release(vid, index)