This topic describes the advanced features of ApsaraVideo Player SDK for Android and provides the sample code.
Configure playback
Enable list playback for short videos
ApsaraVideo Player SDK for Android provides a full-fledged list playback feature for short videos. The SDK uses solutions such as preload to minimize the startup loading duration of playbacks. We recommend that you do not enable this feature for long videos.
Configure external subtitles
ApsaraVideo Player SDK for Android allows you to add or switch external subtitles in the SRT, SSA, or ASS3 format for videos. The following sample code provides an example:
Enable audio-only playback
PlayerConfig config = mAliPlayer.getConfig();
config.mDisableVideo = true; // Enable audio-only playback.
mAliPlayer.setConfig(config);
Switch between hardware and software decodings
enableHardwareDecoder
method to enable or disable the hardware decoding feature. By default, hardware decoding
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.
mAliyunVodPlayer.enableHardwareDecoder(true);
onInfo
callback is invoked. The following sample code provides an example:mApsaraPlayerActivity.setOnInfoListener(new IPlayer.OnInfoListener() {
@Override
public void onInfo(InfoBean infoBean) {
if (infoBean.getCode() == InfoCode.SwitchToSoftwareVideoDecoder) {
// Switch to software decoding.
}
}
});
Enable adaptive bitrate streaming
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:List<TrackInfo> trackInfos = aliyunVodPlayer.getMediaInfo().getTrackInfos();
selectTrack
method to switch the bitrate. If you pass SELECT_AVPTRACK_TYPE_VIDEO_AUTO to the method, adaptive bitrate streaming is enabled. The following sample code provides
an example:int index = trackInfo.getIndex();
// Switch the bitrate.
aliyunVodPlayer.selectTrack(index);
// Enable adaptive bitrate streaming.
aliyunVodPlayer.selectTrack(TrackInfo.AUTO_SELECT_INDEX);
OnTrackChangedListener
method returns the switching result. You must configure the OnTrackChangedListener
callback before you call the selectTrack
method. The following sample code provides an example:aliyunVodPlayer.setOnTrackChangedListener(new IPlayer.OnTrackChangedListener() {
@Override
public void onChangedSuccess(TrackInfo trackInfo) {
// The bitrate switching is successful.
}
@Override
public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
// The bitrate switching fails. You can call the errorInfo.getMsg() method to find the cause of the failure.
}
});
Capture snapshots
snapshot
method for you to capture snapshots of videos. When you capture a snapshot, the player
saves the source data of the video image to be captured and converts the source data
to a bitmap. Then, you can invoke the OnSnapShotListener
callback to obtain the bitmap. The following sample code provides an example:// Configure the callback for snapshot capture.
aliyunVodPlayer.setOnSnapShotListener(new OnSnapShotListener(){
@Override
public void onSnapShot(Bitmap bm, int with, int height){
// Obtain the bitmap and the width and height of the video image.
}
});
// Capture a snapshot of the current video image.
aliyunVodPlayer.snapshot();
Configure video preview
ApsaraVideo Player SDK for Android integrates other configurations of ApsaraVideo VOD to support previews of videos. Only VidSts and VidAuth sources can be previewed. We recommend that you preview only VidAuth sources in ApsaraVideo VOD. For more information about how to configure and use the preview feature, see Configure the preview feature.
setPreviewTime()
method in the VidPlayerConfigGen class to specify the preview duration. The following
sample code provides an example. In this example, VidSts is used.VidSts vidSts = new VidSts;
....
VidPlayerConfigGen configGen = new VidPlayerConfigGen();
configGen.setPreviewTime(20); // Set the preview duration to 20s.
vidSts.setPlayConfig(configGen); // Configure the settings for the player.
...
After you specify the preview duration, ApsaraVideo Player SDK for Android allows
you to preview a video for the specified duration instead of the whole video. - You can use the VidPlayerConfigGen class to set the request parameters that are supported by the server. For more information, see Request parameters.
- The preview feature is not supported for Flash Video (FLV) and MP3 files.
Configure a blacklist
DeviceInfo deviceInfo = new DeviceInfo();
deviceInfo.model="Lenovo K320t";
AliPlayerFactory.addBlackDevice(BlackType.HW_Decode_H264 ,deviceInfo );
Set the referer
PlayerConfig
class for you to set the request referer. You can use the referer together with a
referer whitelist or blacklist configured in the ApsaraVideo VOD console to implement
access control. The following sample code provides an example:// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Set the referer. Example: http://example.aliyundoc.com. Note: You must add the protocol header when you set the referer.
config.mReferrer = referrer;
.... // Configure other settings.
// Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);
Specify the user agent
PlayerConfig
class for you to specify the request user agent. After you specify the user agent,
the player contains the user agent information in its requests. The following sample
code provides an example:// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Specify the user agent.
config.mUserAgent = "Required user agent";
.... // Configure other settings.
// Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);
Set the network timeout period and retries
PlayerConfig
class for you to set the network timeout period and retries. The following sample
code provides an example:// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Specify the network timeout period. Unit: milliseconds.
config.mNetworkTimeout = 5000;
// Specify the maximum number of retries upon a network timeout. The retry interval equals the timeout period specified by the mNetworkTimeout parameter. The mNetworkRetryCount parameter specifies the maximum number of retries. A value of 0 indicates zero retry. The application determines the maximum number of retries. Default value: 2.
config.mNetworkRetryCount=2;
.... // Configure other settings.
// Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);
- If you set the mNetworkRetryCount parameter to a value other than 0, the player retries the playback when it enters the loading status due to network errors. The maximum number of retries is specified by the mNetworkRetryCount parameter, and the retry interval equals the timeout period specified by the mNetworkTimeout parameter.
- If loading persists after the maximum number of retries is reached, a callback is
invoked by the
onError
method. In this case, the AVPErrorModel.code method returns ERROR_LOADING_TIMEOUT. - If the mNetworkRetryCount parameter is set to 0, the
onInfo
callback is invoked when a network timeout occurs. In this case, the InfoBean.getCode() method returns InfoCode.NetworkRetry. To resolve the issue, you can call thereload
method of ApsaraVideo Player SDK for Android to reload network packets or perform other operations as required.
Configure buffer and latency settings
PlayerConfig
class for you to configure buffer and latency settings. The following sample code
provides an example:// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Set the maximum latency. This parameter is valid only for live streaming. If the latency exceeds the maximum limit, ApsaraVideo Player SDK synchronizes frames to ensure that the latency is within the limit.
config.mMaxDelayTime = 5000;
// Set the maximum buffer duration. Unit: milliseconds. This parameter specifies the maximum buffer duration for the player to load data at a time.
config.mMaxBufferDuration = 50000;
// Set the peak buffer duration. Unit: milliseconds. The player starts to load data if the network condition is unstable. This parameter specifies the buffer duration beyond which the player stops loading data in this case.
config.mHighBufferDuration = 3000;
// Set the startup loading duration. Unit: milliseconds. A smaller value indicates a shorter startup loading duration. In this case, the player starts to load data sooner after the start of playback.
config.mStartBufferDuration = 500;
.... // Configure other settings.
// Set the maximum cache duration. Unit: milliseconds. Default value: 0.
config.mMaxBackwardBufferDurationMs = 0;
// Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);
Configure HTTP headers
PlayerConfig
class for you to add HTTP headers to requests. The following sample code provides
an example:// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Define a header.
String[] headers = new String[1];
headers[0]="Host:example.com"; // For example, add the host information to the header.
// Configure the headers.
config.setCustomHeaders(headers);
.... // Configure other settings.
// Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);
Configure the performance
Configure local caching
CacheConfig
class before you call the prepare
method. The following sample code provides an example:CacheConfig cacheConfig = new CacheConfig();
// Enable the play-and-cache feature.
cacheConfig.mEnable = true;
// Specify the maximum duration of a single cached file. Files whose duration exceeds the maximum limit are not cached.
cacheConfig.mMaxDurationS =100;
// Specify the cache directory.
cacheConfig.mDir = "The directory of the cached file";
// Specify the maximum size of the cache directory. When the total size of cached files in the cache directory exceeds the maximum limit, the earliest cached files are overwritten.
cacheConfig.mMaxSizeMB = 200;
// Configure the cache settings for the player.
mAliyunVodPlayer.setCacheConfig(cacheConfig);
setCacheConfig
method. After a video is cached, the cached file is used in the following scenarios:
- If the loop playback feature is enabled by using the
setLoop(true)
method, the cached file is used when the player replays the video. - After you cache a video and create a player to play the video, the new player plays
the video by using the cached video file.
Note For ID-based playback, information such as the audio or video ID is required to find cached files. An online request must be sent to obtain the required information that determines which cached files are needed for ID-based playback.
Method | Description | Parameter | Return value |
---|---|---|---|
public String getCacheFilePath(String URL) |
Queries the path of a cached file based on the video URL. To obtain the path, make
sure that you have called the setCacheConfig method.
|
URL | The absolute path of the cached file. |
public String getCacheFilePath(String vid, String format, String definition, int previewTime) |
Queries the path of a cached file based on the audio or video ID. To obtain the path,
make sure that you have called the setCacheConfig method.
|
|
The absolute path of the cached file. |
- If the player plays UrlSource streams by using the HLS protocol based on the URL in an M3U8 playlist, the player does not cache the video during the playback. For other supported formats, the player caches videos during playback as configured.
- If you use VidAuth or VidSts sources for playback, the player caches videos during playback as configured.
- A video is considered cached after the player reads all video data. Caching fails
if the
stop
method is called or a callback is invoked by theonError
method before the player reads all video data. - Seeking to a position inside the cached video does not affect the caching result. Seeking to a position outside the cached video may cause a caching failure.
- An encrypted video cannot be cached if the verification information in the security file for encryption verification does not match the application information.
- The
onInfo
callback is invoked to return the caching result.
mAliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
@Override
public void onInfo(InfoBean infoBean) {
if(infoBean.getCode() == InfoCode.CacheSuccess){
// Indicate that the caching succeeds.
}else if(infoBean.getCode() == InfoCode.CacheError){
// Indicate that the caching fails.
}
}
});
Configure video preload
ApsaraVideo Player SDK for Android supports video preload, which is an upgrade of the play-and-cache feature. The video preload feature allows you to specify the maximum size of memory that can be occupied by cached videos. This helps reduce the startup loading duration.
- You can preload only one MP4, MP3, FLV, or HLS file at a time.
- You can preload only one file that is played based on the URL. You cannot preload VidAuth or VidSts sources.
Query the download speed
getExtraValue
method for you to query the download speed of specified videos. The onInfo callback
is invoked to obtain the query result. The following sample code provides an example:mAliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
@Override
public void onInfo(InfoBean infoBean) {
if(infoBean.getCode() == InfoCode.CurrentDownloadSpeed){
// The download speed.
long extraValue = infoBean.getExtraValue();
}
}
});
Configure networks
Enable HTTP/2
AliPlayerGlobalSettings.setUseHttp2(true);
Configure video download settings
- 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 use only ApsaraVideo Player to play them.
Play encrypted videos
ApsaraVideo Player SDK for Android allows you to play on-demand videos encrypted based on HLS encryption, Alibaba Cloud proprietary cryptography, or digital rights management (DRM) encryption. The SDK allows you to play live streams encrypted only based on DRM encryption. For more information, see Encrypt videos for playback.Configure Native RTS SDK
You can integrate ApsaraVideo Player SDK for Android with Native RTS SDK to use the Real-Time Streaming (RTS) feature. For more information, see Native RTS SDK for Android.