This topic provides usage examples for the advanced features of ApsaraVideo Player SDK for Android. For more information about supported features and their usage, see API reference.
To run the demo, download it and follow the instructions in Run the Demo to compile and run it.
Professional competence verification
Some features of ApsaraVideo Player require a Professional Edition license. To use these features, you must obtain a license. For more information, see Features of ApsaraVideo Player SDK and Obtain a license for ApsaraVideo Player SDK.
Set a listener when the application starts or before you call any player API operations:
import com.aliyun.private_service.PrivateService;
PrivateService.setOnPremiumLicenseVerifyCallback(new PrivateService.OnPremiumLicenseVerifyCallback() {
@Override
public void onPremiumLicenseVerifyCallback(PrivateService.PremiumBizType type, boolean isValid, String errorMsg) {
Log.d(TAG, "onPremiumLicenseVerifyCallback: " + type + " isValid: " + isValid + " errorMsg: " + errorMsg);
}
});PremiumBizType is an enumeration of Professional Edition features. When you use a related feature, the player verifies the license and returns the result through this callback. If isValid is false, errorMsg contains the reason for the failure.
Playback
List playback
The ApsaraVideo Player SDK for Android provides a comprehensive list playback feature that is ideal for short video feeds. When combined with features such as preloading, it significantly improves the startup speed of short videos.
For a better list playback experience, we recommend that you use our mini-series solution. For more information, see Client-side development for mini-series.
Play videos with transparency
Feature description
The ApsaraVideo Player SDK supports rendering the alpha channel to achieve dynamic effects for transparent gift animations. In scenarios such as live channels, playing transparent gift animations without obscuring the live content significantly enhances the user's viewing and interactive experience.
Limits
The transparent rendering feature is available in All-in-One SDK V6.8.0 and later or ApsaraVideo Player SDK V6.9.0 and later.
Advantages
Using MP4 videos with transparency information for gift effects provides better animation quality, smaller file sizes, higher compatibility, and greater development efficiency. This allows gift effects to be better presented to users, improving the user experience.
Better animation quality: MP4 videos retain original animation quality, including details and colors. Compared to other formats such as APNG or IXD, MP4 more accurately restores designer-created animation effects.
Smaller file size: MP4 video files compress more effectively than other formats such as APNG or IXD, which improves loading speed and reduces network bandwidth consumption.
Higher compatibility: MP4 is a universal video format widely supported across various devices and browsers, which ensures gift effects play correctly on mainstream devices.
Higher development efficiency: Using MP4 videos as gift effects involves a relatively simple technical solution. Developers do not need to research and implement complex parsing and rendering logic, which allows them to focus on other features and improve development efficiency.
External subtitles
For detailed code examples, see the ExternalSubtitle module in API-Example. This project is a Java-based example project for the ApsaraVideo Player SDK for Android to help you quickly integrate the core features of the SDK.
The ApsaraVideo Player SDK for Android supports adding and switching external subtitles. The SDK supports SRT, SSA, ASS, and VTT subtitle formats.
Example:
Create a view to display subtitles.
Create different views based on subtitle formats.
If you are using Player SDK V7.6.0 or later and
VttSubtitleViewto display SRT and VTT subtitles, you must set the following listener:// Required for player V7.6.0 and later mAliPlayer.setOnVideoSizeChangedListener(new IPlayer.OnVideoSizeChangedListener() { @Override public void onVideoSizeChanged(int width, int height) { int viewWidth = getWidth(); int viewHeight = getHeight(); IPlayer.ScaleMode mode = mVideoListPlayer.getScaleMode(); SubTitleBase.VideoDimensions videoDimensions = SubTitleBase.getVideoDimensionsWhenRenderChanged(width, height, viewWidth, viewHeight, mode); vttSubtitleView.setVideoRenderSize(videoDimensions.videoDisplayWidth, videoDimensions.videoDisplayHeight); } });Add subtitles.
ImportantSet the subtitle file in
onPrepared.mAliPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() { @Override public void onPrepared() { // Subtitle settings (must be set in onPrepared) mAliPlayer.addExtSubtitle(EXT_SUBTITLE_URL); } });Set subtitle-related listeners.
Audio-only playback
To achieve audio-only playback, disable video playback by configuring PlayerConfig before you call prepare.
PlayerConfig config = aliPlayer.getConfig();
config.mDisableVideo = true; // Enable audio-only playback
aliPlayer.setConfig(config);Switch between software and hardware decoding
Switch the decoding method before playback starts. Switching during playback has no effect.
The ApsaraVideo Player SDK for Android provides hardware decoding capabilities for H.264 and H.265. It also provides the enableHardwareDecoder switch. This switch is enabled by default. If hardware decoding fails to initialize, the player automatically switches to software decoding to ensure normal video playback. The following code is an example:
// Enable hardware decoding. Enabled by default
aliPlayer.enableHardwareDecoder(true);If the player automatically switches from hardware to software decoding, a callback is triggered through onInfo. The following code is an example:
mApsaraPlayerActivity.setOnInfoListener(new IPlayer.OnInfoListener() {
@Override
public void onInfo(InfoBean infoBean) {
if (infoBean.getCode() == InfoCode.SwitchToSoftwareVideoDecoder) {
// Switched to software decoding
}
}
});H.265 adaptive playback
If the current device model is in the cloud-based H.265 blacklist or if hardware decoding of an H.265 stream fails, adaptive fallback occurs. The fallback process is as follows: If an H.264 backup stream is set, the backup stream plays automatically. If no H.264 backup stream is set, the player automatically falls back to H.265 software decoding.
This feature is enabled only after you activate the value-added service for adaptive decoding with combined cloud and client capabilities. To activate this service, you must submit a Yida form to apply for a license.
The value-added service for adaptive decoding with combined cloud and client capabilities primarily includes: 1. Dynamic delivery of cloud-based hardware decoding compatibility data. 2. Adaptive fallback from H.265 streams to H.264 streams.
Even if this value-added service is not enabled, the SDK can still automatically switch to software decoding when hardware decoding fails.
The following code shows how to set a backup stream:
// The application layer maintains a Map storing all key-value pairs of original URL-backup URL. When switching, query the backup URL in the Map based on the original URL
AliPlayerGlobalSettings.setAdaptiveDecoderGetBackupURLCallback(new AliPlayerGlobalSettings.OnGetBackupUrlCallback() {
@Override
public String getBackupUrlCallback(int oriBizScene, int oriCodecType, String original_url) {
String kurl = original_url;
if (!H265toH264Map.get(kurl).isEmpty()) {
return H265toH264Map.get(kurl);
} else {
return "";
}
}
});Adaptively switch video definition based on network conditions
Multi-bitrate adaptive HLS video streams can be generated using a video packaging transcoding template group in ApsaraVideo VOD. For more information, see Configure adaptive bitrate streaming for VOD.
For adaptive streams generated by transcoding in ApsaraVideo VOD, if you use Vid for playback, you must set the default playback definition list to
DEFINITION_AUTOto obtain and play the adaptive video stream. Otherwise, the player selects a low-definition video stream for playback based on the default logic. For the default definition playback order, see If a video is transcoded into multiple definitions, which definition will the player SDK play by default?. The following code shows how to specify the definition list for VidAuth playback:VidAuth vidAuth = new VidAuth(); List<Definition> list = new ArrayList<>(); list.add(Definition.DEFINITION_AUTO); vidAuth.setDefinition(list);
The ApsaraVideo Player SDK for Android supports adaptive bitrate streaming for HLS and DASH video streams. After prepare succeeds, you can call getMediaInfo to obtain information about each bitrate stream in a TrackInfo object. The following code is an example:
List<TrackInfo> trackInfos = aliPlayer.getMediaInfo().getTrackInfos();During playback, you can call the player's selectTrack method to switch the playback bitrate stream. Set the value to AUTO_SELECT_INDEX to enable adaptive bitrate streaming. The following code is an example:
int index = trackInfo.getIndex();
// Switch bitrates
aliPlayer.selectTrack(index);
// Switch bitrates and adapt
aliPlayer.selectTrack(TrackInfo.AUTO_SELECT_INDEX);The switch result is returned through a callback after you set the OnTrackChangedListener (before calling selectTrack). The following code is an example:
aliPlayer.setOnTrackChangedListener(new IPlayer.OnTrackChangedListener() {
@Override
public void onChangedSuccess(TrackInfo trackInfo) {
// Switch successful
}
@Override
public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
// Switch failed. Get failure reason from errorInfo.getMsg()
}
});Optional: Before you call the player's selectTrack method to switch the playback stream to adaptive bitrate streaming, you can set a maximum definition for adaptive bitrate (ABR) switching in the configuration. This prevents automatic switching to an unexpected bitrate. For the setting to take effect, we recommend that you call this code before the player calls the prepare method or the list player calls the moveTo method. The following code is an example:
PlayerConfig config = aliPlayer.getConfig();
config.mMaxAllowedAbrVideoPixelNumber = 921600; // Set upper limit of pixel count for ABR definition to 921600 (width × height = 1280 × 720), so pixel count of definition ABR can switch to is ≤ this value
aliPlayer.setConfig(config);Take snapshots
The ApsaraVideo Player SDK for Android provides a snapshot feature to capture the current video frame. You can use the snapshot API operation, which captures raw data and returns it as a bitmap through the OnSnapShotListener callback interface. The following code is an example:
// Set snapshot callback
aliPlayer.setOnSnapShotListener(new OnSnapShotListener(){
@Override
public void onSnapShot(Bitmap bm, int with, int height){
// Obtained bitmap and image dimensions
}
});
// Capture current playback frame
aliPlayer.snapshot();Preview
The ApsaraVideo Player SDK for Android, together with ApsaraVideo VOD configurations, implements a preview feature. It supports VidSts and VidAuth (recommended for ApsaraVideo VOD) playback methods. For more information about how to configure and use the preview feature, see Preview videos.
After you configure the preview feature, use the VidPlayerConfigGen.setPreviewTime() method to set the preview duration for the player. The following code shows an example for VidSts playback:
VidSts vidSts = new VidSts;
....
VidPlayerConfigGen configGen = new VidPlayerConfigGen();
configGen.setPreviewTime(20);// 20-second preview
vidSts.setPlayConfig(configGen);// Set for playback source
...When the preview duration is set, the server does not return the full video content when the video is played through the ApsaraVideo Player SDK for Android. Instead, it returns only the content for the specified preview duration.
VidPlayerConfigGen supports setting request parameters that are supported by the server. For more information, see Request parameters.
The preview feature is not currently supported for FLV and MP3 format videos.
Set a blacklist
The ApsaraVideo Player SDK for Android provides a hardware decoding blacklist mechanism. For devices that cannot use hardware decoding for playback, you can directly use software decoding to prevent errors. The following code is an example:
DeviceInfo deviceInfo = new DeviceInfo();
deviceInfo.model="Lenovo K320t";
AliPlayerFactory.addBlackDevice(BlackType.HW_Decode_H264 ,deviceInfo );The blacklist is automatically cleared after you exit the app.
Set a Referer
The ApsaraVideo Player SDK for Android supports setting a Referer. Together with the blacklist and whitelist Referer settings in the console, this lets you control access permissions. You can use the PlayerConfig method to set the request Referer. The following code shows an example of the player SDK settings:
// First, get the configuration
PlayerConfig config = aliPlayer.getConfig();
// Set the Referer. Example: http://example.aliyundoc.com. (Note: Include the protocol part when setting the Referer.)
config.mReferrer = referrer;
....// Other settings
// Set the configuration for the player
aliPlayer.setConfig(config);Set a User-Agent
The ApsaraVideo Player SDK for Android lets you use PlayerConfig to set the request User-Agent (UA). After you set it, the player includes the UA information in its requests. The following code is an example:
// First, get the configuration
PlayerConfig config = aliPlayer.getConfig();
// Set the UA
config.mUserAgent = "User-Agent to set";
....// Other settings
// Set the configuration for the player
aliPlayer.setConfig(config);Configure network retry time and count
You can use the PlayerConfig class to set the network timeout and retry count for the ApsaraVideo Player SDK for Android. The following code provides an example:
// First, get the configuration
PlayerConfig config = aliPlayer.getConfig();
// Set network timeout in milliseconds
config.mNetworkTimeout = 5000;
// Set number of retry attempts on timeout. Retry interval is networkTimeout. networkRetryCount=0 means no retries; retry policy is determined by the app. Default value is 2
config.mNetworkRetryCount=2;
....// Other settings
// Set the configuration for the player
aliPlayer.setConfig(config);If you set NetworkRetryCount and a network problem causes a loading state, the player retries NetworkRetryCount times. The interval for each retry is mNetworkTimeout.
If the player is still in a loading state after multiple retries, the
onErrorevent is called. In this case, ErrorInfo.getCode() returns ErrorCode.ERROR_LOADING_TIMEOUT.If NetworkRetryCount is set to 0 and the network connection times out, the player calls the
onInfoevent. For this event, InfoBean.getCode() returns InfoCode.NetworkRetry. At this point, you can call the player'sreloadmethod to reload the network or perform other processing.
Configure cache and latency control
The ApsaraVideo Player SDK for Android provides interfaces for setting cache and latency control through PlayerConfig. The following code is an example:
Set HTTP headers
Using the PlayerConfig method, you can add HTTP header parameters to the player's requests. The following code is an example:
// First, get the configuration
PlayerConfig config = aliPlayer.getConfig();
// Define the header
String[] headers = new String[1];
headers[0]="Host:example.com";// For example, to set Host in the header
// Set the header
config.setCustomHeaders(headers);
....// Other settings
// Set the configuration for the player
aliPlayer.setConfig(config);Picture-in-Picture (PiP)
For detailed code examples, see the PictureInPicture module in API-Example. This project is a Java-based example project for the ApsaraVideo Player SDK for Android to help you quickly integrate the core features of the SDK.
The procedure is as follows:
In the
AndroidManifest.xmlfile, declare the PiP permission.<activity android:name=".PictureInPictureActivity" android:exported="true" android:supportsPictureInPicture="true" android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation" />Switch the target
Activityto PiP mode.Rational aspectRatio = new Rational(16, 9); // PiP aspect ratio, adjustable based on your business needs PictureInPictureParams.Builder pipBuilder = new PictureInPictureParams.Builder(); pipBuilder.setAspectRatio(aspectRatio); enterPictureInPictureMode(pipBuilder.build());You can choose to trigger PiP mode from an OnClick event, when leaving the app, or when returning to the app. The implementation methods are as follows:
Triggered by OnClick
button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Rational aspectRatio = new Rational(16, 9); // PiP aspect ratio PictureInPictureParams.Builder pipBuilder = new PictureInPictureParams.Builder(); pipBuilder.setAspectRatio(aspectRatio); enterPictureInPictureMode(pipBuilder.build()); } });Triggered when leaving the app
@Override protected void onUserLeaveHint() { super.onUserLeaveHint(); Rational aspectRatio = new Rational(16, 9); // PiP aspect ratio PictureInPictureParams.Builder pipBuilder = new PictureInPictureParams.Builder(); pipBuilder.setAspectRatio(aspectRatio); enterPictureInPictureMode(pipBuilder.build()); Log.e(TAG, "PiP onUserLeaveHint"); }Triggered when returning to the app
@Override public void onBackPressed() { super.onBackPressed(); // Triggered from back press enterPictureInPictureMode(); }Handle the UI for showing and hiding the PiP window.
@Override public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) { super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig); if (isInPictureInPictureMode) { // Handling when entering PiP mode // hide UI Log.e(TAG, "Entering PiP mode"); } else { // Handling when exiting PiP mode // show UI Log.e(TAG, "Exiting PiP mode"); } }
Live RTS fallback
For detailed code examples, see the RtsLiveStream module in API-Example. This project is a Java-based example project for the ApsaraVideo Player SDK for Android to help you quickly integrate the core features of the SDK.
For more information, see RTS live streaming.
Switch between left and right sound channels
The ApsaraVideo Player SDK for Android uses the setOutputAudioChannel method to set the output sound channel. If the input source is dual-channel, you can use the following method to switch to the left or right channel. If the input source is single-channel, this setting has no effect.
The output sound channel setting affects both audio rendering and PCM data callbacks.
/*
OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_LEFT: Switch to left channel for playback,
OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_RIGHT: Switch to right channel for playback,
OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_NONE: Do not switch channels, keep input source channel for playback
*/
aliPlayer.setOutputAudioChannel();Parse audio streams
Set a listener to obtain audio and video stream data. This feature does not support encrypted streams because they cannot be parsed.
Set the video background color
The ApsaraVideo Player SDK for Android supports setting the background color for player rendering. The API operation and usage instructions are as follows:
API operation example
/**
* Sets the video background color.
*
* @param color ARGB
*
*/
abstract public void setVideoBackgroundColor(int color);Usage instructions
// Parameter is 8-digit hexadecimal data. The 8 digits are grouped in pairs, representing A (alpha transparency), R (red), G (green), and B (blue) in order
// For example, 0x0000ff00 represents green
aliPlayer.setVideoBackgroundColor(0x0000ff00);Specify a playback domain name for VidAuth
You can use the VidAuth method to specify fields such as the domain name that corresponds to a VID. For more information about the supported fields, see GetPlayInfo request parameters. The API operation and usage instructions are as follows:
API operation example
/**
* Sets playback parameters.
*
* @param playConfig Playback parameters
*/
public void setPlayConfig(VidPlayerConfigGen playConfig);Usage instructions
You can use the addPlayerConfig method of the VidPlayerConfigGen interface to add the playDomain field.
vidAuth = new VidAuth();
VidPlayerConfigGen configGen = new VidPlayerConfigGen();
// Add playDomain field. For more information about fields that can be added, see
// https://www.alibabacloud.com/help/en/vod/developer-reference/api-vod-2017-03-21-getplayinfo
configGen.addPlayerConfig("playDomain", "com.xxx.xxx");
vidAuth.setPlayConfig(configGen);H.266 decoding plug-in
H.266 (VVC/Versatile Video Coding) is the next-generation video encoding standard that can significantly save bitrate while maintaining the same image quality. To optimize performance and control the size of the main SDK, the H.266 value-added decoding capability is independently encapsulated as a plug-in, which supports on-demand integration.
Prerequisites
The ApsaraVideo Player SDK or All-in-One SDK is version 7.6.0 or later.
You have obtained a Professional Edition license. For more information, see Obtain a license for ApsaraVideo Player SDK.
The ApsaraVideo Player with the H.266 decoding plug-in supports only H.266 videos that are transcoded by Alibaba Cloud Transcoding.
Integrate the plug-in
Activate the plug-in
Starting from ApsaraVideo Player SDK V7.7.0 for Android, the plug-in is enabled by default after integration and does not need to be manually activated.
AliPlayerGlobalSettings.enableCodecPlugin("vvc", true);Related error codes
For error codes related to the H.266 decoding plug-in, see Common FAQ for players on different clients.
Auto-refresh the playback source
Enabling the playback source auto-refresh feature prevents playback interruptions caused by authentication expiration. This feature triggers a listener when the source becomes invalid and obtains a new playback address, ensuring continuous and smooth video playback.
Prerequisites
The ApsaraVideo Player SDK or All-in-One SDK is version 7.9.0 or later.
You are using a VidAuth source for playback or your business has configured URL signing.
VidAuth source
API operation example
/**
* Sets the listener for VidAuth source expiration events.
*
* This feature enables automated VidAuth source refresh to avoid playback interruptions
* caused by expiration. When the listener is triggered, you can refresh the VidAuth source
* and return the updated VidAuth using {@link SourceRefreshCallback#onSuccess}.
*
* @param listener The interface for listening to VidAuth source expiration events. See {@link OnVidAuthExpiredListener}.
*
*/
abstract public void setOnVidAuthExpiredListener(OnVidAuthExpiredListener listener);Feature components
UrlSource source
API operation example
/**
* Sets the listener for URL source expiration events.
*
* This feature enables URL refresh to avoid playback interruptions caused by
* URL expiration due to authentication. When the listener is triggered,
* you can refresh the URL source and return the updated URL source using {@link SourceRefreshCallback#onSuccess}.
*
* @param listener Listener for handling URL source expiration events. See {@link OnURLSourceExpiredListener}.
*
* <p>For more information on configuring URL authentication, see
* <a href="https://www.alibabacloud.com/help/zh/vod/user-guide/configure-url-signing?spm=a2c4g.11186623.0.0.560c4140fGh8MW">URL authentication documentation</a>.</p>
*/
abstract public void setOnURLSourceExpiredListener(OnURLSourceExpiredListener listener);Feature components
Additional utility functions
The following example uses Type A signing.
Performance
Set the playback scenario
Setting the playback scenario automatically configures the optimal parameters (including buffer settings, feature switches, etc.) for that scenario. It is also compatible with custom parameter settings made through the setConfig interface (custom settings take precedence).
After you set the playback scenario, you can use the
getConfiginterface to view the parameter configurations.
API operation example
/**
* Sets the player scene.
*
* @param scene
*/
abstract public void setPlayerScene(PlayerScene scene);Playback scenarios
public enum PlayerScene {
/**
* No scene
*/
NONE,
/**
* Long video scene: applies to videos longer than 30 minutes
*/
LONG,
/**
* Medium video scene: applies to videos between 5 and 30 minutes
*/
MEDIUM,
/**
* Short video scene: applies to videos between 0 seconds and 5 minutes
*/
SHORT,
/**
* Live streaming scene
*/
LIVE,
/**
* RTS live scene
*/
RTS_LIVE
}Usage instructions
// Set short video scene
aliPlayer.setPlayerScene(PlayerScene.SHORT)
// Set medium video scene
aliPlayer.setPlayerScene(PlayerScene.MEDIUM)
// Set long video scene
aliPlayer.setPlayerScene(PlayerScene.LONG)
// Set live streaming scene
aliPlayer.setPlayerScene(PlayerScene.LIVE)Pre-rendering
The ApsaraVideo Player SDK for Android supports quickly rendering the first frame before playback starts, which can improve the startup speed.
This feature is disabled by default.
Enabling this feature affects the trigger order of the preparation success and first frame rendering callbacks. When disabled, the preparation success callback is triggered before the first frame rendering callback. When enabled, the first frame rendering callback may be triggered before the preparation success callback due to different decoding and rendering speeds, but this does not affect playback.
For example:
aliPlayer.setOption(ALLOW_PRE_RENDER, 1);Local cache
For detailed code examples, see the Preload module in API-Example. This project is a Java-based example project for the ApsaraVideo Player SDK for Android to help you quickly integrate the core features of the SDK.
The ApsaraVideo Player SDK for Android provides a local cache feature. This feature improves startup speed, seek speed, and reduces stuttering when users replay videos, while it also saves traffic.
Enable local cache
The local cache feature is disabled by default. To use it, you must enable it manually. This is controlled by AliPlayerGlobalSettings through enableLocalCache. The following code is an example:
If the video playback URL has authentication parameters, the authentication parameters change during local caching and playback. To improve the cache hit ratio for the same URL with different authentications, you can remove the authentication parameters from the URL before you calculate the hash value (for example, MD5) through the
setCacheUrlHashCallbackinterface. For example, if the video playback URL with authentication parameters ishttp://****.mp4?aaa, usehttp://****.mp4to calculate the hash value when loading. However, if the video is an encrypted m3u8 video and its keyURL is processed by removing the authentication parameters before the hash value is calculated, the cache of different videos may hit the same key, which leads to playback failure. Solution: In the callback ofsetCacheUrlHashCallback, you can perform a domain name check and remove the authentication parameters only for the playback domain (http(s)://xxxxx.m3u8?aaaa), and not remove them for the domain that corresponds to the keyURL (http(s)://yyyyy?bbbb).
If the server supports both HTTP and HTTPS protocols, but different protocols point to the same media file, you can remove or unify the request headers before you calculate the hash value. For example:
If the video playback URLs are
https://****.mp4andhttp://****.mp4, use****.mp4to calculate the hash value when loading.If the video playback URL is
https://****.mp4, unify it tohttp://****.mp4before you calculate the hash value.
For player SDK versions 5.5.4.0 and later, if the video playback URL has authentication parameters and the playback protocol is HLS, you can set the
PlayerConfig.mEnableStrictAuthModefield to select different authentication modes (the default value is false for versions 5.5.4.0 to 6.21.0. The default value is true for versions 7.0.0 and later):Non-strict authentication (false): Authentication is also cached. If only part of the media was cached last time, the player uses the cached authentication to make a request when playing the non-cached part next time. If the validity period of the URL authentication is very short, it causes playback exceptions.
Strict authentication (true): Authentication is not cached. Authentication is performed every time playback starts. This causes playback to fail without a network connection.
Enable or disable local cache for a single URL
If you want to enable or disable the local cache feature for a single URL, you can set it in the PlayerConfig.
// First, get the configuration
PlayerConfig config = aliPlayer.getConfig();
// Whether to enable local cache for the playback URL. The default value is true. When the local cache in AliPlayerGlobalSettings is enabled, and the local cache here is also enabled (set to true), the local cache for this URL will take effect. If set to false here, the local cache for this URL is disabled.
config.mEnableLocalCache = false;
....// Other settings
// Set the configuration for the player
aliPlayer.setConfig(config);Preload
The ApsaraVideo Player SDK for Android provides a preload feature, which is an upgrade to the local cache feature. By setting the memory size for video caching, you can further improve the startup speed of videos.
The limits of the preload feature are as follows:
It currently supports loading single media files such as MP4, MP3, FLV, and HLS.
The ApsaraVideo Player SDK for Android provides an automatic network resource scheduling capability for preloading by default. This reduces the impact of preloading network requests on the network requests of the video being played. The automatic scheduling policy works as follows: preloading is allowed to make requests only after the buffer of the currently playing video reaches a certain threshold. To control the real-time requests for preloading yourself, you can disable this policy using the following method:
AliPlayerGlobalSettings.enableNetworkBalance(false);Enable the local cache feature. For more information, see Local cache.
Set the data source.
VidAuth (recommended)
VidAuth vidAuth = new VidAuth(); vidAuth.setVid("Vid information");// Required. The video ID (VideoId). vidAuth.setPlayAuth("<yourPlayAuth>");// Required. The playback credential, which needs to be generated by calling the GetVideoPlayAuth API operation of ApsaraVideo VOD. vidAuth.setRegion("Access region");// For player SDK V5.5.5.0 and later, this parameter is deprecated. You do not need to set the region, as the player will automatically parse it. For player SDK versions earlier than 5.5.5.0, this parameter is required. It is the access region of ApsaraVideo VOD, which defaults to cn-shanghai. vidAuth.setQuality("Selected definition") //"AUTO" represents adaptive bitrateVidSts
VidSts vidSts = new VidSts(); vidSts.setVid("Vid information");// Required. The video ID (VideoId). vidSts.setAccessKeyId("<yourAccessKeyId>");// Required. The AccessKey ID of the temporary STS token, which needs to be generated by calling the AssumeRole API operation of STS. vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required. The AccessKey secret of the temporary STS token, which needs to be generated by calling the AssumeRole API operation of STS. vidSts.setSecurityToken("<yourSecurityToken>");// Required. The STS security token, which needs to be generated by calling the AssumeRole API operation of STS. vidSts.setRegion("Access region");// Required. The access region of ApsaraVideo VOD, which defaults to cn-shanghai. vidSts.setQuality("Selected definition") //"AUTO" represents adaptive bitrateUrlSource
UrlSource urlSource = new UrlSource(); urlSource.setUri("Playback URL");// Required. The playback URL, which can be a third-party VOD URL or a playback URL in ApsaraVideo VOD.Set task parameters.
NoteThis applies only to multi-bitrate videos. You can choose one of
setDefaultBandWidth,setDefaultResolution, orsetDefaultQuality.PreloadConfig preloadConfig = new PreloadConfig(); // Set the preload bitrate for multi-bitrate streams preloadConfig.setDefaultBandWidth(400000); // Set the preload resolution for multi-bitrate streams preloadConfig.setDefaultResolution(640 * 480); // Set the preload quality for multi-bitrate streams preloadConfig.setDefaultQuality(“FD”); // Set the preload duration preloadConfig.setDuration(1000);Add a task listener.
Build the task and add it to the
MediaLoaderV2instance to start preloading.VidAuth (recommended)
// Build the preload task PreloadTask mPreloadTask = new PreloadTask(vidAuth, preloadConfig); // Get the MediaLoaderV2 instance MediaLoaderV2 mediaLoaderV2 = MediaLoaderV2.getInstance(); // Add the task and start preloading String taskId = mediaLoaderV2.addTask(mPreloadTask, PreloadListenerImpl)VidSts
// Build the preload task PreloadTask mPreloadTask = new PreloadTask(vidSts, preloadConfig); // Get the MediaLoaderV2 instance MediaLoaderV2 mediaLoaderV2 = MediaLoaderV2.getInstance(); // Add the task and start preloading String taskId = mediaLoaderV2.addTask(mPreloadTask, PreloadListenerImpl);UrlSource
// Build the preload task PreloadTask mPreloadTask = new PreloadTask(urlSource, preloadConfig); // Get the MediaLoaderV2 instance MediaLoaderV2 mediaLoaderV2 = MediaLoaderV2.getInstance(); // Add the task and start preloading String taskId = mediaLoaderV2.addTask(mPreloadTask, PreloadListenerImpl)Optional: Manage tasks.
mediaLoaderV2.cancelTask(taskId);// Cancel the preload task with the specified task ID mediaLoaderV2.pauseTask(taskId);// Pause the preload task with the specified task ID mediaLoaderV2.resumeTask(taskId);// Resume the preload task with the specified task IDOptional: Delete loaded files.
You can delete loaded files as needed to save space. The ApsaraVideo Player SDK for Android does not provide a deletion interface. You need to delete the files in the loading directory of the app.
Dynamic preload
The dynamic preload strategy allows integrators to control both the cache of the currently playing video and the number and cache of preloaded items. This helps businesses balance playback experience with cost.
Preload multi-bitrate HLS videos
In the listPlayer + multi-bitrate HLS video playback scenario, integrators can preload a stream with the same definition as the currently playing video. They can also choose the preload mode based on their business needs.
Get the download speed
You can obtain the download speed of the currently playing video from the onInfo callback using the getExtraValue API operation. The following code is an example:
aliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
@Override
public void onInfo(InfoBean infoBean) {
if(infoBean.getCode() == InfoCode.CurrentDownloadSpeed){
// Current download speed
long extraValue = infoBean.getExtraValue();
}
}
});Network features
HTTPDNS
HTTPDNS sends domain name resolution requests to a specific HTTPDNS server to obtain faster and more stable domain name resolution results, which reduces the risk of DNS hijacking.
The ApsaraVideo Player SDK provides an enhanced HTTPDNS feature that offers HTTPDNS services specifically for Alibaba Cloud CDN domain names. It supports precise scheduling and real-time resolution for the Alibaba Cloud CDN network, which effectively improves network performance.
Enhanced HTTPDNS example
Enhanced HTTPDNS provides HTTPDNS services only for Alibaba Cloud CDN domain names. Ensure that the domain name you configure is an Alibaba Cloud CDN domain name and that the domain name configuration is complete and ready for use. For more information about how to add and configure a CDN domain name in ApsaraVideo VOD, see Add an accelerated domain name. For more information about CDN domain names, see Alibaba Cloud CDN.
// Enable enhanced HTTPDNS
AliPlayerGlobalSettings.enableEnhancedHttpDns(true);
// Optional: Add a domain name for HTTPDNS pre-resolution
DomainProcessor.getInstance().addPreResolveDomain("player.***alicdn.com");HTTP/2
The ApsaraVideo Player SDK for Android has enabled HTTP/2 by default since version 5.5.0.0.
The ApsaraVideo Player SDK for Android supports using the HTTP/2 protocol. This protocol improves playback performance through multiplexing, which avoids head-of-line blocking. The following code is an example:
AliPlayerGlobalSettings.setUseHttp2(true);Pre-establish TCP connections for HTTP
For HTTP video playback requests (not HTTPS), pre-establishing a TCP connection can significantly improve the user experience, reduce network connection time, ensure immediate and continuous playback, and optimize the use of network and system resources. The usage is as follows:
// The domain format is host[:port], where port is optional. Use a semicolon (;) to separate multiple domain names
// Global settings
// The full interface uses the current string as the standard for each setting (more - add, less - delete). An empty string stops pre-connection
AliPlayerGlobalSettings.setOption(AliPlayerGlobalSettings.SET_PRE_CONNECT_DOMAIN, "domain1;domain2");Video download
For detailed code examples, see the Download module in API-Example. This project is a Java-based example project for the ApsaraVideo Player SDK for Android to help you quickly integrate the core features of the SDK.
The ApsaraVideo Player SDK for Android provides a video download feature for ApsaraVideo VOD. This allows users to cache videos locally to be viewed offline using ApsaraVideo Player. It also offers two download methods: normal download and secure download.
Normal download
The downloaded video data is not encrypted by Alibaba Cloud. Users can play it with a third-party player.
Secure download
The downloaded video data is encrypted by Alibaba Cloud. Third-party players cannot play it. It can be played only using the ApsaraVideo Player.
Instructions
The video download feature is supported only for VidSts and VidAuth methods.
To use the player's video download feature, you need to enable and configure the download mode in the ApsaraVideo VOD console. For more information, see Offline download.
Video download supports resumable downloads.
Procedure
Optional: Configure the encryption file for secure download. This is required only for secure download, not for normal download.
NoteEnsure that the configured encryption file is consistent with the app information. Otherwise, the video download fails.
If you set the download method to secure download, you need to configure the player SDK with the key file generated in the ApsaraVideo VOD console. This is used for decryption and verification during video download and playback. For more information about how to generate the key file, see Enable secure download.
We recommend that you configure this once in the Application class. The following code is an example:
PrivateService.initService(getApplicationContext(), "File path where encryptedApp.dat is located"); // We recommend storing the encryptedApp.dat file on the phone and then setting the local file path of the encryption file hereCreate and set up the downloader.
You can create a downloader using AliDownloaderFactory. The following code is an example:
AliMediaDownloader mAliDownloader = null; ...... // Create the downloader mAliDownloader = AliDownloaderFactory.create(getApplicationContext()); // Configure the save path for the download mAliDownloader.setSaveDir("Save folder address");Set listeners.
The downloader provides multiple event listeners. The following code is an example:
Prepare the download source.
You can use the
preparemethod to prepare the download source. The download source supports VidSts and VidAuth methods. The following code is an example:VidSts
// Create a VidSts object. VidSts aliyunVidSts = new VidSts(); aliyunVidSts.setVid("your_video_id"); // The video ID. aliyunVidSts.setAccessKeyId("<yourAccessKeyId>"); // The AccessKey ID of the temporary STS token. To obtain the token, you must call the AssumeRole operation of STS. aliyunVidSts.setAccessKeySecret("<yourAccessKeySecret>"); // The AccessKey secret of the temporary STS token. To obtain the token, you must call the AssumeRole operation of STS. aliyunVidSts.setSecurityToken("<yourSecurityToken>"); // The security token. To obtain the token, you must call the AssumeRole operation of STS. aliyunVidSts.setRegion("your_region_id"); // The ID of the region where VOD is activated. Default value: cn-shanghai. // If you enabled HLS encryption with parameter pass-through in the VOD console and the default parameter name is MtsHlsUriToken, you must set the config parameter and pass it to the VidSts object. For more information, see the following code. // If you did not enable HLS encryption with parameter pass-through in the VOD console, you do not need to integrate the following code. VidPlayerConfigGen vidConfig = new VidPlayerConfigGen(); vidConfig.setMtsHlsUriToken("<yourMtsHlsUriToken>"); aliyunVidSts.setPlayerConfig(vidConfig); // Prepare the download source. mAliDownloader.prepare(aliyunVidSts);VidAuth
// Create a VidAuth object. VidAuth vidAuth = new VidAuth(); vidAuth.setVid("Your Video ID");// The video ID (VideoId). vidAuth.setPlayAuth("<yourPlayAuth>");// The playback credential. You must call the GetVideoPlayAuth operation of the VOD service to generate the credential. vidAuth.setRegion("The region");// For player SDKs V5.5.5.0 and later, this parameter is deprecated. You do not need to set the region because the player automatically parses the region. For player SDKs earlier than V5.5.5.0, this parameter is required. It specifies the region where the VOD service is activated. The default value is cn-shanghai. // If you enable pass-through of HLS encryption parameters in the VOD console and the default parameter name is MtsHlsUriToken, you must set the config and pass it to the VidAuth object. For more information, see the following code. VidPlayerConfigGen vidConfig = new VidPlayerConfigGen(); vidConfig.setMtsHlsUriToken("<yourMtsHlsUriToken>"); vidAuth.setPlayerConfig(vidConfig); // Prepare the download source. mAliDownloader.prepare(vidAuth);
NoteThe source file format and the output download file format are the same and cannot be changed.
If you enable HLS standard encryption parameter pass-through in the VOD console, the default parameter name is MtsHIsUriToken. For more information, see HLS standard encryption parameter pass-through. In this case, you must set the MtsHIsUriToken value in the VOD source as shown in the code above.
After the preparation is successful, select a download item and start the download.
After the preparation is successful, the
OnPreparedListenermethod is called. The returned TrackInfo object contains information such as the definition of each video stream. You can select a Track to download. The following code is an example:public void onPrepared(MediaInfo mediaInfo) { // Successfully prepared the download item List<TrackInfo> trackInfos = mediaInfo.getTrackInfos(); // For example, download the first TrackInfo mAliDownloader.selectItem(trackInfos.get(0).getIndex()); // Start the download mAliDownloader.start(); }(Optional) Update the download source.
To prevent VidSts and VidAuth from expiring, you can also update the download source information before you start the download. The following code is an example:
// Update the download source mAliDownloader.updateSource(VidSts); // Start the download mAliDownloader.start();After the download succeeds or fails, release the downloader.
After the download is complete, you can call
releasein theonCompletionoronErrorcallback to release the downloader. The following code is an example:mAliDownloader.stop(); mAliDownloader.release();Optional: Delete the downloaded files.
During or after the download, you can delete the downloaded files. The following code is an example:
// Delete the file through the object mAliDownloader.deleteFile(); // Delete through a static method. If successful, it returns 0 AliDownloaderFactory.deleteFile("Path of the download folder to be deleted", "Video ID", "Video format", "Index of the downloaded video");
What to do next
The downloaded video can be played using the ApsaraVideo Player. The method is as follows:
After the download is complete, obtain the absolute path of the video file.
String path = mAliDownloader.getFilePath();Set the absolute path for playback using the UrlSource method.
UrlSource urlSource = new UrlSource(); urlSource.setUri("Playback URL");// Set the absolute path of the downloaded video aliPlayer.setDataSource(urlSource);
Encrypted video playback
ApsaraVideo VOD supports HLS encryption, Alibaba Cloud proprietary cryptography, and DRM encryption. Live streaming supports only DRM encryption. For more information about encrypted playback, see Encrypted video playback.
Native RTS playback
The ApsaraVideo Player SDK for Android integrates the Native RTS SDK to implement the native low-latency live streaming feature. For more information, see Implement RTS stream pulling on Android.