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.
You can 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, which improves the user experience.
Better animation quality: MP4 videos can retain the original animation quality, including details and colors. Compared to other formats such as APNG or IXD, MP4 can more accurately restore the animation effects created by designers.
Smaller file size: MP4 video files can be more effectively compressed than other formats such as APNG or IXD. This improves loading speed and reduces network bandwidth consumption.
Higher compatibility: MP4 is a universal video format that is widely supported on various devices and browsers. This ensures that gift effects can be played and viewed on mainstream devices.
Higher development efficiency: The technical solution for using MP4 videos as gift effects is relatively simple. Developers do not need to research and implement complex parsing and rendering logic. This allows developers 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.
The following code is an example:
Create a view to display subtitles.
You can create different views for different subtitle formats.
When you integrate player V7.6.0 or later and use
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.
ImportantThe subtitle file must be set in
onPrepared.mAliPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() { @Override public void onPrepared() { // Set subtitles (must be set in onPrepared). mAliPlayer.addExtSubtitle(EXT_SUBTITLE_URL); } });Set subtitle-related listeners.
Audio-only playback
You can disable video playback to play only the audio. You must configure PlayerConfig before you prepare the player.
PlayerConfig config = aliPlayer.getConfig();
config.mDisableVideo = true; // Enable audio-only playback.
aliPlayer.setConfig(config);Switch between software and hardware decoding
The decoding method must be switched before playback starts. Switching the decoding method during playback does not take 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. This is 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 on 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 is automatically played. 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 combined with cloud and client capabilities. You must submit a ticket to apply for a license.
The value-added service for adaptive decoding combined with cloud and client capabilities mainly includes: 1. Dynamic delivery of cloud-based hardware decoding compatibility data. 2. Adaptive fallback from H.265 streams to H.264 streams.
The SDK can still automatically switch to software decoding when hardware decoding fails, even if the value-added service is not enabled.
The following code shows how to set a backup stream:
// The application layer maintains a Map that stores all key-value pairs of original URL-backup URL. When switching, the backup URL is queried 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 result of the switch is returned in 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 the reason for the failure 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. The following code is an example: 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.
PlayerConfig config = aliPlayer.getConfig();
config.mMaxAllowedAbrVideoPixelNumber = 921600; // Set the upper limit of the pixel count for ABR definition to 921600 (width × height = 1280 × 720), so that the pixel count of the definition that ABR can switch to is less than or equal to this value.
aliPlayer.setConfig(config);Take snapshots
The ApsaraVideo Player SDK for Android provides a snapshot feature to take a snapshot of the current video. This feature is implemented by the snapshot API operation. It captures the raw data and returns it as a bitmap. The callback interface is OnSnapShotListener. The following code is an example:
// Set the snapshot callback.
aliPlayer.setOnSnapShotListener(new OnSnapShotListener(){
@Override
public void onSnapShot(Bitmap bm, int with, int height){
// The obtained bitmap and the width and height of the image.
}
});
// Take a snapshot of the 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, you can 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 the playback source
...When the preview duration is set, the server does not return the full video content when playing the video 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: When setting the Referer, you need to include the protocol part at the beginning.)
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 = "The User-Agent to be 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 the network timeout in milliseconds.
config.mNetworkTimeout = 5000;
// Set the number of retry attempts on timeout. The interval for each retry is networkTimeout. networkRetryCount=0 means no retries, and the retry policy is determined by the app. The 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 the 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); // The aspect ratio of the PiP window, which can be adjusted as needed. 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); // The aspect ratio of the PiP window. 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); // The aspect ratio of the PiP window. 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 the left channel for playback.
OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_RIGHT: Switch to the right channel for playback.
OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_NONE: Do not switch channels, keep the input source channel for playback.
*/
aliPlayer.setOutputAudioChannel();Parse audio streams
You can set a listener to obtain audio and video stream data. The audio and video cannot be encrypted streams because encrypted streams 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
// The parameter is 8-bit hexadecimal data. The 8 bits 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 the playDomain field. For more information about the 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 it maintains 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 V7.6.0 or later.
A Professional Edition license has been obtained. For more information, see Obtain a license for ApsaraVideo Player SDK.
The ApsaraVideo Player with the H.266 decoding plug-in supports only playing H.266 videos 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 that are caused by authentication expiration. This feature triggers a listener when the source becomes invalid and obtains a new playback address, which ensures continuous and smooth video playback.
Prerequisites
The ApsaraVideo Player SDK or All-in-One SDK is V7.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/en/vod/user-guide/configure-url-signing">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 The 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 the short video scene.
aliPlayer.setPlayerScene(PlayerScene.SHORT)
// Set the medium video scene.
aliPlayer.setPlayerScene(PlayerScene.MEDIUM)
// Set the long video scene.
aliPlayer.setPlayerScene(PlayerScene.LONG)
// Set the 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.
The following code is an 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 enableLocalCache in AliPlayerGlobalSettings. 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 player config.
// 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 bitrate.VidSts
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 bitrate.UrlSource
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 ID.Optional: 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 in the onInfo callback. This is done 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:
// We recommend storing the encryptedApp.dat file on the phone and then setting the local file path of the encryption file here. PrivateService.initService(getApplicationContext(), "File path where encryptedApp.dat is located");Create 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 VidSts. VidSts aliyunVidSts = new VidSts(); aliyunVidSts.setVid("Vid information"); // The video ID (VideoId). aliyunVidSts.setAccessKeyId("<yourAccessKeyId>"); // The AccessKey ID of the temporary STS token, which needs to be generated by calling the AssumeRole API operation of STS. aliyunVidSts.setAccessKeySecret("<yourAccessKeySecret>"); // The AccessKey secret of the temporary STS token, which needs to be generated by calling the AssumeRole API operation of STS. aliyunVidSts.setSecurityToken("<yourSecurityToken>"); // The STS security token, which needs to be generated by calling the AssumeRole API operation of STS. aliyunVidSts.setRegion("Access region"); // The access region of ApsaraVideo VOD, which defaults to cn-shanghai. // If you have enabled HLS standard encryption parameter pass-through in the VOD console, and the default parameter name is MtsHlsUriToken, you need to set the config and pass it into the vid, as shown below. // If you have not enabled HLS standard encryption 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(config); // Prepare the download source. mAliDownloader.prepare(aliyunVidSts)VidAuth
// Create VidAuth. VidAuth vidAuth = new VidAuth(); vidAuth.setVid("Vid information"); // The video ID (VideoId). vidAuth.setPlayAuth("<yourPlayAuth>"); // 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. // If you have enabled HLS standard encryption parameter pass-through in the VOD console, and the default parameter name is MtsHlsUriToken, you need to set the config and pass it into the vid, as shown below. VidPlayerConfigGen vidConfig = new VidPlayerConfigGen(); vidConfig.setMtsHlsUriToken("<yourMtsHlsUriToken>"); vidAuth.setPlayerConfig(config); // 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 back. 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.