All Products
Search
Document Center

Features and usage

Last Updated: Sep 17, 2019

ApsaraVideo Player SDK for Android provides the following features:

  • Playing a single video
  • Playing videos in a list
  • Download
  • Caching

This topic describes these features.

1. Playback

The playback procedure is as follows:

  1. Create a player. 2. Set listeners. 3. Set the playback source. 4. Prepare the player. 5. Start playback. 6. Set operations for playback control. 7. Release the player.

1. Create a player

ApsaraVideo Player SDK for Android provides the AliPlayerFactory class to create a player. You can use the AliPlayer class to create a player for playing a single video or use the AliListPlayer class to create a player for playing videos in a list. Use the AliPlayer class to create a player as follows:

  1. AliPlayer aliyunVodPlayer;
  2. .....
  3. aliyunVodPlayer = AliPlayerFactory.createAliPlayer(getApplicationContext());

If you want to play a local file securely downloaded by ApsaraVideo Player SDK, you need to configure a security file for encryption verification. We recommend that you configure the security file in your application, and you only need to do that once.

  1. PrivateService.initService(getApplicationContext(), "The local path of the encryptedApp.dat file");

For more information about how to configure a security file, see here.

The following error message is returned if you do not properly configure a security file: ERROR_DEMUXER_OPENSTREAM.

2. Set player listeners

The player object provides multiple listeners, such as onPrepared and onCompletion. The sample code is as follows:

  1. aliyunVodPlayer.setOnCompletionListener(new IPlayer.OnCompletionListener() {
  2. @Override
  3. public void onCompletion() {
  4. // The listener for the completion of playback.
  5. }
  6. });
  7. aliyunVodPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
  8. @Override
  9. public void onError(ErrorInfo errorInfo) {
  10. // The listener for errors.
  11. }
  12. });
  13. aliyunVodPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
  14. @Override
  15. public void onPrepared() {
  16. // The listener for successful preparation.
  17. }
  18. });
  19. aliyunVodPlayer.setOnVideoSizeChangedListener(new IPlayer.OnVideoSizeChangedListener() {
  20. @Override
  21. public void onVideoSizeChanged(int width, int height) {
  22. // A callback for video resolution changes.
  23. }
  24. });
  25. aliyunVodPlayer.setOnRenderingStartListener(new IPlayer.OnRenderingStartListener() {
  26. @Override
  27. public void onRenderingStart() {
  28. // The listener for the display of the first frame.
  29. }
  30. });
  31. aliyunVodPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
  32. @Override
  33. public void onInfo(int type, long extra) {
  34. // The listener for other events. The type parameter contains multiple values, indicating various events, such as the start of loop playback, buffer position, current playback position, and the start of autoplay.
  35. }
  36. });
  37. aliyunVodPlayer.setOnLoadingStatusListener(new IPlayer.OnLoadingStatusListener() {
  38. @Override
  39. public void onLoadingBegin() {
  40. // Indicate that the player starts to buffer a video.
  41. }
  42. @Override
  43. public void onLoadingProgress(int percent, float kbps) {
  44. // Indicate the buffering progress.
  45. }
  46. @Override
  47. public void onLoadingEnd() {
  48. // Indicate that the video buffering is complete.
  49. }
  50. });
  51. aliyunVodPlayer.setOnSeekCompleteListener(new IPlayer.OnSeekCompleteListener() {
  52. @Override
  53. public void onSeekComplete() {
  54. // Indicate that the seeking is complete.
  55. }
  56. });
  57. aliyunVodPlayer.setOnSubtitleDisplayListener(new IPlayer.OnSubtitleDisplayListener() {
  58. @Override
  59. public void onSubtitleShow(long id, String data) {
  60. // Indicate that subtitles are displayed.
  61. }
  62. @Override
  63. public void onSubtitleHide(long id) {
  64. // Indicate that subtitles are hidden.
  65. }
  66. });
  67. aliyunVodPlayer.setOnTrackChangedListener(new IPlayer.OnTrackChangedListener() {
  68. @Override
  69. public void onChangedSuccess(TrackInfo trackInfo) {
  70. // Indicate that the switching of audio and video streams or the resolution switching succeeds.
  71. }
  72. @Override
  73. public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
  74. // Indicate that the switching of audio and video streams or the resolution switching failed.
  75. }
  76. });
  77. aliyunVodPlayer.setOnStateChangedListener(new IPlayer.OnStateChangedListener() {
  78. @Override
  79. public void onStateChanged(int newState) {
  80. // The listener for player status changes.
  81. }
  82. });
  83. aliyunVodPlayer.setOnSnapShotListener(new IPlayer.OnSnapShotListener() {
  84. @Override
  85. public void onSnapShot(Bitmap bm, int with, int height) {
  86. // The listener for snapshot capture.
  87. }
  88. });

For more information about callback parameters, see the description of operations. TODO link

3. Set the source and prepare the playback

Four playback sources are supported: VidSts, VidAuth, VidMps, and UrlSource. You can use UrlSource for URL-based playback, and use VidSts, VidAuth, and VidMps for video ID (VID)-based playback. VidSts and VidAuth are available for ApsaraVideo for VOD users only. VidMps is available for ApsaraVideo for Media Processing users only.

The following code uses VidSts as an example:

  1. // Create the aliyunVidSts object.
  2. VidSts aliyunVidSts = new VidSts();
  3. aliyunVidSts.setVid(VID);
  4. aliyunVidSts.setAccessKeyId(Temporary AccessKey ID);
  5. aliyunVidSts.setAccessKeySecret(Temporary AccessKey secret);
  6. aliyunVidSts.setSecurityToken(Security token);
  7. aliyunVidSts.setRegion(Access region);
  8. // Set the playback source.
  9. aliyunVodPlayer.setDataSource(aliyunVidSts);
  10. ......
  11. // Prepare the player.
  12. aliyunVodPlayer.prepare();

For more information about playback based on ApsaraVideo for Media Processing, see Video playback.
For more information about playAuth-based playback, see Use playback credentials.
For more information of region settings, see VOD centers and access domains.

4. Set the UI view

If the playback source contains video images, you need to set the UI view to display the video images. The player SDK provides SurfaceView and TextureView for you to set the UI view.
The following code uses SurfaceView as an example:

  1. surfaceView = (SurfaceView) findViewById(R.id.playview);
  2. surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
  3. @Override
  4. public void surfaceCreated(SurfaceHolder holder) {
  5. aliyunVodPlayer.setDisplay(holder);
  6. }
  7. @Override
  8. public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
  9. aliyunVodPlayer.redraw();
  10. }
  11. @Override
  12. public void surfaceDestroyed(SurfaceHolder holder) {
  13. aliyunVodPlayer.setDisplay(null);
  14. }
  15. });

In the surfaceChanged method, the redraw method is called to refresh the video image. If the UI view size changes, you can call the redraw method to refresh the video image to adapt to the UI view.

5. Set playback control

You can create playback control buttons and associate the click events with the corresponding playback control methods to implement playback interaction. The basic control features include play, stop, pause, and seek. The seek feature is valid only for VOD. If you pause a live stream, the current position of the live stream is saved. You can go back to where you left off by using the resume feature. The sample code is as follows:

  1. // Start the playback.
  2. aliyunVodPlayer.start();
  3. // Pause the playback.
  4. aliyunVodPlayer.pause();
  5. // Stop the playback.
  6. aliyunVodPlayer.stop();
  7. // Seek to the video image at the specified time point. This operation may not direct the video to the precise time point.
  8. aliyunVodPlayer.seekTo(long position);
  9. // Reset the player.
  10. aliyunVodPlayer.reset();
  11. // Release the player. The player cannot be used once it is released.
  12. aliyunVodPlayer.release();

6. Set multi-bitrate switching

ApsaraVideo Player SDK for Android supports playing an HTTP Live Streaming (HLS) Encryption-based video in different bitrates. After the player is prepared successfully using the prepare method, you can call the getMediaInfo method to obtain the value of the TrackInfo parameter, which indicates the bitrate information.

  1. List<TrackInfo> trackInfos = aliyunVodPlayer.getMediaInfo().getTrackInfos();

During playback, you can call the selectTrack method to switch the bitrate.

  1. int index = trackInfo.getIndex();
  2. aliyunVodPlayer.selectTrack(index);

To obtain the multi-bitrate switching result, set the OnTrackChangedListener listener before calling the selectTrack method.

  1. aliyunVodPlayer.setOnTrackChangedListener(new IPlayer.OnTrackChangedListener() {
  2. @Override
  3. public void onChangedSuccess(TrackInfo trackInfo) {
  4. // Multi-bitrate switching succeeds.
  5. }
  6. @Override
  7. public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
  8. // Multi-bitrate switching failed. Call the errorInfo.getMsg() method to obtain the cause of failure.
  9. }
  10. });

For more information about the TrackInfo, see here. TODO link……

7. Set autoplay

ApsaraVideo Player SDK for Android supports autoplay. To set autoplay, call the setAutoPlay method before calling the prepare method.

  1. aliyunVodPlayer.setAutoPlay(true);

After you set autoplay, the player automatically starts playback once it is successfully prepared. In this case, the onInfo callback instead of the onPrepared callback is fired when the player is prepared.

  1. aliyunVodPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
  2. @Override
  3. public void onInfo(InfoBean infoBean) {
  4. if (infoBean.getCode() == InfoCode.AutoPlayStart){
  5. // The listener for the start of autoplay.
  6. }
  7. }
  8. });

8. Set loop playback

ApsaraVideo Player SDK for Android supports loop playback. Call the setLoop method to enable the loop playback feature. The player plays a video all over again after it plays the video completely.

  1. aliyunVodPlayer.setLoop(true);

The callback for the start of loop playback is fired by the onInfo callback.

  1. aliyunVodPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
  2. @Override
  3. public void onInfo(InfoBean infoBean) {
  4. if (infoBean.getCode() == InfoCode.LoopingStart){
  5. // The listener for the start of loop playback.
  6. }
  7. }
  8. });

9. Set video image rotation, scaling, and mirroring

ApsaraVideo Player SDK for Android provides multiple operations for you to precisely control the video image, such as rotation, scaling, and mirroring.

  1. // Set the mirroring mode: horizontal image, vertical image, and no image.
  2. aliyunVodPlayer.setMirrorMode(MirrorMode.MIRROR_MODE_NONE);
  3. // Set the rotation angel: 0°, 90°, 180°, and 270°.
  4. aliyunVodPlayer.setRotateMode(RotateMode.ROTATE_0);
  5. // Set the scaling mode: aspect ratio-based padding, aspect ratio-based fitting, and stretching.
  6. aliyunVodPlayer.setScaleMode(ScaleMode.SCALE_ASPECT_FIT);

The following table describes values of the RotateMode parameter.

Value Description
ROTATE_0 Indicates that the rotation angle is 0°, in the clockwise direction.
ROTATE_90 Indicates that the rotation angle is 90°, in the clockwise direction.
ROTATE_180 Indicates that the rotation angle is 180°, in the clockwise direction.
ROTATE_270 Indicates that the rotation angle is 270°, in the clockwise direction.

The following table describes values of the ScaleMode parameter.

Value Description
SCALE_ASPECT_FIT Indicates that the video image is scaled down into the UI view without changing the aspect ratio. This prevents image distortion.
SCALE_ASPECT_FILL Indicates that the video image is scaled out to fill the UI view without changing the aspect ratio. This prevents image distortion.
SCALE_TO_FILL Indicates that the video image is stretched to fill the UI view. This may cause image distortion if the video image and the UI view do not match in the aspect ratio.

The following table describes values of the MirrorMode parameter.

Value Description
MIRROR_MODE_NONE Indicates that mirroring is disabled.
MIRROR_MODE_HORIZONTAL Indicates horizontal mirroring.
MIRROR_MODE_VERTICAL Indicates vertical mirroring.

10. Set the mute mode and volume control

ApsaraVideo Player SDK for Android provides the feature of volume control. You can call the setMute method to set the mute mode for the player, and call the setVolume method to set the player volume (valid values: 0 to 1).

  1. // Enable the mute mode.
  2. aliyunVodPlayer.setMute(true);
  3. // Set the player volume. Value range: 0 to 1.
  4. aliyunVodPlayer.setVolume(1f);

11. Set the playback speed

ApsaraVideo Player SDK for Android allows you to set the playback speed. You can call the setSpeed method to change the playback speed from 0.5x to 2x. The audio pitch remains unchanged at different speeds.

  1. // Set the playback speed. You can change the playback speed from 0.5x to 2x.
  2. aliyunVodPlayer.setSpeed(1.0f);

12. Set snapshot capture

ApsaraVideo Player SDK for Android provides the feature of snapshot capture. 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 call the OnSnapShotListener method to obtain the bitmap. Note that a snapshot is a video image and does not contain the UI.

  1. // The callback for snapshot capture.
  2. aliyunVodPlayer.setOnSnapShotListener(new OnSnapShotListener(){
  3. @Override
  4. public void onSnapShot(Bitmap bm, int with, int height){
  5. // Obtain the bitmap, and width and height of the captured video image.
  6. }
  7. });
  8. // Take a snapshot of the current video image.
  9. aliyunVodPlayer.snapshot();

13. Set play-and-cache

ApsaraVideo Player SDK for Android provides the feature of play-and-cache. This feature saves your traffic during loop playback. To enable play-and-cache, call the CacheConfig method before the prepare method is called.

To play an encrypted video, you need to configure a security file for encryption verification. For more information, see 14. Configure a security file for encryption verification.

  1. CacheConfig cacheConfig = new CacheConfig();
  2. // Enable play-and-cache.
  3. cacheConfig.mEnable = true;
  4. // Specify the maximum length of a single cached file. Files whose length exceeds the maximum value are not cached.
  5. cacheConfig.mMaxDurationS =100;
  6. // Specify the cache directory.
  7. cacheConfig.mDir = "The directory of the cached file";
  8. // Specify the maximum size of the cache directory. When the total size of cached files in the cache directory exceeds the maximum size, the system overwrites the earliest cached files.
  9. cacheConfig.mMaxSizeMB = 200;
  10. // Specify the cache configuration for the player.
  11. mAliyunVodPlayer.setCacheConfig(cacheConfig);

You must call the setCacheConfig method to use cached files. Cached files are used in the following scenarios:

  1. If you enable loop playback by setting setLoop to true, the player automatically plays a video all over again by using the cached file after it plays the video completely.
  2. After you cache a video and create a new player to play the video, the new player plays the video by using the cached file.

Note: The player needs to locate cached files for VID-based playback based on the VID and other required information, which can be obtained through online requests.

ApsaraVideo Player SDK also provides an operation for you to obtain the cache file directory:

  1. public String getCacheFilePath(String URL)
  2. Feature: Obtain the cached file name based on the video URL. Call the setCacheConfig method to obtain the name of the cached file based on the URL.
  3. Parameter: url: the video URL.
  4. Return value: the absolute path for the cached file.
  5. public String getCacheFilePath(String vid, String format, String definition, int previewTime)
  6. Feature: Obtain the cached file name based on the VID. Call the setCacheConfig method to obtain the name of the cached file based on the VID.
  7. Parameters: vid: the video ID. format: the video format. definition: the video resolution. previewTime: the preview duration.
  8. Return value: the absolute path for the cached file.

The player does not cache videos during playback in some scenarios. The following provides more information about the play-and-cache feature:

  1. When the player plays UrlSource streams by using the HLS protocol based on the URL in an M3U8 file, the player does not cache the video during playback. For other supported formats of URL-based playback, the player caches videos during playback as configured.
  2. When the player plays a video based on the VID, the player caches the video during playback as configured.
  3. A video is successfully cached when the player reads all video data. Caching may fail if the stop method or the onError method is called before data reading is complete.
  4. Seeking to a position inside the cached video does not affect the caching result, but seeking to a position outside the cached video may cause a caching failure.
  5. To cache an encrypted video, ensure that the application information matches the authentication information in the security file of the video. Otherwise, the video caching may fail.
  6. The onInfo callback returns the caching result.
  1. aliyunVodPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
  2. @Override
  3. public void onInfo(InfoBean infoBean) {
  4. if (infoBean.getCode() == InfoCode.CacheSuccess){
  5. // Indicate that the caching succeeds.
  6. }else if (infoBean.getCode() == InfoCode.CacheError){
  7. // Indicate that the caching failed. You can call the infoBean.getExtraMsg() method to obtain the failure cause.
  8. }
  9. }
  10. });

14. Set preview

ApsaraVideo Player SDK provides the preview feature. After you set the preview duration, the player plays the video clip for preview instead of the whole video.
You can set the preview feature by using ApsaraVideo for VOD. Currently, this feature supports VidSts and VidAuth sources. For more information about how to configure and use the preview feature, see Best practice of preview. After you enable the preview feature, you can call the setPreviewTime() method in VidPlayerConfigGen to set the preview duration. The following code uses VidSts as an example:

  1. VidSts vidSts = new VidSts;
  2. ....
  3. VidPlayerConfigGen configGen = new VidPlayerConfigGen();
  4. configGen.setPreviewTime(20);// Specify the preview duration to 20 seconds.
  5. vidSts.setPlayConfig(configGen);// Specify the settings for the playback source.
  6. ...

You can use the VidPlayerConfigGen method to specify request parameters supported by the server. For more information, see Request parameters.

Note: FLV and MP3 files do not support the preview feature.

15. Enable or disable hard decoding

ApsaraVideo Player SDK for Android supports H.264 and H.265 hard decoding. You can call the enableHardwareDecoder method to enable or disable hard decoding. By default, the hard decoding feature is enabled. If the hard decoding failed to be initialized, it is switched to soft decoding to ensure normal playback.

  1. // Enable hard decoding. It is enabled by default.
  2. mAliyunVodPlayer.enableHardwareDecoder(true);

The onInfo method fires a callback when hard decoding is switched to soft decoding.

  1. mApsaraPlayerActivity.setOnInfoListener(new IPlayer.OnInfoListener() {
  2. @Override
  3. public void onInfo(InfoBean infoBean) {
  4. if (infoBean.getCode() == InfoCode.SwitchToSoftwareVideoDecoder) {
  5. // Switch to soft decoding.
  6. }
  7. }
  8. });

16. Set the blacklist

ApsaraVideo Player SDK for Android allows you to set the blacklist for hard decoding. If a player does not support hard decoding, soft decoding is enabled to avoid invalid operations.

  1. DeviceInfo deviceInfo = new DeviceInfo();
  2. deviceInfo.model="Lenovo K320t";
  3. AliPlayerFactory.addBlackDevice(BlackType.HW_Decode_H264 ,deviceInfo );

The blacklist automatically expires when the application exits.

17. Set the referer

ApsaraVideo Player SDK for Android provides the PlayerConfig class for you to set the request referer. By setting referers in the blacklist or whitelist in the ApsaraVideo for VOD console, you can implement access control. The sample code is as follows:

  1. // Obtain player parameters.
  2. PlayerConfig config = mAliyunVodPlayer.getConfig();
  3. // Set the referer.
  4. config.mReferrer = referrer;
  5. ... // Set other parameters.
  6. // Specify the settings for the player.
  7. mAliyunVodPlayer.setConfig(config);

18. Specify UserAgent

ApsaraVideo Player SDK for Android provides the PlayerConfig class for you to specify the request UserAgent. After you specify UserAgent, the player contains the UserAgent information in its requests. The sample code is as follows:

  1. // Obtain player parameters.
  2. PlayerConfig config = mAliyunVodPlayer.getConfig();
  3. // Specify UserAgent.
  4. config.mUserAgent = "UserAgent to be specified";
  5. ... // Set other parameters.
  6. // Specify the settings for the player.
  7. mAliyunVodPlayer.setConfig(config);

19. Specify the network timeout period and retry times

You can use the PlayerConfig class to set the network timeout period and retry times. The sample code is as follows:

  1. // Obtain player parameters.
  2. PlayerConfig config = mAliyunVodPlayer.getConfig();
  3. // Specify the network timeout period, in milliseconds.
  4. config.mNetworkTimeout = 5000;
  5. // Specify retry times upon a network timeout. The networkTimeout parameter indicates the retry interval. The networkRetryCount parameter indicates the retry times. A value of 0 indicates that the player does not retry playback upon a network timeout. The application determines the retry times. The default value is 2.
  6. config.mNetworkRetryCount=2;
  7. ... // Set other parameters.
  8. // Specify the settings for the player.
  9. mAliyunVodPlayer.setConfig(config);
  1. If you set the NetworkRetryCount parameter to a value other than 0, the player retries playback when the player starts loading data due to a network error. The number of retry times equals the value of the NetworkRetryCount parameter. The retry interval equals the value of the mNetworkTimeout parameter. If the player is still loading data when the retry times exceed the maximum limit, the onError callback is fired. You can call the ErrorInfo.getCode() method to obtain the error code: ERROR_LOADING_TIMEOUT.
  2. If you set the NetworkRetryCount parameter to 0, the onInfo callback is fired when the network connection times out. You can call the InfoBean.getCode() method to obtain the information code: NetworkRetry. To resolve the problem, call the reload method to reload data or take other operations as required. You can configure your application to implement the relevant logic.

20. Control the buffer and delay

Buffer control is important for a player. You can significantly shorten the startup loading time and improve playback smoothness with proper configuration. ApsaraVideo Player SDK for Android provides the PlayerConfig class for you to control the buffer and delay.

  1. // Obtain player parameters.
  2. PlayerConfig config = mAliyunVodPlayer.getConfig();
  3. // Set the maximum buffer delay. This parameter is valid only for live streaming. If the delay time exceeds the maximum limit, the player synchronizes frames to reduce the delay under the set limit.
  4. config.mMaxDelayTime = 5000;
  5. // Set the maximum buffer duration, in milliseconds. This parameter indicates the maximum video length that can be loaded by the player.
  6. config.mMaxBufferDuration = 50000;
  7. // Set the peak buffer duration, in milliseconds. The player starts loading data when the network connection is poor. This parameter indicates the buffer duration beyond which the player stops loading in this case.
  8. config.mHighBufferDuration = 3000;
  9. // Set the startup loading duration, in milliseconds. The smaller this value is, the shorter the startup loading time is, and the sooner the player starts loading after the start of playback.
  10. config.mStartBufferDuration = 500;
  11. ... // Set other parameters.
  12. // Specify the settings for the player.
  13. mAliyunVodPlayer.setConfig(config);

Note: Ensure that the value of mStartBufferDuration is not greater than the value of mHighBufferDuration, and the value of mHighBufferDuration is not greater than the value of mMaxBufferDuration.

21. Set HTTP headers

ApsaraVideo Player SDK provides the PlayerConfig class to set HTTP headers for the player. The sample code is as follows:

  1. // Obtain player parameters.
  2. PlayerConfig config = mAliyunVodPlayer.getConfig();
  3. // Define a header.
  4. String[] headers = new String[1];
  5. headers[0]="Host:xxx.com";// Add the host information to the header.
  6. // Set the header.
  7. config.setCustomHeaders(headers);
  8. ... // Set other parameters.
  9. // Specify the settings for the player.
  10. mAliyunVodPlayer.setConfig(config);

2. List playback

Currently, list playback for short videos is popular. ApsaraVideo Player SDK for Android provides a complete list playback feature with the preloading mechanism. This significantly shortens the startup loading time. The list playback procedure is as follows:

  1. Create a player. 2. Set listeners. 3. Add multiple playback sources. 4. Play a playback source. 5. Set operations for playback control. 6. Remove a playback source. 7. Release the player.

Features and operations of playback for list playback are same as those in Playback, except that some list control features are added. For more information about creation, listening, control, and release of the player, see Playback.

1. Create a player

ApsaraVideo Player SDK for Android provides the AliPlayerFactory class to create a player. You can use the AliPlayer class to create a player for playing a single video or use the AliListPlayer class to create a player for playing videos in a list.
AliListPlayer and AliPlayer provide almost the same features, except that AliListPlayer provides a feature of list playback. To use the list playback feature, create an AliListPlayer player as follows:

  1. AliListPlayer aliyunListPlayer;
  2. .....
  3. aliyunListPlayer = AliPlayerFactory.createAliListPlayer(getApplicationContext());

2. Specify the number of short videos to be preloaded

You can significantly shorten the startup loading time by properly setting the number of short videos to be preloaded.

  1. // Specify the number of short videos to be preloaded. Total number of short videos to be preloaded = 1 + count × 2, where, count is the value of the setPreloadCount parameter.
  2. aliyunListPlayer.setPreloadCount(int count);

3. Add or remove multiple playback sources

List playback supports VidSts and UrlSource sources. You can use UrlSource for URL-based playback, and use VidSts for VID-based playback.

VidAuth and VidMps sources are not supported by list playback.

  1. // Add a VidSts source.
  2. aliyunListPlayer.addVid(String videoId, String uid);
  3. // Add a UrlSource source.
  4. aliyunListPlayer.addUrl(String url, String uid);
  5. // Remove a source.
  6. aliyunListPlayer.removeSource(String uid);

The uid parameter indicates the unique ID of a video, which is used to differentiate videos. Videos with the same unique ID are considered as the same video.
If the player plays a video that is not the one you specified, check whether you specify a unique ID for multiple videos.
You can specify the uid parameter to any string.

4. Play a playback source

After you add one or more playback sources, call the moveTo method so that the player automatically plays the specified source. You can call the following operations to play a source:

  1. // Use this operation for URL-based playback.
  2. aliyunVodPlayer.moveTo(String uid);
  3. // Use this operation for VID-based playback. You need to specify the STS token information for the stsInfo parameter. Ensure that the STS token is valid.
  4. aliyunVodPlayer.moveTo(String uid, StsInfo info);

5. Play the previous or next video in the list

After you call the moveToPrev method, the player automatically plays the previous video in the list. After you call the moveToNext method, the player automatically plays the next video in the list.

  1. // Play the next video. This method is valid only for URL-based playback, and not valid for VID-based playback.
  2. aliyunVodPlayer.moveToNext();
  3. // Play the previous video. This method is valid only for URL-based playback, and not valid for VID-based playback.
  4. aliyunVodPlayer.moveToPrev();
  5. // Play the next video. This method is valid only for VID-based playback.
  6. aliyunVodPlayer.moveToNext(StsInfo info);
  7. // Play the previous video. This method is valid only for VID-based playback.
  8. aliyunVodPlayer.moveToPrev(StsInfo info);

For more information about API operations and parameters, see the description of operations. TODO link

3. Video download

ApsaraVideo Player SDK allows you to download videos from ApsaraVideo for VOD by using the STS token and playAuth. ApsaraVideo for VOD supports two download modes: secure download and normal download. You can set the download mode in the console.
When you select the normal download mode, downloaded videos are not encrypted by Alibaba Cloud, even though the videos have been encrypted by ApsaraVideo for VOD. That means you can use third-party players to play the downloaded videos.
When you select the secure download mode, downloaded videos are encrypted by Alibaba Cloud, even though the videos have not been encrypted by ApsaraVideo for VOD. That means you cannot use third-party players other than ApsaraVideo Player to play the downloaded videos.

The process for video download is as follows:

  1. Create and set a download object. 2. Set listeners. 3. Prepare the download source. 4. Select download tasks. 5. Update the download source information and start download. 6. Release the download object after the download succeeds or fails.

1. Create and set a download object

Use the AliDownloaderFactory class to create a download object. The sample code is as follows:

  1. AliMediaDownloader mAliDownloader = null;
  2. ......
  3. // Create a download object.
  4. mAliDownloader = AliDownloaderFactory.create(getApplicationContext());
  5. // Set the path for storing downloaded files.
  6. mAliDownloader.setSaveDir("The path of the folder for storing downloaded files");

ApsaraVideo Player SDK for Android allows you to download videos encrypted by Alibaba Cloud. You need to configure a security file for encryption verification in the player SDK to ensure security. We recommend that you configure the security file in your application, and you only need to do that once.

  1. PrivateService.initService(getApplicationContext(), "The local path of the encryptedApp.dat file");

To download an encrypted video, ensure that the application information matches the authentication information in the security file of the video. Otherwise, the video download may fail.

2. Set listeners

The download object provides multiple listeners. Use the following code to set listeners:

  1. mAliDownloader.setOnPreparedListener(new AliMediaDownloader.OnPreparedListener() {
  2. @Override
  3. public void onPrepared(MediaInfo mediaInfo) {
  4. // Indicate that the preparation of download tasks succeeds.
  5. }
  6. });
  7. mAliDownloader.setOnProgressListener(new AliMediaDownloader.OnProgressListener() {
  8. @Override
  9. public void onDownloadingProgress(int percent) {
  10. // Indicate the percentage of the download progress.
  11. }
  12. @Override
  13. public void onProcessingProgress(int percent) {
  14. // Indicate the percentage of the processing progress.
  15. }
  16. });
  17. mAliDownloader.setOnErrorListener(new AliMediaDownloader.OnErrorListener() {
  18. @Override
  19. public void onError(ErrorInfo errorInfo) {
  20. // Indicate that a download error occurs.
  21. }
  22. });
  23. mAliDownloader.setOnCompletionListener(new AliMediaDownloader.OnCompletionListener() {
  24. @Override
  25. public void onCompletion() {
  26. // Indicate that the download succeeds.
  27. }
  28. });

3. Prepare the download source

Call the prepare method to prepare the download source. ApsaraVideo Player SDK for Android supports two download sources: VidSts and VidAuth. The following code uses VidSts as an example:

  1. // Create the aliyunVidSts object.
  2. VidSts aliyunVidSts = new VidSts();
  3. aliyunVidSts.setVid(VID);
  4. aliyunVidSts.setAccessKeyId(Temporary AccessKey ID);
  5. aliyunVidSts.setAccessKeySecret(Temporary AccessKey secret);
  6. aliyunVidSts.setSecurityToken(Security token);
  7. aliyunVidSts.setRegion(Access region);
  8. // Prepare the download source.
  9. mAliDownloader.prepare(aliyunVidSts)

4. Select download tasks

When the download source preparation is completed, the OnPreparedListener callback is fired. Select a video track for download:

  1. public void onPrepared(MediaInfo mediaInfo) {
  2. // Indicate that the preparation of download tasks succeeds.
  3. List<TrackInfo> trackInfos = mediaInfo.getTrackInfos();
  4. // Download the information of tracks, for example, the first track.
  5. mAliDownloader.selectItem(trackInfos.get(0).getIndex());
  6. }

5. Update the download source information and start download

After you select download tasks and download the track information, you can start the download. We recommend that you update the download source information before the download in case of VidSts or VidAuth expiration.

  1. // Update the download source information.
  2. mAliDownloader.updateSource(mVidSts);
  3. // Start the download.
  4. mAliDownloader.start();

6. Release the download object after the download succeeds or fails

After the download succeeds, call the release method to release the download object. The download object is stopped when the onCompletion callback is fired, or is released when the onError callback is fired:

  1. mAliDownloader.stop();
  2. mAliDownloader.release();

7. Delete a downloaded file

You can delete a downloaded file during the download or after the download is complete:

  1. // Call an operation to delete a downloaded file.
  2. mAliDownloader.deleteFile();
  3. // Delete the download files from the local directory.
  4. AliDownloaderFactory.deleteFile("Directory of the downloaded file",vid, format,index);