This topic provides examples of how to use the advanced features of ApsaraVideo Player SDK for Flutter. For a complete list of features, see the API reference.
Playback
Play short video lists
Create a list player.
FlutterAliListPlayer fAliListPlayer = FlutterAliPlayerFactory.createAliListPlayer();Add and remove resources.
The list player supports playback only from UrlSource or VidSts.
// The uid parameter specifies the unique ID of a video. You can use the UID to identify videos. Videos that have the same UID are considered the same. fAliListPlayer.addUrlSource(url,uid); fAliListPlayer.addVidSource(vid,uid); fAliListPlayer.removeSource(uid);Set the number of videos to preload.
Set a reasonable number of videos to preload to improve startup speed. The following code provides an example:
// Set the number of videos to preload. The total number of loaded videos is calculated using the following formula: 1 + count * 2. fAliListPlayer.setPreloadCount(count);Play the video source.
// The uid parameter is required. For URL-based playback, specify only the uid. For STS-based playback, specify the STS information. fAliListPlayer.moveTo();
Switch between hardware and software decoding
ApsaraVideo Player SDK for Flutter supports hardware decoding for H.264 and H.265. It also provides the setEnableHardwareDecoder method, which is enabled by default. If hardware decoding fails to initialize, the player automatically switches to software decoding to ensure uninterrupted playback. The following code provides an example:
// Enable hardware decoding. This feature is enabled by default.
fAliplayer.setEnableHardwareDecoder(enable);Adaptively switch video definition based on network conditions
ApsaraVideo Player SDK for Flutter supports adaptive bitrate streaming for HLS and Dynamic Adaptive Streaming over HTTP (DASH) video streams. After the prepare method succeeds, call getMediaInfo to retrieve information about each stream as a TrackInfo object. The following code provides an example:
fAliplayer.getMediaInfo().then((value) {
// The value is of the map type. You can use value['tracks'] to get the corresponding 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 switch the active stream. Pass the trackIndex value from the TrackInfo object as the parameter. The result of the switch is returned in the callback after the OnTrackChangedListener listener triggers.
// Switch the bitrate.
fAliplayer.selectTrack(index);
// Switch the bitrate and enable adaptive streaming.
fAliplayer.selectTrack(-1);Capture snapshots
ApsaraVideo Player SDK for Flutter provides a snapshot capture feature, implemented through the setOnSnapShot method.
// The listener for successful snapshot capturing.
fAliplayer.setOnSnapShot((path,playerId) {
});
// Capture a snapshot. path specifies the path where the image is saved.
fAliplayer.snapshot(path);Preview videos
ApsaraVideo Player SDK for Flutter works with ApsaraVideo VOD configurations to support video preview. The VidAuth (recommended) and VidSts playback methods support this feature. For more information about configuring and using video preview, see Video preview.
After you configure the preview feature, call the previewTime method of the setVidAuth interface to set the preview duration. The following code provides an example:
// previewTime specifies the preview duration in seconds.
// VidAuth-based playback
fAliplayer.setVidAuth(
vid: "Enter the VID of the resource",
region: "Enter the region of the resource",
playAuth: "Enter the PlayAuth of the resource",
previewTime: "Enter the preview duration in seconds");
// VidSts-based playback
fAliplayer.setVidSts(
vid: "Enter the VID of the resource",
region: "Enter the region of the resource",
accessKeyId: "Enter the AccessKey ID of the resource",
accessKeySecret: "Enter the AccessKey secret of the resource",
securityToken: "Enter the security token of the resource",
previewTime: "Enter the preview duration in seconds");Other configurations
You can configure additional playback settings for ApsaraVideo Player SDK for Flutter. Set these configurations before calling the prepare() method.
var configMap = {
'mStartBufferDuration':_mStartBufferDurationController.text,// The buffer duration before playback starts. Unit: milliseconds.
'mHighBufferDuration':_mHighBufferDurationController.text,// The high buffer duration. Unit: milliseconds.
'mMaxBufferDuration':_mMaxBufferDurationController.text,// The maximum buffer duration. Unit: milliseconds.
'mMaxDelayTime': _mMaxDelayTimeController.text,// The maximum latency for live streaming. Unit: milliseconds. Note: This parameter is valid only for live streaming.
'mNetworkTimeout': _mNetworkTimeoutController.text,// The network timeout period. Unit: milliseconds.
'mNetworkRetryCount':_mNetworkRetryCountController.text,// The number of retries after a network timeout.
'mMaxProbeSize': _mMaxProbeSizeController.text,// The maximum probe size.
'mReferrer': _mReferrerController.text,// The referrer.
'mHttpProxy': _mHttpProxyController.text,// The HTTP proxy.
'mEnableSEI': mEnableSEI,// Specifies whether to enable Supplemental Enhancement Information (SEI).
'mClearFrameWhenStop': !mShowFrameWhenStop,// Specifies whether to clear the frame when playback stops.
'mDisableVideo': mDisableVideo,// Specifies whether to disable video.
'mDisableAudio': mDisableAudio,// Specifies whether to disable audio.
'mUserAgent':mUserAgent,// The User-Agent.
};
// Apply the configuration.
fAliplayer.setConfig(configMap);Performance
Pre-rendering
ApsaraVideo Player SDK for Flutter supports fast rendering of the first video frame before playback starts.
This feature is disabled by default.
You must set the
Viewbefore callingPrepareto ensure that frames are rendered to theViewpromptly when they are ready.Enabling this feature affects the trigger order of the preparation success and first-frame rendering events. When disabled, the preparation success event triggers before the first-frame rendering event. When enabled, the first-frame rendering event may trigger before the preparation success event due to differences in decoding and rendering speeds. This does not affect playback.
The following code provides an example:
fAliplayer.setOption(FlutterAvpdef.ALLOW_PRE_RENDER, 1);Local caching
ApsaraVideo Player SDK for Flutter provides local caching to store videos during playback. This helps reduce traffic when users replay videos. To use this feature, enable enableLocalCache for the player before calling prepare. The following code provides an example:
/**
* Enable local caching. After this feature is enabled, videos are cached to local files.
*
* @param enable - The switch for the local caching feature. true: enables local caching. false: disables local caching. Default value: false.
* @param maxBufferMemoryKB - This parameter is deprecated and has no effect in v5.4.7.1 and later.
* @param localCacheDir - The directory of the cached file. This must be an absolute path.
* @param mDocTypeForIOS - The type of the sandbox directory on your iOS device.
*/
FlutterAliplayer.enableLocalCache(bool enable,String maxBufferMemoryKB,String localCacheDir,DocTypeForIOS mDocTypeForIOS);
/**
* Configurations for clearing local cache files.
*
* @param expireMin - This parameter is deprecated and has no effect in v5.4.7.1 and later.
* @param maxCapacityMB - The maximum cache size. Unit: MB. Default value: 20 GB. When the system clears the cache, if the total cache size exceeds this limit, the system sorts cache items by their last access time and deletes the oldest cached files one by one until the total cache size is less than or equal to the limit.
* @param freeStorageMB - The minimum free disk space. Unit: MB. Default value: 0. When the system clears the cache, if the current free disk space is less than this value, the system also deletes cached files one by one according to the rules until the free disk space is greater than or equal to this value or all cached files are cleared.
*/
FlutterAliplayer.setCacheFileClearConfig(String expireMin,String maxCapacityMB,String freeStorageMB);Enable or disable local caching for a single URL
To enable or disable local caching for a specific URL, set the corresponding parameter in the player config. The following code provides an example:
// Get the configurations.
fAliplayer.getPlayConfig().then((config){
// Disable or enable local caching.
config.enableLocalCache = false;
// Apply the configurations.
fAliplayer.setPlayConfig(config);
});Preloading
ApsaraVideo Player SDK for Flutter provides a preloading feature, an enhancement of local caching that improves video startup speed by allowing you to specify the memory size allocated for the video cache.
The preloading feature has the following limits:
Supports loading single media files, such as MP4, MP3, FLV, and HLS files.
Supports preloading only for videos played using the UrlSource method. Preloading is not supported for videos played using the VidAuth or VidSts methods.
Enable the local caching feature. For more information, see Local caching.
Create a
FlutterAliMediaLoaderV2instance.FlutterAliMediaLoaderV2 loaderV2 = FlutterAliMediaLoaderV2();Set listeners for the preloading task.
onError: Listener for errors.loaderV2.onError = (ErrorInfo error) { };onCompleted: Listener for task completion.loaderV2.onCompleted = (taskId, urlOrVid) { };onCanceled: Listener for task cancellation.loaderV2.onCanceled = (taskId, urlOrVid) { };
Optional: Set parameters for the preloading task. This step applies only to adaptive bitrate streaming.
You only need to set one of the following parameters:
defaultQuality,defaultBandWidth, ordefaultResolution.PreloadConfig config = PreloadConfig(); config.duration = 1000; // Default value: 1000 config.defaultQuality = "FD"; config.defaultBandWidth = 200000; config.defaultResolution = 1920 * 1080; loaderV2.setPreloadConfig(config);Add a preloading task and retrieve the task ID.
VidAuth (Recommended)
VidAuth auth = VidAuth( vid: "your videoId", playAuth: "your playAuth", region: "your region", ); loaderV2.addTask(auth).then((taskId) { print("MediaLoaderV2: taskId: $taskId"); });VidSts
VidSts vidSts = VidSts( vid: "your vid", accessKeyId: "your accessKeyId", accessKeySecret: "your accessKeySecret", securityToken: "your securityToken", ); loaderV2.addTask(vidSts).then((taskId) { print("MediaLoaderV2: taskId: $taskId"); });UrlSource
loaderV2.addTask(UrlSource(videoUrl: "videoUrl")).then((taskId) { print("MediaLoaderV2: taskId: $taskId"); });Pause the preloading task.
loaderV2.pauseTask(taskId);Resume the preloading task.
loaderV2.resumeTask(taskId);Cancel the preloading task.
loaderV2.cancelTask(taskId);Destroy the
FlutterAliMediaLoaderV2instance.loaderV2.dispose();
Video download
ApsaraVideo Player SDK for Flutter supports downloading on-demand videos for offline playback. Two download modes are available: normal download and secure download.
Normal download
Videos downloaded in this mode are not encrypted by Alibaba Cloud and can be played using third-party players.
Secure download
Videos downloaded in this mode are encrypted by Alibaba Cloud and can be played only using ApsaraVideo Player SDK.
Usage Instructions
The video download feature is available only for the VidSts and VidAuth methods.
To use the video download feature, you must enable it and configure a download mode in the ApsaraVideo VOD console. For more information, see Offline download.
Resumable download is supported.
Procedure
Optional: Configure the security file for encryption verification. This step is required only for secure download. You can skip this step for normal download.
NoteEnsure that the configured security file matches the app information. Otherwise, the video download fails.
If you use secure download, you must configure the key file generated in the ApsaraVideo VOD console in ApsaraVideo Player SDK. This key file is used for decryption and verification during video download and playback. For more information about generating the key file, see Secure download.
The following is a one-time configuration:
FlutterAliPlayerFactory.initService(byteData);Create and configure a downloader.
The following code provides an example:
FlutterAliDownloader downloader = FlutterAliDownloader.init(); /// Set the save path. downloader.setSaveDir(path)Start the download.
After you start the download, listeners are automatically registered and callback information is returned. The following code provides an example:
/// 1. prepare /// Parameter description: The type parameter can be set to FlutterAvpdef.DOWNLOADTYPE_STS or FlutterAvpdef.DOWNLOADTYPE_AUTH. If you set type to DOWNLOADTYPE_STS, the vid, accessKeyId, accessKeySecret, and securityToken parameters are required. If you set type to DOWNLOADTYPE_AUTH, the vid and playAuth parameters are required. downloader.prepare(type, vid).then((value) { // The value is of the map type. It corresponds to the custom download class DownloadModel in the demo. DownloadModel downloadModel = DownloadModel.fromJson(value); // 2. selectItem. Select the definition of the video to download based on the trackInfo. 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 types of information. For more information, see FlutterAvpdef.EventChanneldef. The following section describes the details. if (event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_PROGRESS){ // The download progress in percentage. Get the download progress: event[EventChanneldef.DOWNLOAD_PROGRESS]. }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_PROCESS){ // The processing progress in percentage. Get the processing progress: event[EventChanneldef.DOWNLOAD_PROCESS]. }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_COMPLETION){ // The download is complete. You can use event['vid'] and event['index'] to get the corresponding vid and index to identify which video is downloaded. You can use event['savePath'] to get the local path of the downloaded video. }else if(event[EventChanneldef.TYPE_KEY] == EventChanneldef.DOWNLOAD_ERROR){ // The download failed. You can use event['vid'] and event['index'] to get the corresponding vid and index to identify which video failed to download. You can use event['errorCode'] and event['errorMsg'] to get the error code and error message. } }); });Stop the download.
The following code provides an example:
downloader.stop(vid, index)Delete the download.
Deleting the download option also deletes the downloaded local file. The following is an example:
downloader.delete(vid, index)Release the download object.
When a download object is no longer needed, call the
releasemethod to release it and prevent memory leaks. The following code provides an example:downloader.release(vid, index)
Encrypted video playback
ApsaraVideo VOD supports HLS encryption, Alibaba Cloud proprietary cryptography, and Digital Rights Management (DRM) encryption. For more information about encrypted playback, see Play an encrypted video.