This topic describes the advanced features of ApsaraVideo Player SDK for Android and provides sample code. For more information about other features, see API operations for ApsaraVideo Player SDK for Android.
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 features such as preloading to minimize the startup time of short videos. We recommend that you do not enable this feature for long videos.
Play videos that have transparency configurations
Description
ApsaraVideo Player SDK supports rendering of videos with alpha channels to play dynamic gift videos with a transparent background. This way, you can view the dynamic effects of gifts without blocking the live video content when someone is streaming. This significantly improves the viewing and interactive experience.
Limits
You can use ApsaraVideo MediaBox SDK V6.8.0 or later and ApsaraVideo Player SDK V6.9.0 or later to render videos with transparency.
Benefits
You can use MP4 videos with transparency to play dynamic gift videos with a transparent background. This improves the performance of dynamic effects and video compatibility, reduces the video size, and simplifies development. This also optimizes the viewing experience of gift effects and improves user experience. Using MP4 videos with transparency to play dynamic gift videos has the following benefits:
Higher video quality: You can use MP4 videos to display the dynamic gift effects in the original quality, such as the original image details and colors. Compared with other video formats such as APN or IXD, MP4 can display the dynamic effect in the original quality intended by the designers.
Smaller video size: Compared with other video formats such as APNG or IXD, MP4 reduces file sizes in a more efficient way. This accelerates loading and reduces the consumption of network bandwidth.
Better compatibility: MP4 is a general video format that is widely supported on various devices and browsers. You can play MP4 videos that are used as gift effects on mainstream devices.
Higher development efficiency: The solution of using MP4 videos as dynamic gift videos requires simple development. Instead of studying and developing complex parsing and rendering logic, developers can focus on the implementation of other features to improve development efficiency.
Configure external subtitles
ApsaraVideo Player SDK for Android allows you to add or switch external subtitles in the SRT, SSA, ASS, or VTT format for videos. Sample code:
Create a view that displays the subtitles.
You must create different views for subtitles in different formats.
Configure listeners for subtitles.
Add subtitles
mAliPlayer.addExtSubtitle(url);
Display or hide subtitles.
After you receive the
onSubtitleExtAdded
callback, you can use one of the following methods to display or hide subtitles://trackIndex: specifies whether to display subtitles. If the value is true, subtitles are displayed. If the value is false, subtitles are hidden. mAliPlayer.selectExtSubtitle(trackIndex, true);
Enable audio-only playback
You can disable the display capability for video images to enable audio-only playback. Before you call the prepare method, configure the PlayerConfig class.
PlayerConfig config = mAliPlayer.getConfig();
config.mDisableVideo = true; // Enable audio-only playback.
mAliPlayer.setConfig(config);
Switch between software decoding and hardware decoding
If you want to change the decoding method, change it before the playback starts. The change that is made during playback does not take effect.
ApsaraVideo Player SDK for Android supports hardware decoding based on the H.264 and H.265 standards. You can call enableHardwareDecoder
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. Sample code:
// Enable hardware decoding. Hardware decoding is enabled by default.
mAliyunVodPlayer.enableHardwareDecoder(true);
If hardware decoding is switched to software decoding, the onInfo
callback is invoked. Sample code:
mApsaraPlayerActivity.setOnInfoListener(new IPlayer.OnInfoListener() {
@Override
public void onInfo(InfoBean infoBean) {
if (infoBean.getCode() == InfoCode.SwitchToSoftwareVideoDecoder) {
// Switch to software decoding.
}
}
});
H.265 adaptive playback
If you have configured a secondary H.264 stream and hardware decoding of the H.265 stream fails, the system automatically plays the secondary H.264 stream. If you do not configure a secondary stream, soft decoding is automatically used for H.265 playback when hardware decoding fails.
This feature is available only after you enable adaptive playback. Adaptive playback is a value-added service. To activate value-added services, submit a request on Yida.
The adaptive playback service provides the following features: dynamic data issuing of hardware decoded data and automatic H.264 switching.
If you do not activate the adaptive playback service, the player SDK can still automatically use software decoding when hardware decoding fails.
The following sample code describes how to configure a secondary stream:
// Create a map on the application layer to store the primary stream URLs and secondary stream URLs as key-value pairs. The system queries the corresponding secondary URL based on the primary stream URL during switching.
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 "";
}
}
});
Enable adaptive bitrate streaming
You can transcode videos to HTTP Live Streaming (HLS) adaptive bitrate streams by using ApsaraVideo VOD transcoding template groups. For more information, see Implement adaptive bitrate streaming with ApsaraVideo VOD.
If you use Vid-based playback for adaptive bitrate streams that are transcoded by ApsaraVideo VOD, you must specify
AUTO
as the default playback definition. This way, the player can obtain and play adaptive bitrate streams. If you do not specify AUTO as the default playback definition, the player automatically plays video streams in low definition. For more information about the playback order based on video definitions, see FAQ about video resolution. The following sample code provides an example on how to specify the default playback definition for VidAuth-based playback:VidAuth vidAuth = new VidAuth(); List<Definition> list = new ArrayList<>(); list.add(Definition.DEFINITION_AUTO); vidAuth.setDefinition(list);
ApsaraVideo Player SDK for Android supports adaptive bitrate streaming of HLS or DASH video streams. After the prepare
method is called, call getMediaInfo
to obtain the bitrate information that is indicated by TrackInfo
. Sample code:
List<TrackInfo> trackInfos = aliyunVodPlayer.getMediaInfo().getTrackInfos();
During the playback, you can call the selectTrack
method to switch the bitrate. If you specify AUTO_SELECT_INDEX, adaptive bitrate streaming is enabled. Sample code:
int index = trackInfo.getIndex();
// Switch the bitrate.
aliyunVodPlayer.selectTrack(index);
// Enable adaptive bitrate streaming.
aliyunVodPlayer.selectTrack(TrackInfo.AUTO_SELECT_INDEX);
The switching result is returned in the OnTrackChangedListener
callback. You must configure the OnTrackChangedListener callback before you call the selectTrack
method. Sample code:
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
ApsaraVideo Player SDK for Android provides the 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 OnSnapShotListener
to obtain the bitmap. Sample code:
// Set 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 specific configurations of ApsaraVideo VOD to support video preview. 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.
After you enable the preview feature, you can call the VidPlayerConfigGen.setPreviewTime()
method to specify the preview duration. The following sample code provides an example on how to specify the preview duration for VidSts-based playback:
VidSts vidSts = new VidSts;
....
VidPlayerConfigGen configGen = new VidPlayerConfigGen();
configGen.setPreviewTime(20); // Set the preview duration to 20s.
vidSts.setPlayConfig(configGen); // Specify the video source.
...
After you specify the preview duration, ApsaraVideo Player SDK for Android generates a preview for the video that lasts for the specified duration instead of the entire video.
You can call VidPlayerConfigGen to configure 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
ApsaraVideo Player SDK for Android allows you to configure a blacklist for hardware decoding. If hardware decoding is not allowed for a device, you can use software decoding to prevent decoding failures. Sample code:
DeviceInfo deviceInfo = new DeviceInfo();
deviceInfo.model="Lenovo K320t";
AliPlayerFactory.addBlackDevice(BlackType.HW_Decode_H264 ,deviceInfo );
The blacklist becomes invalid after the application exits.
Set the referer
ApsaraVideo Player SDK for Android provides the 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. Sample code:
// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Set the referer. Example: http://example.aliyundoc.com. 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 header
ApsaraVideo Player SDK for Android provides the PlayerConfig
class for you to specify the request user agent. After you specify the user agent, the player includes the user agent information in its requests. Sample code:
// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Set 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 number of retries
ApsaraVideo Player SDK for Android provides the PlayerConfig
class for you to set the network timeout period and number of retries. Sample code:
// 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 NetworkTimeout parameter. The NetworkRetryCount parameter specifies the number of retries. A value of 0 indicates zero retry. The application determines the 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 NetworkRetryCount parameter to a value other than 0, the player retries playback when the player starts to load data due to a network error. The maximum number of retries is equal to the value of the NetworkRetryCount parameter. The retry interval is equal to the value of the NetworkTimeout parameter.
If loading persists after the maximum number of retries is reached, a callback is invoked by the
onError
method. In this case, the ErrorInfo.getCode() method returns ErrorCode.ERROR_LOADING_TIMEOUT.If you set the NetworkRetryCount parameter to 0, a callback is invoked by the
onInfo
method when a network timeout occurs. In this case, the InfoBean.getCode() 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.
Control the buffer and latency
ApsaraVideo Player SDK for Android provides the PlayerConfig
class for you to configure buffer and latency settings. Sample code:
Configure HTTP headers
ApsaraVideo Player SDK for Android provides the PlayerConfig
class for you to add HTTP headers to requests. Sample code:
// 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 an alternative RTS URL
Playback degradation is supported by Real-Time Streaming (RTS). You can specify an alternative RTS URL, such as a playback URL in the HLS or FLV format. If stream pulling over RTS fails, the video specified in this URL is automatically played. Sample code:
PlayerConfig config = player.getConfig();
// Optional. Configure playback degradation.
UrlSource urlSource = new UrlSource();
urlSource.setUri(downgradeUrl);
// Specify an alternative RTS URL.
player.enableDowngrade(urlSource, config);
Enable RTS playback degradation
If you enable the RTS playback degradation feature but your browser does not support RTS or stream pulling over RTS fails, the system automatically plays the stream over a degraded protocol. Sample code:
// 1 indicates that the RTS playback degradation feature is enabled and 0 indicates that the RTS playback degradation feature is disabled. The RTS playback degradation feature is enabled by default.
AliPlayerGlobalSettings.setOption(AliPlayerGlobalSettings.ALLOW_RTS_DEGRADE, 1);
Switch between left and right audio channels
outputAudioChannel
specifies the output audio channel. You can switch between the left and right audio channels only if the input file contains two audio channels. If the input file contains only one audio channel, the outputAudioChannel configuration is invalid.
The following output channel settings affect both audio rendering and PCM data callback.
/*
Specify OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_LEFT to use the left audio channel for playback.
Specify OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_RIGHT to use the right audio channel for playback.
Specify OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_NONE to use the audio channel settings of the input file.
*/
player.setOutputAudioChannel();
Parse audio streams
You can configure a listener to obtain information about audio and video streams. Encrypted audio and video streams cannot be parsed.
Set the background color of the player
ApsaraVideo Player SDK for Android provides a method for you to set the background color for player rendering. The following sample code provides examples on how to declare and call the method:
Declare the method
/**
* Set the background color of the video.
*
* @param color ARGB
*
*/
/****
* Set video background color
* @param color ARGB
*/
abstract public void setVideoBackgroundColor(int color);
Call the method
// The parameter value is an eight-digit hexadecimal ARGB color value. The first two digits of an eight-digit ARGB color value represent alpha, the next two represent red, the next two represent green, and the last two represent blue.
// For example, a value of 0x0000ff00 specifies green.
player.setVideoBackgroundColor(0x0000ff00);
Specify a domain name for vidAuth-based playback
You can specify parameters such as the domain name when you use vidAuth for playback. For more information about the parameters, see GetPlayInfo. The following content describes how to specify a domain name for vidAuth-based playback and provides sample code:
Sample code
/**
* Specify the playback parameters.
*
* @param playConfig The playback parameters.
*/
public void setPlayConfig(VidPlayerConfigGen playConfig);
Usage notes
Specify the playDomain parameter when you call addPlayerConfig in VidPlayerConfigGen.
vidAuth = new VidAuth();
VidPlayerConfigGen configGen = new VidPlayerConfigGen();
// Specify the playDomain parameter. For more information, visit https://www.alibabacloud.com/help/en/vod/developer-reference/api-vod-2017-03-21-getplayinfo.
//https://www.alibabacloud.com/help/zh/vod/developer-reference/api-vod-2017-03-21-getplayinfo
configGen.addPlayerConfig("playDomain", "com.xxx.xxx");
vidAuth.setPlayConfig(configGen);
Configure the performance
Configure pre-rendering
ApsaraVideo Player SDK for Android supports pre-rendering of the first frame before the playback starts. Sample code:
player.setOption(ALLOW_PRE_RENDER, 1);
Configure local caching
ApsaraVideo Player SDK for Android allows you to cache videos during playback. This reduces the startup loading time, accelerates the seeking process, reduces playback latency, and reduces traffic consumption during loop playback.
Enable local caching
By default, the local caching feature is disabled. To use this feature, you must enable it. You can call enableLocalCache
in the AliPlayerGlobalSettings
class to enable the local caching feature. Sample code:
If the playback URL of a video file contains authentication parameters, the values of the authentication parameters change during the local caching and playback of the video file. You can call the
setCacheUrlHashCallback
operation to calculate the MD5 hash value after you remove the authentication parameters. For example,http://****.mp4?aaa
is the playback URL of a video file that contains authentication parameters. In this case, the URLhttp://****.mp4
is used to calculate the MD5 hash value when the video file is loaded. However, if you calculate the MD5 hash value after you remove the authentication parameters in the key URL of an encrypted M3U8 video, the playback fails because different videos are hit by the same key URL. Solution: Remove the authentication parameters only from the playback URLhttp(s)://xxxxx.m3u8?aaaa
but not the key URLhttp(s)://yyyyy?bbbb
in thesetCacheUrlHashCallback
callback.If your server supports HTTP and HTTPS and a video file can be specified by using two URLs with the same elements but different protocols, you can remove the protocol headers of the URLs or use either the HTTP or HTTPS protocol to calculate the MD5 hash value. Examples:
If the playback URLs of a video file are
https://****.mp4
andhttp://****.mp4
, the MD5 hash value is calculated by using****.mp4
when the video file is loaded.If the playback URL of the video file is
https://****.mp4
, the MD5 hash value is calculated by using the URLhttp://****.mp4
when the video file is loaded.
For ApsaraVideo Player SDK V5.5.4.0 or later, if you want to play an HLS stream whose playback URL contains authentication parameters, configure
PlayerConfig.mEnableStrictAuthMode
to specify the authentication mode. By default, PlayerConfig.mEnableStrictAuthMode is set to false. Valid values of PlayerConfig.mEnableStrictAuthMode:false: caches the video content and performs authentication. If a video is not completely cached, the player sends a URL signing request by using the authentication information about the cached content when you play the uncached video content. If the validity period of the signed URL is too short, playback errors occur.
true: performs authentication and does not cache video content. URL signing is required for every playback. No network connections lead to playback failures.
Enable or disable local caching for a single URL
You can enable or disable local caching for a single URL in player config
.
// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Configure whether to enable local caching for the playback URL. Default value: true. Local caching for the URL takes effect only when local caching is enabled in AliPlayerGlobalSettings and the value of this parameter is true. If the value of this parameter is false, the local caching for the URL is disabled.
config.mEnableLocalCache = false;
....// Configure other settings.
// Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);
Use the default cache path
The following sample code describes how to configure AliPlayerGlobalSettings
to use the default cache path.
/**
* Enable local caching. After this feature is enabled, a media file is cached on your device.
* @param enable true: enables local caching. false: disables local caching. Default value: false.
*/
/****
* Enable local cache. When enabled, it will be cached in local files.
* @param enable true: enables the local cache. false: disable. This function is disabled by default.
* @param context The context.
*/
public static String enableLocalCache(boolean enable, Context context)
Configure large cache
You can set the maximum buffer duration to cache video data in the memory during playback, which improves the playback performance and user experience. If the maximum buffer duration is set too large, the buffer consumes excessive memory. You can use the large cache feature to cache video data in files, which reduces memory usage and further improves player performance.
When mMaxBufferDuration is greater than 50,000 ms, you can enable local caching to automatically trigger large cache. Procedure:
Enable the global local caching feature.
By default, the local caching feature is disabled. To use this feature, you must manually enable it. You can call
enableLocalCache
in theAliPlayerGlobalSettings
class to enable local caching. For more information about the sample code, see the Configure local caching section of this topic.Enable local caching for a URL.
For more information about the sample code, see the Enable or disable local caching for a single URL section of this topic.
Enable large cache. Sample code:
AliPlayerGlobalSettings.enableBufferToLocalCache(true);
Configure video preload
ApsaraVideo Player SDK for Android supports video preload, which is an upgrade of the local caching 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.
The video preload feature has the following limits:
You can preload only one MP4, MP3, FLV, or HLS file at a time.
You can preload only videos that are played based on URLs. You cannot preload videos that use VidAuth or VidSts for playback.
By default, network resource scheduling is enabled when you use ApsaraVideo Player SDK for Android to preload videos. This ensures the quality of the video that is being played. If network resource scheduling is enabled, the preload request is sent only after the buffered content of the video that is being played reaches a specific limit. You can disable network resource scheduling if you want to manage the real-time preload requests. Sample code:
AliPlayerGlobalSettings.enableNetworkBalance(false);
Enable the local caching feature. For more information, see the Configure local caching section of this topic.
Obtain an AliMediaLoader instance.
The AliMediaLoader instance is a singleton. You can create only one AliMediaLoader instance regardless of the times for which you obtain the instance.
MediaLoader mediaLoader = MediaLoader.getInstance();
Configure the AliMediaLoader instance.
Configure listeners and start to load video files.
NoteIf you call
prepare
inplayer
andmediaLoader.load
at the same time, an Application Not Responding (ANR) error may occur. This is because the system must traverse all local files for both operations. We recommend that you start loading after theonPrepared
callback is fired inplayer
.Optional: Delete the loaded video files.
You can delete the loaded video files to reduce occupied space. ApsaraVideo Player SDK for Android does not provide a method to delete the loaded video files. You must delete the video files in the corresponding directory in your application.
Dynamic preloading
The dynamic preloading feature allows you to manage cache of the video that is being played and videos that are preloaded. You can also control the number of videos that are preloaded. This helps maintain a balance between playback experience and cost.
Preloading of multi-bitrate HLS videos
You can preload videos in the same definition as the current video stream when you call the listPlayer
method during the playback of multi-bitrate HLS videos. You can use different preloading modes based on your business requirements.
Obtain the download speed
ApsaraVideo Player SDK for Android provides the getExtraValue
method for you to query the download speed of specified videos. The onInfo callback is invoked to obtain the query result. Sample code:
mAliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
@Override
public void onInfo(InfoBean infoBean) {
if(infoBean.getCode() == InfoCode.CurrentDownloadSpeed){
// The download speed.
long extraValue = infoBean.getExtraValue();
}
}
});
Configure the network
HTTPDNS
The HTTPDNS feature uses the DNS resolution technology to send domain name resolution requests to the specific HTTPDNS server and obtain the resolution results in a quick and stable manner. This prevents DNS hijacking.
ApsaraVideo Player SDK provides HTTPDNS services for domain names that are accelerated by Alibaba Cloud CDN. You can use the enhanced HTTPDNS feature to implement precise scheduling and ensure that the real-time domain resolution results immediately take effect. This improves the network performance.
The enhanced HTTPDNS feature is supported in ApsaraVideo Player SDK V6.7.0 or later. To use the enhanced HTTPDNS feature in ApsaraVideo Player SDK V6.7.0 to V6.11.0, submit a ticket or contact your Alibaba Cloud account manager. If you use ApsaraVideo Player SDK V6.12.0 or later, the enhanced HTTPDNS feature is enabled by default and no application is required.
Sample code for using the enhanced HTTPDNS feature
You can use the enhanced HTTPDNS feature only for accelerated domain names. Before you use the feature, make sure that an accelerated domain name is added and configured. For more information about how to add and configure a domain name for CDN in ApsaraVideo VOD, see Add a domain name for CDN. For more information about accelerated domain names, see What is Alibaba Cloud CDN?.
// Enable the enhanced HTTPDNS feature.
AliPlayerGlobalSettings.enableEnhancedHttpDns(true);
// Optional. Add an HTTPDNS pre-resolved domain name.
DomainProcessor.getInstance().addPreResolveDomain("player.***alicdn.com");
HTTP/2
By default, HTTP/2 is enabled for ApsaraVideo Player SDK for Android V5.5.0.0 or later.
ApsaraVideo Player SDK for Android supports HTTP/2. You can enable HTTP/2 to implement the multiplexing of requests. This prevents head-of-line (HOL) blocking and improves playback performance. Sample code:
AliPlayerGlobalSettings.setUseHttp2(true);
Create TCP connections before playback requests are initiated over HTTP
You can create Transmission Control Protocol (TCP) connections before playback requests are initiated over HTTP. This reduces the waiting time, ensures the timeliness and consistency of video playback, improves the user experience, and optimizes the usage of network and system resources. Sample code:
// Specify the domain parameter in the host[:port] format. Separate multiple domain names with semicolons (;). The port parameter is optional.
// Specify global settings.
// Add or delete TCP connections. If you specify an empty string, no TCP connections are created.
AliPlayerGlobalSettings.setOption(AliPlayerGlobalSettings.SET_PRE_CONNECT_DOMAIN, "domain1;domain2");
Configure video download
ApsaraVideo Player SDK for Android allows you to download videos to local devices for offline playback in ApsaraVideo Player. The normal download mode and secure download mode are supported.
Normal download
Videos that are downloaded in the normal download mode are not encrypted by Alibaba Cloud and can be played by using 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.
Usage notes
You can download only videos that are played based on VidSts or VidAuth.
To use the video download feature, you must enable the feature and configure the download mode in the ApsaraVideo VOD console. For more information, see Configure download settings.
Resumable download is supported.
Procedure
Optional. Configure the security file for encryption verification. You must configure the security file only when you use the secure download mode.
NoteMake sure that the information in the security file for encryption verification matches the application information. Otherwise, the video download fails.
If you use the secure download mode, you must configure the key file generated in the ApsaraVideo VOD console in ApsaraVideo Player SDK. The key file is used to decrypt and verify the video for download and playback. For more information about how to generate the key file, see the Enable secure download section of the "Configure download settings" topic.
We recommend that you configure the key file only once. Sample code:
PrivateService.initService(getApplicationContext(), "The path in which the encryptedApp.dat file is stored"); // We recommend that you store the encryptedApp.dat file on your mobile phone and set this parameter to the path in which the file is stored.
Create and set a video downloader.
Use the AliDownloaderFactory class to create a download object. Sample code:
AliMediaDownloader mAliDownloader = null; ...... // Create a download object. mAliDownloader = AliDownloaderFactory.create(getApplicationContext()); // Specify the path for storing downloaded files. mAliDownloader.setSaveDir("The storage path");
Configure listeners.
The downloader provides multiple listeners. Sample code:
Prepare the download source.
You can call the
prepare
method to prepare a download source. VidSts and VidAuth sources are supported. Sample code:VidSts
// Create the VidSts download source. VidSts aliyunVidSts = new VidSts(); aliyunVidSts.setVid("Vid");// The ID of the video. aliyunVidSts.setAccessKeyId("<yourAccessKeyId>");// The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS. aliyunVidSts.setAccessKeySecret"<yourAccessKeySecret>");// The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS. aliyunVidSts.setSecurityToken("<yourSecurityToken>");// The STS token. To obtain the STS token, call the AssumeRole operation in STS. aliyunVidSts.setRegion("Access region");// The region in which ApsaraVideo VOD is activated. Default value: cn-shanghai. // Prepare the download source. mAliDownloader.prepare(aliyunVidSts)
VidAuth
// Create the VidAuth download source. VidAuth vidAuth = new VidAuth(); vidAuth.setVid("Vid"); // The ID of the video. vidAuth.setPlayAuth("<yourPlayAuth>");// The playback credential. To obtain the playback credential, call the GetVideoPlayAuth operation. vidAuth.setRegion("Access region"); // This parameter is deprecated in ApsaraVideo Player SDK V5.5.5.0 or later. If you use ApsaraVideo Player SDK V5.5.5.0 or later, the player automatically parses the region information. If you use ApsaraVideo Player SDK V5.5.5.0 or earlier, this parameter is required. Specify the ID of the region in which ApsaraVideo VOD is activated for this parameter. Default value: cn-shanghai. // Prepare the download source. mAliDownloader.prepare(vidAuth);
NoteThe output file and the input file are in the same format and cannot be changed.
Select the content to be downloaded from the prepared download source.
After the download source is prepared, the OnPreparedListener callback is fired.
The value of the TrackInfo parameter indicates the information about video tracks such as video definitions. Select a track to download. Sample code:
public void onPrepared(MediaInfo mediaInfo) { // Prepare the content to be downloaded. List<TrackInfo> trackInfos = mediaInfo.getTrackInfos(); // Download the information about tracks, such as the first track. mAliDownloader.selectItem(trackInfos.get(0).getIndex()); // Start the download. mAliDownloader.start(); }
Optional. Update the download source.
VidSts or VidAuth sources may expire before the download. Therefore, we recommend that you update the download source before you start the download. Sample code:
// Update the download source. mAliDownloader.updateSource(VidSts); // Start the download. mAliDownloader.start();
Release the download object after the download succeeds or fails.
After the download succeeds, call the
release
method to release the download object. You can release the download object after theonCompletion
oronError
callback is invoked. Sample code:mAliDownloader.stop(); mAliDownloader.release();
Optional. Delete a downloaded file.
You can delete a downloaded file during the download or after the download is complete. Sample code:
// Delete the file by using the download object. mAliDownloader.deleteFile(); // Delete the file by using the static method. If 0 is returned, the file is deleted. AliDownloaderFactory.deleteFile("The path of the downloaded file","Video ID","Video format","The index of the downloaded video");
What to do next
Perform the following operations to play downloaded videos by using ApsaraVideo Player: update PHP SDK to the latest version:
Obtain the absolute path of the downloaded video file.
String path = mAliDownloader.getFilePath();
Set UrlSource to the absolute path of the downloaded video file to play the video.
UrlSource urlSource = new UrlSource(); urlSource.setUri("Playback URL");// Specify the absolute path of the downloaded video file. aliPlayer.setDataSource(urlSource);
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 about how to play encrypted videos, see Play an encrypted video.
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.