This topic provides examples of the basic features of ApsaraVideo Player SDK for Flutter. For more information about advanced features and the API reference, see Advanced features and API reference.
Set the playback source (DataSource)
ApsaraVideo Player SDK for Flutter supports four video on-demand (VOD) playback methods: VidAuth (recommended for ApsaraVideo VOD users), VidSts, UrlSource, and encrypted playback.
ApsaraVideo Player SDK for Flutter supports only one live streaming playback method: UrlSource.
VOD playback
VOD playback using VidAuth (Recommended)
To play a VOD video using the VidAuth method, set the vid property to the video ID and the playAuth property to the playback credential.
After an audio or video is uploaded, you can obtain its ID from the console (path: Media Library > Audio/Video) or using the SearchMedia server-side API.
You can call the GetVideoPlayAuth operation to obtain playback credentials. We recommend that you use an SDK to call this operation. This frees you from performing complex signature calculations. For more information, see the Developer Portal.
We recommend that ApsaraVideo VOD users use this playback method. Compared with the VidSts method, the VidAuth method is more secure and easier to use. For a detailed comparison, see Comparison between the credential-based method and the STS-based method.
void onViewPlayerCreated(viewId) async {
// Set the render view for the player.
fAliplayer.setPlayerView(viewId);
// 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: "Video ID",// Required. The video ID.
region: "Region",// Required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
playAuth: "<yourPlayAuth>",// Required. The playback credential. To generate a playback credential, call the GetVideoPlayAuth operation.
playConfig: value);
});
}
}VOD playback using VidSts
To play a VOD video using the VidSts method, you can use a temporary Security Token Service (STS) token instead of a playback credential. You must obtain an STS token and a temporary AccessKey pair (AccessKey ID and AccessKey secret). For more information, see Obtain an STS token.
void onViewPlayerCreated(viewId) async {
// Set the render view for the player.
fAliplayer.setPlayerView(viewId);
// Before you call generatePlayerConfig, you must call createVidPlayerConfigGenerator() and setPreviewTime().
FlutterAliplayer.createVidPlayerConfigGenerator();
FlutterAliplayer.setPreviewTime(0);
// The VidSts playback method.
FlutterAliplayer.generatePlayerConfig().then((value) {
fAliplayer.setVidSts(
vid: "Video ID",// Required. The video ID.
region: "Region",// Required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
accessKeyId: "<yourAccessKeyId>",// Required. The AccessKey ID of the temporary STS AccessKey pair. To generate the AccessKey ID, call the AssumeRole operation in STS.
accessKeySecret: "<yourAccessKeySecret>",// Required. The AccessKey secret of the temporary STS AccessKey pair. 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);
});
}VOD playback using UrlSource
To play a VOD video using the UrlSource method, set the `url` property of the player to the playback URL. The playback URL can be a third-party VOD URL or a playback URL from ApsaraVideo VOD.
You can call the GetPlayInfo operation to obtain Alibaba Cloud playback URLs. We recommend that you use an SDK to obtain media playback URLs. This frees you from performing complex signature calculations. For more information, see the Developer Portal.
void onViewPlayerCreated(viewId) async {
// Set the render view for the player.
fAliplayer.setPlayerView(viewId);
// Set the playback source.
switch (_playMode) {
// The UrlSource playback method.
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
VOD videos support HLS encryption, Alibaba Cloud proprietary cryptography, and DRM encryption. For more information about encrypted playback, see Play encrypted videos on Flutter.
Live video playback
For more information, see ApsaraVideo Player for Flutter.
The UrlSource method plays a video directly from a URL. The VidSts and VidAuth methods play a video using a video ID (VID).
For more information about how to set the region, see VOD regions.
Control playback
ApsaraVideo Player SDK for Flutter supports common operations such as starting, pausing, and seeking to a specific time.
Autoplay
To enable autoplay for a video, call the setAutoPlay method. This feature is disabled by default. The following sample code shows how to enable autoplay:
fAliplayer.setAutoPlay(true);Prepare for playback
To prepare for video playback, call the prepare method to start reading and parsing data. If autoplay is enabled, the video automatically starts playing after the data is parsed. The following sample code shows how to prepare for playback:
fAliplayer.prepare();Start playback
To start playing a video, call the play method. The following sample code shows how to start playback:
fAliplayer.play();Start playback from a specific time
To play a video from a specific time, call the seek method. This is useful in scenarios such as dragging the progress bar or resuming playback. The following sample code shows how to start playback from a specific time:
//// The position parameter specifies the time in milliseconds. The seekMode parameter can be set to FlutterAvpdef.ACCURATE for accurate seeking or FlutterAvpdef.INACCURATE for inaccurate seeking.
fAliplayer.seek(position,seekMode);To start playback from a specific position, you can call the following method. This setting takes effect only once and is suitable for scenarios where playback starts from a specific time. The following sample code shows how to start playback from a specific position:
// Call this method before each call to prepare. This setting takes effect only once. The time parameter specifies the time in milliseconds. The seekMode parameter can be set to FlutterAvpdef.ACCURATE for accurate seeking or FlutterAvpdef.INACCURATE for inaccurate seeking.
fAliplayer.setStartTime(time, seekMode);Pause playback
To pause video playback, call the pause method. The following sample code shows how to pause playback:
fAliplayer.pause();Resume playback
To resume video playback, call the play method. The following sample code shows how to resume playback:
fAliplayer.play();Stop playback
To stop video playback, call the stop method. The following sample code shows how to stop playback:
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 waits for all player resources to be released before it returns a value. If your UI requires high responsiveness, use the asynchronous destroy method. Note the following:
Do not perform any other operations on the player object during asynchronous destruction.
Do not manually stop the player before you call the asynchronous destroy method. This is because the method includes an asynchronous stop process.
Player status listener
ApsaraVideo Player SDK for Flutter lets you set player listeners and monitor the player status.
Set player listeners
The player supports multiple listeners.
When you create a player for manual playback, you must set
OnPrepared. This is because you need to callplayin theOnPreparedcallback to start the playback.We recommend that you set the
OnTrackReadyandOnErrorlisteners because they are important for handling track readiness and errors.
The following sample code shows only some of the available listener methods:
// The player is prepared.
fAliplayer.setOnPrepard((playerId) {});
// The first frame is rendered.
fAliplayer.setOnRenderingStart((playerId) {});
// The video width or height changes.
fAliplayer.setOnVideoSizeChanged((width, height,playerId) {});
// The player status changes.
fAliplayer.setOnStateChanged((newState,playerId) {});
// The loading status.
fAliplayer.setOnLoadingStatusListener(
loadingBegin: (playerId) {},
loadingProgress: (percent, netSpeed,playerId) {},
loadingEnd: (playerId) {});
// Seeking is complete.
fAliplayer.setOnSeekComplete((playerId) {});
// The callback for player event information, such as 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) {});
// The snapshot is taken.
fAliplayer.setOnSnapShot((path,playerId) {});
// An error occurs.
fAliplayer.setOnError((errorCode, errorExtra, errorMsg,playerId) {});
// The stream is switched.
fAliplayer.setOnTrackChanged((value,playerId) {});Monitor the playback status
To monitor the status of the player, you can use the `onStateChanged` callback. The parameter of the callback indicates the current status of the player. The following sample code shows how to monitor the player status:
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: // Playback is in progress.
break;
case FlutterAvpdef.AVPStatus_AVPStatusPaused: // Playback is paused.
break;
case FlutterAvpdef.AVPStatus_AVPStatusStopped: // Playback is stopped.
break;
case FlutterAvpdef.AVPStatus_AVPStatusCompletion: // Playback is complete.
break;
case FlutterAvpdef.AVPStatus_AVPStatusError: // An error occurs during playback.
break;
default:
}
});Set the display mode
ApsaraVideo Player SDK for Flutter supports display settings such as scaling, rotation, and mirroring.
Fill
You can set one of the following three scaling modes for the video by calling the setScalingMode method: aspect fit, aspect fill, or scale to fill. The following sample code shows how to set the scaling mode:
// Set the mode to aspect fit. The video is scaled down to fit within the view without changing the aspect ratio. No image distortion occurs.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALEASPECTFIT);
// Set the mode to aspect fill. The video is scaled up to fill the view without changing the aspect ratio. No image distortion occurs.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALEASPECTFILL);
// Set the mode to scale to fill. The video is stretched to fill the view. If the aspect ratio of the video is different from that of the view, the image may be distorted.
fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALETOFILL);Rotation
To rotate the video by a specified angle, call the setRotateMode method. After you set the rotation angle, you can query the current angle. The following sample code shows how to rotate the video:
// Set the clockwise rotation to 0 degrees.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_0);
// Set the clockwise rotation to 90 degrees.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_90);
// Set the clockwise rotation to 180 degrees.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_180);
// Set the clockwise rotation to 270 degrees.
fAliplayer.setRotateMode(FlutterAvpdef.AVP_ROTATE_270);
// Get the rotation angle.
fAliplayer.getRotateMode();Mirroring
You can set the mirroring mode to horizontal, vertical, or none by calling the setMirrorMode method. The following sample code shows how to set the mirroring mode:
// Set the mode to no mirroring.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_NONE);
// Set the mode to horizontal mirroring.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_HORIZONTAL);
// Set the mode to vertical mirroring.
fAliplayer.setMirrorMode(FlutterAvpdef.AVP_MIRRORMODE_VERTICAL); Get playback information
ApsaraVideo Player SDK for Flutter lets you obtain the current playback progress and the duration of the video.
Obtain the current playback progress
You can obtain the current playback position from the `onInfo` callback. The value is returned in milliseconds. The following sample code shows how to obtain the current playback progress:
fAliplayer.setOnInfo((infoCode,extraValue,extraMsg,playerId){
if(infoCode==FlutterAvpdef.CURRENTPOSITION){
// The extraValue parameter indicates the current playback progress.
}
});Obtain the video duration
You can obtain the total duration of a video. The video duration can be obtained only after the video is loaded. You can obtain the duration after the `AVPEventPrepareDone` event occurs. The following sample code shows how to obtain the video duration:
fAliplayer.getMediaInfo().then((value){
_videoDuration=value['duration'];
});Set the volume
Volume settings include volume adjustment and mute settings.
Volume adjustment
To adjust the volume, call the setVolume method. The volume can be set to a value from 0 to 2. If the value is greater than 1, noise may occur. We do not recommend that you set the value to be greater than 1. After you set the volume, you can also obtain the current volume. The following sample code shows how to adjust the volume:
// The value of volume is a real number from 0 to 2.
fAliPlayer.setVolume(1);
// Get the volume information.
fAliPlayer.getVolume();Mute settings
To mute a video that is being played, call the setMute method. The following sample code shows how to mute a video:
fAliplayer.setMute(true);Fast-forward playback
ApsaraVideo Player SDK for Flutter provides a fast-forward playback feature. By calling the setRate method, you can play a video at a speed of 0.5× to 5×. The audio pitch remains unchanged. The following sample code shows how to set the playback speed:
// Set the playback speed. Speeds from 0.5x to 5x are supported. The speed is usually set to a multiple of 0.5, such as 0.5x, 1x, or 1.5x.
fAliplayer.setRate(1.0);Multi-definition settings
If you use a VID-based method (VidAuth (recommended) or VidSts) for playback, no extra settings are required. ApsaraVideo Player SDK for Flutter obtains the list of definitions from the ApsaraVideo VOD service. The SDK lets you obtain and switch definitions. This feature is not supported for the UrlSource playback method.
Obtain definitions
After a video is loaded, you can obtain the available definitions for the video.
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 definitions
To switch the definition, call the selectTrack method and pass the index of the corresponding `TrackInfo` object.
fAliplayer.selectTrack(trackIdx);Definition switching notification
The following callback is triggered after the definition is successfully switched.
fAliplayer.setOnTrackChanged((value,playerId){
// A callback indicates that the definition is switched successfully. No method is provided for a switching failure.
});Loop playback
ApsaraVideo Player SDK for Flutter provides a loop playback feature. Call setLoop to enable loop playback. After the video finishes playing, it automatically starts playing again from the beginning. The following sample code shows how to enable loop playback:
fAliplayer.setLoop(true);The onInfo callback is used to notify you when the loop playback starts. The following sample code shows how to use the callback:
fAliplayer.setOnInfo((infoCode, extraValue, extraMsg, playerId) {
if(infoCode == FlutterAvpdef.LOOPINGSTART){
// The notification for the start of loop playback.
}
});Get playback logs
ApsaraVideo Player SDK for Flutter provides a feature to obtain playback logs. Call `enableConsoleLog` to enable log printing. The following sample code shows how to enable log printing:
// Enable log printing.
FlutterAliplayer.enableConsoleLog(true);
// Set the log level. The default value is AF_LOG_LEVEL_INFO. To troubleshoot issues, you can set the level to AF_LOG_LEVEL_TRACE.
FlutterAliplayer.setLogLevel(FlutterAvpdef.AF_LOG_LEVEL_INFO);ApsaraVideo Player SDK for Flutter provides a feature to obtain frame-level logs. Call `setLogOption` to enable the printing of frame-level logs. The following sample code shows how to set the printing of frame-level logs:
/// Set the log level. For troubleshooting, set the log level to AF_LOG_LEVEL_TRACE.
FlutterAliplayer.setLogLevel(LogLevel.AF_LOG_LEVEL_INFO);
/// Enable or disable logs.
FlutterAliplayer.enableConsoleLog(true);
/// The callback for log information.
FlutterAliplayer.setLogInfoCallBack((level, msg) {
print("[LOG][LEVEL][$level] $msg");
});
/// Enable the callback for frame-level logs. This is usually enabled for troubleshooting.
/// The value of the option. 0: disable. 1: enable.
FlutterAliplayer.setLogOption(value);The frame-level logging feature is mainly used for troubleshooting.