This topic describes the advanced features of ApsaraVideo Player SDK for Android and provides the sample code.

Configure playback

Enable list playback for short videos

ApsaraVideo Player SDK for Android provides a full-fledged list playback feature for short videos. The SDK uses solutions such as preload to minimize the startup loading duration of playbacks. We recommend that you do not enable this feature for long videos.

  1. Create a player.
    Create an AliListPlayer object by using the AliPlayerFactory class. The following sample code provides an example:
    AliListPlayer aliyunListPlayer;
    .....
    aliyunListPlayer = AliPlayerFactory.createAliListPlayer(getApplicationContext());
    aliyunListPlayer.setTraceId("traceId"); // The trace ID is the unique identifier of the device used by the user. In most cases, the value is the International Mobile Equipment Identity (IMEI) or the Identifier for Advertisers (IDFA) of the device.
  2. Optional:Configure listeners.
    Listeners are optional when you create a short video list player. However, if you do not configure listeners, you cannot receive notifications of events related to the player, such as the failure and progress of the playback. Therefore, we recommend that you configure listeners as needed. You can configure multiple listeners for your player. We recommend that you configure the following important listeners: OnPreparedListener, OnErrorListener, OnCompletionListener, OnLoadingStatusListener, and OnInfoListener.
    aliyunListPlayer.setOnCompletionListener(new IPlayer.OnCompletionListener() {
        @Override
        public void onCompletion() {
            // Listens to the completion of playback.
        }
    });
    aliyunListPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
        @Override
        public void onError(ErrorInfo errorInfo) {
            // Listens to errors.
        }
    });
    aliyunListPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
        @Override
        public void onPrepared() {
            // Listens to successful preparation.
        }
    });
    aliyunListPlayer.setOnVideoSizeChangedListener(new IPlayer.OnVideoSizeChangedListener() {
        @Override
        public void onVideoSizeChanged(int width, int height) {
            // Listens to the change of video resolution.
        }
    });
    aliyunListPlayer.setOnRenderingStartListener(new IPlayer.OnRenderingStartListener() {
        @Override
        public void onRenderingStart() {
            // Listens to the display of the first frame.
        }
    });
    aliyunListPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
        @Override
        public void onInfo(int type, long extra) {
            // Listens to other events. The type parameter contains multiple values, indicating various events, such as the start of loop playback, the buffer position, the current playback position, and the start of autoplay.
        }
    });
    aliyunListPlayer.setOnLoadingStatusListener(new IPlayer.OnLoadingStatusListener() {
        @Override
        public void onLoadingBegin() {
            // Listens to the start of buffering. 
        }
        @Override
        public void onLoadingProgress(int percent, float kbps) {
            // Listens to the buffering progress.
        }
        @Override
        public void onLoadingEnd() {
            // Listens to the completion of buffering.
        }
    });
    aliyunListPlayer.setOnSeekCompleteListener(new IPlayer.OnSeekCompleteListener() {
        @Override
        public void onSeekComplete() {
            // Listens to the completion of seeking.
        }
    });
    aliyunListPlayer.setOnSubtitleDisplayListener(new IPlayer.OnSubtitleDisplayListener() {
        @Override
        public void onSubtitleShow(long id, String data) {
            // Listens to the display of subtitles.
        }
        @Override
        public void onSubtitleHide(long id) {
            // Listens to the hiding of subtitles.
        }
    });
    aliyunListPlayer.setOnTrackChangedListener(new IPlayer.OnTrackChangedListener() {
        @Override
        public void onChangedSuccess(TrackInfo trackInfo) {
            // Listens to the success of switching between audio and video streams or between definitions.
        }
        @Override
        public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
            // Listens to the failure of switching between audio and video streams or between definitions.
        }
    });
    aliyunListPlayer.setOnStateChangedListener(new IPlayer.OnStateChangedListener() {
        @Override
        public void onStateChanged(int newState) {
            // Listens to the change of player status.
        }
    });
    aliyunListPlayer.setOnSnapShotListener(new IPlayer.OnSnapShotListener() {
        @Override
        public void onSnapShot(Bitmap bm, int with, int height) {
            // Listens to the capture of snapshots.
        }
    });
  3. Set the number of videos that you want to preload.
    You can set the number of videos to be preloaded based on your business requirements. This way, the startup loading duration can be reduced. The following sample code provides an example:
    // Set the number of videos that you want to preload. The total number of loaded videos is equal to one plus twice the specified number. 
    aliyunListPlayer.setPreloadCount(int count);
  4. Add or remove multiple playback sources.
    List playback supports the VidSts and UrlSource playback sources. UrlSource is used for URL-based playback. The following sample code provides an example:
    • UrlSource: The streaming URL can be the URL of an audio or a video in ApsaraVideo VOD or on a third-party video-on-demand (VOD) platform. You can call the GetPlayInfo operation to obtain the streaming URL of an audio or a video in ApsaraVideo VOD. We recommend that you integrate a server operation SDK of ApsaraVideo VOD to obtain the URL. This way, you do not need to calculate the signature value. For more information, see GetPlayInfo in OpenAPI Explorer.
    • VidSts: VidSts is used for ID-based playback. To obtain the ID, you can log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video in the left-side navigation pane. Alternatively, you can call the SearchMedia operation.
    // Add a VidSts playback source.
    aliyunListPlayer.addVid(String videoId, String uid);
    // Add an UrlSource playback source.
    aliyunListPlayer.addUrl(String url, String uid);
    // Remove a playback source.
    aliyunListPlayer.removeSource(String uid);
    Note
    • VidAuth and VidMps are not supported for list playback.
    • The uid parameter specifies the unique ID of a video. You can use the unique ID to identify videos. Videos with the same unique ID are considered the same. 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 set the uid parameter to a string.
  5. Configure the UI view.
    SurfaceView and TextureView are supported. Set the UI view to SurfaceView or TextureView.
    • Sample code for SurfaceView:
      SurfaceView surfaceView = findViewById(R.id.surface_view);
      surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
          @Override
          public void surfaceCreated(SurfaceHolder holder) {
              aliyunListPlayer.setSurface(holder.getSurface());
          }
      
          @Override
          public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
              aliyunListPlayer.surfaceChanged();
          }
      
          @Override
          public void surfaceDestroyed(SurfaceHolder holder) {
              aliyunListPlayer.setSurface(null);
          }
      });
    • Sample code for TextureView:
      TextureView textureView = findViewById(R.id.texture_view);
      textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
          @Override
          public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
              aliyunListPlayer.setSurface(new Surface(surface));
          }
      
          @Override
          public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
              aliyunListPlayer.surfaceChanged();
          }
      
          @Override
          public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
              aliyunListPlayer.setSurface(null);
              return false;
          }
      
          @Override
          public void onSurfaceTextureUpdated(SurfaceTexture surface) {
      
          }
      });
  6. Play the content from a playback source.
    After you add one or more playback sources, call the moveTo method to play the content from the specified playback source. The following sample code provides an example:
    // Call the following method for URL-based playback:
    aliyunVodPlayer.moveTo(String uid);
    // Call the following method for ID-based playback. Make sure that you obtain the Security Token Service (STS) token and AccessKey pair before you call this method. For more information, see Create a role and grant temporary access permissions to the role by using STS. 
    aliyunVodPlayer.moveTo(String uid, StsInfo info);
  7. Play the previous or next video in the list.
    You can call the moveToPrev method to play the previous video or call the moveToNext method to play the next video. The following sample code provides an example:
    // Play the next video.  Note: This method is valid only for URL-based playback. The method is invalid for ID-based playback. 
    aliyunVodPlayer.moveToNext();
    // Play the previous video. Note: This method is valid only for URL-based playback. The method is invalid for ID-based playback. 
    aliyunVodPlayer.moveToPrev();
    // Play the next video. Note: This method is valid only for ID-based playback. 
    aliyunVodPlayer.moveToNext(StsInfo info);
    // Play the previous video. Note: This method is valid only for ID-based playback. 
    aliyunVodPlayer.moveToPrev(StsInfo info);

Configure external subtitles

ApsaraVideo Player SDK for Android allows you to add or switch external subtitles in the SRT, SSA, or ASS3 format for videos. The following sample code provides an example:

  1. Create a view that displays the subtitles.
    You must create different views for subtitles in different formats.
    // Create a view that displays subtitles in the SRT format.
    SubtitleView subtitleView = new SubtitleView(getContext());
    // Create a view that displays subtitles in the ASS or SSA format.
    AssSubtitleView assSubtitleView = new AssSubtitleView(getContext());
    // Add the view that displays subtitles to the layout view.
    viewGroup.addView(assSubtitleView);
  2. Configure listeners for subtitles.
    mAliPlayer.setOnSubtitleDisplayListener(new IPlayer.OnSubtitleDisplayListener() {
        @Override
        public void onSubtitleExtAdded(int trackIndex, String url) { }
    
        @Override
        public void onSubtitleShow(int trackIndex, long id, String data) {
                // Listens to the display of subtitles in the ASS format.
            assSubtitleView.show(id,data);
    
            // Listens to the display of subtitles in the SRT format.
            SubtitleView.Subtitle subtitle = new SubtitleView.Subtitle();
            subtitle.id = id + "";
            subtitle.content = data;
            subtitleView.show(subtitle);
    
        }
    
        @Override
        public void onSubtitleHide(int trackIndex, long id) {
                // Listens to the hiding of subtitles in the ASS format.
                assSubtitleView.dismiss(id);
    
            // Listens to the hiding of subtitles in the SRT format.
            subtitleView.dismiss(id + "");
        }
    
        @Override
        public void onSubtitleHeader(int trackIndex, String header) { }
    });
  3. Add subtitles.
    mAliPlayer.addExtSubtitle(url);
  4. Switch subtitles.
    mAliPlayer.selectTrack(trackIndex);

Enable audio-only playback

You can disable the display of 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 hardware and software decodings

ApsaraVideo Player SDK for Android supports hardware decoding based on the H.264 and H.265 standards. You can call the enableHardwareDecoder method to enable or disable the hardware decoding feature. By default, hardware decoding is enabled. If hardware decoding fails to be initialized, it is switched to software decoding to ensure normal playback. The following sample code provides an example:
// Enable hardware decoding. By default, hardware decoding is enabled.
mAliyunVodPlayer.enableHardwareDecoder(true);
If hardware decoding is switched to software decoding, the onInfo callback is invoked. The following sample code provides an example:
mApsaraPlayerActivity.setOnInfoListener(new IPlayer.OnInfoListener() {
    @Override
    public void onInfo(InfoBean infoBean) {
        if (infoBean.getCode() == InfoCode.SwitchToSoftwareVideoDecoder) {
            // Switch to software decoding.
        }
    }
});

Enable adaptive bitrate streaming

ApsaraVideo Player SDK for Android supports adaptive bitrate streaming of HTTP-Live-Streaming (HLS) or DASH video streams. After the player is prepared by using the prepare method, you can call the getMediaInfo method to query the bitrate information, which is indicated by the TrackInfo parameter. The following sample code provides an example:
List<TrackInfo> trackInfos  = aliyunVodPlayer.getMediaInfo().getTrackInfos();
During the playback, you can call the selectTrack method to switch the bitrate. If you pass SELECT_AVPTRACK_TYPE_VIDEO_AUTO to the method, adaptive bitrate streaming is enabled. The following sample code provides an example:
int index = trackInfo.getIndex();
// Switch the bitrate.
aliyunVodPlayer.selectTrack(index);
// Enable adaptive bitrate streaming.
aliyunVodPlayer.selectTrack(TrackInfo.AUTO_SELECT_INDEX);
The callback invoked by the OnTrackChangedListener method returns the switching result. You must configure the OnTrackChangedListener callback before you call the selectTrack method. The following sample code provides an example:
aliyunVodPlayer.setOnTrackChangedListener(new IPlayer.OnTrackChangedListener() {
    @Override
    public void onChangedSuccess(TrackInfo trackInfo) {
        // The bitrate switching is successful.
    }
    @Override
    public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
        // The bitrate switching fails. You can call the errorInfo.getMsg() method to find the cause of the failure.
    }
});

Capture snapshots

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 the OnSnapShotListener callback to obtain the bitmap. The following sample code provides an example:
// Configure the callback for snapshot capture.
aliyunVodPlayer.setOnSnapShotListener(new OnSnapShotListener(){
    @Override
    public void onSnapShot(Bitmap bm, int with, int height){
        // Obtain the bitmap and the width and height of the video image. 
    }
});
// Capture a snapshot of the current video image.
aliyunVodPlayer.snapshot();

Configure video preview

ApsaraVideo Player SDK for Android integrates other configurations of ApsaraVideo VOD to support previews of videos. Only VidSts and VidAuth sources can be previewed. We recommend that you preview only VidAuth sources in ApsaraVideo VOD. For more information about how to configure and use the preview feature, see Configure the preview feature.

After you enable the preview feature, you can call the setPreviewTime() method in the VidPlayerConfigGen class to specify the preview duration. The following sample code provides an example. In this example, VidSts is used.
VidSts vidSts = new VidSts;
....
VidPlayerConfigGen configGen = new VidPlayerConfigGen();
configGen.setPreviewTime(20); // Set the preview duration to 20s.
vidSts.setPlayConfig(configGen); // Configure the settings for the player.
...
After you specify the preview duration, ApsaraVideo Player SDK for Android allows you to preview a video for the specified duration instead of the whole video.
Note
  • You can use the VidPlayerConfigGen class to set the request parameters that are supported by the server. For more information, see Request parameters.
  • The preview feature is not supported for Flash Video (FLV) and MP3 files.

Configure a blacklist

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. The following sample code provides an example:
DeviceInfo deviceInfo = new DeviceInfo();
deviceInfo.model="Lenovo K320t";
AliPlayerFactory.addBlackDevice(BlackType.HW_Decode_H264 ,deviceInfo );
Note 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. The following sample code provides an example:
// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Set the referer. Example: http://example.aliyundoc.com. Note: You must add the protocol header when you set the referer.
config.mReferrer = referrer;
.... // Configure other settings.
  // Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);

Specify the user agent

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 contains the user agent information in its requests. The following sample code provides an example:
// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Specify the user agent.
config.mUserAgent = "Required user agent";
.... // Configure other settings.
  // Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);

Set the network timeout period and retries

ApsaraVideo Player SDK for Android provides the PlayerConfig class for you to set the network timeout period and retries. The following sample code provides an example:
// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Specify the network timeout period. Unit: milliseconds.
config.mNetworkTimeout = 5000;
// Specify the maximum number of retries upon a network timeout. The retry interval equals the timeout period specified by the mNetworkTimeout parameter. The mNetworkRetryCount parameter specifies the maximum number of retries. A value of 0 indicates zero retry. The application determines the maximum number of retries. Default value: 2.
config.mNetworkRetryCount=2;
.... // Configure other settings.
  // Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);
Note
  • If you set the mNetworkRetryCount parameter to a value other than 0, the player retries the playback when it enters the loading status due to network errors. The maximum number of retries is specified by the mNetworkRetryCount parameter, and the retry interval equals the timeout period specified by the mNetworkTimeout parameter.
  • If loading persists after the maximum number of retries is reached, a callback is invoked by the onError method. In this case, the AVPErrorModel.code method returns ERROR_LOADING_TIMEOUT.
  • If the mNetworkRetryCount parameter is set to 0, the onInfo callback is invoked when a network timeout occurs. In this case, the InfoBean.getCode() method returns InfoCode.NetworkRetry. To resolve the issue, you can call the reload method of ApsaraVideo Player SDK for Android to reload network packets or perform other operations as required.

Configure buffer and latency settings

ApsaraVideo Player SDK for Android provides the PlayerConfig class for you to configure buffer and latency settings. The following sample code provides an example:
// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Set the maximum latency. This parameter is valid only for live streaming. If the latency exceeds the maximum limit, ApsaraVideo Player SDK synchronizes frames to ensure that the latency is within the limit. 
config.mMaxDelayTime = 5000;
// Set the maximum buffer duration. Unit: milliseconds. This parameter specifies the maximum buffer duration for the player to load data at a time. 
config.mMaxBufferDuration = 50000;
// Set the peak buffer duration. Unit: milliseconds. The player starts to load data if the network condition is unstable. This parameter specifies the buffer duration beyond which the player stops loading data in this case. 
config.mHighBufferDuration = 3000;
// Set the startup loading duration. Unit: milliseconds. A smaller value indicates a shorter startup loading duration. In this case, the player starts to load data sooner after the start of playback. 
config.mStartBufferDuration = 500;
.... // Configure other settings.
// Set the maximum cache duration. Unit: milliseconds. Default value: 0. 
config.mMaxBackwardBufferDurationMs = 0;

// Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);
Notice Make sure that the value of the mStartBufferDuration parameter is not greater than that of the mHighBufferDuration parameter, and that the value of the mHighBufferDuration parameter is not greater than that of the mMaxBufferDuration parameter.

Configure HTTP headers

ApsaraVideo Player SDK for Android provides the PlayerConfig class for you to add HTTP headers to requests. The following sample code provides an example:
// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Define a header.
String[] headers = new String[1];
headers[0]="Host:example.com"; // For example, add the host information to the header. 
// Configure the headers.
config.setCustomHeaders(headers);
.... // Configure other settings.
  // Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);

Configure the performance

Configure local caching

ApsaraVideo Player SDK for Android allows you to cache videos during playback. This saves your traffic during loop playback. To configure the play-and-cache feature, configure the CacheConfig class before you call the prepare method. The following sample code provides an example:
CacheConfig cacheConfig = new CacheConfig();
// Enable the play-and-cache feature.
cacheConfig.mEnable = true;
 // Specify the maximum duration of a single cached file. Files whose duration exceeds the maximum limit are not cached.
cacheConfig.mMaxDurationS =100;
// Specify the cache directory.
cacheConfig.mDir = "The directory of the cached file";
 // Specify the maximum size of the cache directory. When the total size of cached files in the cache directory exceeds the maximum limit, the earliest cached files are overwritten.
cacheConfig.mMaxSizeMB = 200;
// Configure the cache settings for the player.
mAliyunVodPlayer.setCacheConfig(cacheConfig);
You can use cached files only after you call the setCacheConfig method. After a video is cached, the cached file is used in the following scenarios:
  • If the loop playback feature is enabled by using the setLoop(true) method, the cached file is used when the player replays the video.
  • After you cache a video and create a player to play the video, the new player plays the video by using the cached video file.
    Note For ID-based playback, information such as the audio or video ID is required to find cached files. An online request must be sent to obtain the required information that determines which cached files are needed for ID-based playback.
The following table describes the methods that can be used to obtain the path of a cached file.
Method Description Parameter Return value
public String getCacheFilePath(String URL) Queries the path of a cached file based on the video URL. To obtain the path, make sure that you have called the setCacheConfig method. URL The absolute path of the cached file.
public String getCacheFilePath(String vid, String format, String definition, int previewTime) Queries the path of a cached file based on the audio or video ID. To obtain the path, make sure that you have called the setCacheConfig method.
  • vid: the video ID.
  • format: the video format.
  • definition: the video definition.
  • previewTime: the preview duration.
The absolute path of the cached file.
The following information describes the limits on the play-and-cache feature:
  • If the player plays UrlSource streams by using the HLS protocol based on the URL in an M3U8 playlist, the player does not cache the video during the playback. For other supported formats, the player caches videos during playback as configured.
  • If you use VidAuth or VidSts sources for playback, the player caches videos during playback as configured.
  • A video is considered cached after the player reads all video data. Caching fails if the stop method is called or a callback is invoked by the onError method before the player reads all video data.
  • Seeking to a position inside the cached video does not affect the caching result. Seeking to a position outside the cached video may cause a caching failure.
  • An encrypted video cannot be cached if the verification information in the security file for encryption verification does not match the application information.
  • The onInfo callback is invoked to return the caching result.
mAliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
    @Override
    public void onInfo(InfoBean infoBean) {
        if(infoBean.getCode() == InfoCode.CacheSuccess){
            // Indicate that the caching succeeds. 
        }else if(infoBean.getCode() == InfoCode.CacheError){
            // Indicate that the caching fails.
        }
    }
});

Configure video preload

ApsaraVideo Player SDK for Android supports video preload, which is an upgrade of the play-and-cache feature. The video preload feature allows you to specify the maximum size of memory that can be occupied by cached videos. This helps reduce the startup loading duration.

The following information describes the limits on the video preload feature:
  • You can preload only one MP4, MP3, FLV, or HLS file at a time.
  • You can preload only one file that is played based on the URL. You cannot preload VidAuth or VidSts sources.
  1. Enable the video preload feature.
    By default, the video preload feature is disabled. To use this feature, you must manually enable it. You can call the enableLocalCache method in the AliPlayerGlobalSettings class.
    /**
     *  Enable video preload. After this feature is enabled, a media file is cached on your device. 
     *
     *  @param enable - Specifies whether to enable the video preload feature. Valid values: true and false. A value of true indicates that the video preload feature is enabled. A value of false indicates that the video preload feature is disabled. Default value: false. 
     *  @param maxBufferMemoryKB - The maximum size of memory that can be occupied by a single video file to be cached. If the size of the video file exceeds the maximum limit, the video file is not cached. Unit: KB. 
     *  @param localCacheDir - The directory of the cached file, which is an absolute path. 
     */
    public static void enableLocalCache(boolean enable,
                                        int maxBufferMemoryKB,
                                        java.lang.String localCacheDir)
    
     /**
      * Configure settings for clearing cached files. 
      *
      * @param expireMin - The retention period after which the file expires. Unit: minutes. By default, the retention period for each cached file is 30 days. A cached file is deleted after the specified period. 
      * @param maxCapacityMB - The maximum size of cached data. Unit: MB. By default, the maximum size of cached data is 20 GB. If the specified maximum size is exceeded, the system deletes cached files based on the point in time when the file is cached until the size of the cached data is less than or equal to the specified maximum size. During this process, the system preferentially deletes the earliest files that are cached. 
      * @param freeStorageMB - The minimum idle space of the disk. Unit: MB. Default value: 0. If the idle space of the disk is less than the specified minimum space, the system deletes cached files based on the point in time when the file is cached until the idle space of the disk is greater than or equal to the specified minimum space. During this process, the system preferentially deletes the earliest files that are cached. 
      */
     public static void setCacheFileClearConfig(long expireMin,
                                               long maxCapacityMB,
                                               long freeStorageMB)
    
      /**
       * Configure the callback for the URL hash value of a video file. If you do not configure the callback, the SDK calculates the URL hash value by using the MD5 message-digest algorithm. 
       */
      public static void setCacheUrlHashCallback(AliPlayerGlobalSettings.OnGetUrlHashCallback cb)
    Note
    • If the streaming URL of a video file contains authentication parameters, the values of the authentication parameters change during the loading and playback of the video file. You can calculate the MD5 hash value after you remove the authentication parameters. For example, http://****.mp4?aaa is the streaming URL of a video file and contains authentication parameters. In this case, the URL http://****.mp4 is used to calculate the MD5 hash value when the video file is loaded.
    • If your server supports both HTTP and HTTPS protocols and a video file can be specified by using two URLs with the same elements but different protocols, you can remove the protocol header of the URLs or use the URL with the HTTP protocol to calculate the MD5 hash value. Examples:
      • If the streaming URLs of a video file are https://****.mp4 and http://****.mp4, the MD5 hash value is calculated by using ****.mp4 when the video file is loaded.
      • If the streaming URL of the video file is https://****.mp4, the MD5 hash value is calculated by using the URL http://****.mp4 when the video file is loaded.
  2. Obtain an AliMediaLoader instance.

    The AliMediaLoader instance is a singleton object. You can create only one AliMediaLoader instance regardless of the times for which you obtain the instance.

    MediaLoader mediaLoader = MediaLoader.getInstance();
  3. Configure the AliMediaLoader instance.

    Configure listeners and start to load video files.

    /**
     * Configure listeners for loading status.
     */
    mediaLoader.setOnLoadStatusListener(new MediaLoader.OnLoadStatusListener() {
        @Override
        public void onError(String url, int code, String msg) {
            // Listens to a loading error.
        }
    
        @Override
        public void onCompleted(String s) {
            // Listens to the completion of loading.
        }
    
        @Override
        public void onCanceled(String s) {
            // Listens to the cancellation of loading.
        }
    });
    /**
     * Start to load video files. Asynchronous loading is supported. You can load one or more video files at a time. 
     * @param url - The URL of the video file. 
     * @param duration - The loading duration. Unit: milliseconds. 
     */
    mediaLoader.load("url","duration");
  4. 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 for deletion. To delete the loaded video files, you must go to the directories of the specified files and manually delete them.

Query 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. The following sample code provides an example:
mAliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
    @Override
    public void onInfo(InfoBean infoBean) {
        if(infoBean.getCode() == InfoCode.CurrentDownloadSpeed){
            // The download speed.
            long extraValue = infoBean.getExtraValue();
        }
    }
});

Configure networks

Enable HTTP/2

ApsaraVideo Player SDK for Android supports HTTP/2. You can enable HTTP/2 to realize the multiplexing of requests. This prevents head-of-line (HOL) blocking and therefore improves playback performance. The following sample code provides an example:
AliPlayerGlobalSettings.setUseHttp2(true);

Configure video download settings

ApsaraVideo Player SDK for Android allows you to download videos from VidSts and VidAuth sources in ApsaraVideo VOD. You can download videos in secure download mode or normal download mode. To configure the download settings, log on to the ApsaraVideo VOD console and choose Configuration Management > CDN Configuration > Download in the left-side navigation pane.
  • Normal download

    Videos that are downloaded in normal download mode are not encrypted by Alibaba Cloud and can be played by third-party players.

  • Secure download

    Videos that are downloaded in secure download mode are encrypted by Alibaba Cloud. You cannot use third-party players to play the downloaded videos. You can use only ApsaraVideo Player to play them.

  1. Use the AliDownloaderFactory class to create and configure a download object. The following sample code provides an example:
    AliMediaDownloader mAliDownloader = null;
    ......
    // Create a download object.
    mAliDownloader = AliDownloaderFactory.create(getApplicationContext());
    // Set the path for storing downloaded files.
    mAliDownloader.setSaveDir("The path of the folder for storing downloaded files");
    ApsaraVideo Player SDK for Android allows you to download videos that are encrypted by using Alibaba Cloud proprietary cryptography. For security reasons, you must configure a security file for encryption verification in the SDK. We recommend that you configure the security file in your application, once for all. The following sample code provides an example:
    PrivateService.initService(getApplicationContext(),  "The path of the encryptedApp.dat file");
    Notice If you download a video in secure download mode and the information in the security file for encryption verification does not match the application information, the video download fails.
  2. Configure listeners.
    The download object provides multiple listeners. The following sample code provides an example:
    mAliDownloader.setOnPreparedListener(new AliMediaDownloader.OnPreparedListener() {
       @Override
       public void onPrepared(MediaInfo mediaInfo) {
           // Listens to the completion of preparing the content to be downloaded.
       }
    });
    mAliDownloader.setOnProgressListener(new AliMediaDownloader.OnProgressListener() {
       @Override
       public void onDownloadingProgress(int percent) {
           // Listens to the percentage of the download progress.
       }
       @Override
       public void onProcessingProgress(int percent) {
           // Listens to the percentage of the processing progress.
       }
    });
    mAliDownloader.setOnErrorListener(new AliMediaDownloader.OnErrorListener() {
       @Override
       public void onError(ErrorInfo errorInfo) {
           // Listens to a download error.
       }
    });
    mAliDownloader.setOnCompletionListener(new AliMediaDownloader.OnCompletionListener() {
       @Override
       public void onCompletion() {
           // Listens to a successful download.
       }
    });
  3. Prepare the download source.
    You can call the prepare method to prepare a download source. VidSts and VidAuth sources are supported. In this example, VidSts is used.
    // Add the VidSts download source.
    VidSts aliyunVidSts = new VidSts();
    aliyunVidSts.setVid(Video ID);
    aliyunVidSts.setAccessKeyId(Temporary AccessKey ID);
    aliyunVidSts.setAccessKeySecret(Temporary AccessKey secret);
    aliyunVidSts.setSecurityToken(Security token);
    aliyunVidSts.setRegion(Access region);
    // Prepare the download source.
    mAliDownloader.prepare(aliyunVidSts)
  4. Select the content to be downloaded from the prepared download source.
    After the download source is prepared, a callback is invoked by the onPrepared method. Select a track for download. The following sample code provides an example:
    public void onPrepared(MediaInfo mediaInfo) {
        // Listens to the completion of preparing the content to be downloaded.
        List<TrackInfo> trackInfos = mediaInfo.getTrackInfos();
        // In this example, download the content of the first track.
        mAliDownloader.selectItem(trackInfos.get(0).getIndex());
    }
  5. Update the download source and start the download.
    VidSts or VidAuth sources may expire before the download. Therefore, we recommend that you update the download source before you start the download. The following sample code provides an example:
    // Update the download source.
    mAliDownloader.updateSource(VidSts);
    // Start the download.
    mAliDownloader.start();
  6. Release the downloader 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 the onCompletion or onError callback is invoked. The following sample code provides an example:
    mAliDownloader.stop();
    mAliDownloader.release();
  7. Delete a downloaded file.
    You can delete a downloaded file during the download or after the download is complete. The following sample code provides an example:
    // Delete the file by using the download object.
    mAliDownloader.deleteFile();
    // Delete the file by using the static method.
    AliDownloaderFactory.deleteFile("The directory of the downloaded file",vid, format,index);

Play encrypted videos

ApsaraVideo Player SDK for Android allows you to play on-demand videos encrypted based on HLS encryption, Alibaba Cloud proprietary cryptography, or digital rights management (DRM) encryption. The SDK allows you to play live streams encrypted only based on DRM encryption. For more information, see Encrypt videos for playback.

Configure Native RTS SDK

You can integrate ApsaraVideo Player SDK for Android with Native RTS SDK to use the Real-Time Streaming (RTS) feature. For more information, see Native RTS SDK for Android.

References

API reference