This topic describes the advanced features of ApsaraVideo Player SDK for Android and provides 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 leverages technologies such as preloading to minimize the loading time of short videos. We recommend that you do not enable this feature for long videos.

Limits

We recommend that you create multiple AliPlayer instances to enable list playback for short videos. The following items describe the limits of AliListPlayer. For more information, see Usage notes for Android devices.

  • AliListPlayer does not support video playback based on PlayAuth.
  • You can configure only one AliListPlayer instance for ApsaraVideo Player SDK. Multiple AliListPlayer instances may cause issues during video playback.
  • AliListPlayer does not support playing M3U8 files in versions of ApsaraVideo Player SDK for Android earlier than V5.4.5.0. In ApsaraVideo Player SDK for Android V5.4.5.0 and later, you need to enable the local caching feature to play M3U8 files.

Procedure

  1. Create a player.
    Create an AliListPlayer instance by using the AliPlayerFactory class. Sample code:
    AliListPlayer aliyunListPlayer;
    .....
    aliyunListPlayer = AliPlayerFactory.createAliListPlayer(getApplicationContext());
    aliyunListPlayer.setTraceId("traceId"); // The trace ID is the unique identifier of the device or 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. If you do not configure listeners, you cannot receive notifications about player-related events, such as playback failures or the playback progress. We recommend that you configure listeners. You can configure multiple listeners for your player. We recommend that you configure the following listeners: OnPreparedListener, OnErrorListener, OnCompletionListener, OnLoadingStatusListener, and OnInfoListener.
    aliyunListPlayer.setOnCompletionListener(new IPlayer.OnCompletionListener() {
        @Override
        public void onCompletion() {
            // The listener for the end of playback.
        }
    });
    aliyunListPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
        @Override
        public void onError(ErrorInfo errorInfo) {
            // The listener for error occurrence.
        }
    });
    aliyunListPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
        @Override
        public void onPrepared() {
            // The listener for successful preparation.
        }
    });
    aliyunListPlayer.setOnVideoSizeChangedListener(new IPlayer.OnVideoSizeChangedListener() {
        @Override
        public void onVideoSizeChanged(int width, int height) {
            // The listener for the change of video resolution.
        }
    });
    aliyunListPlayer.setOnRenderingStartListener(new IPlayer.OnRenderingStartListener() {
        @Override
        public void onRenderingStart() {
            // The listener for the display of the first frame.
        }
    });
    aliyunListPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
        @Override
        public void onInfo(int type, long extra) {
            // The listener for other events. The type parameter contains multiple values that indicate various events, such as the start of loop playback, buffer position, current playback position, and the start of autoplay.
        }
    });
    aliyunListPlayer.setOnLoadingStatusListener(new IPlayer.OnLoadingStatusListener() {
        @Override
        public void onLoadingBegin() {
            // The listener for the start of buffering. 
        }
        @Override
        public void onLoadingProgress(int percent, float kbps) {
            // The listener for the buffering progress.
        }
        @Override
        public void onLoadingEnd() {
            // The listener for the completion of buffering.
        }
    });
    aliyunListPlayer.setOnSeekCompleteListener(new IPlayer.OnSeekCompleteListener() {
        @Override
        public void onSeekComplete() {
            // The listener for the end of seeking.
        }
    });
    aliyunListPlayer.setOnSubtitleDisplayListener(new IPlayer.OnSubtitleDisplayListener() {
        @Override
        public void onSubtitleShow(long id, String data) {
            // The listener for the display of subtitles.
        }
        @Override
        public void onSubtitleHide(long id) {
            // The listener for the hiding of subtitles.
        }
    });
    aliyunListPlayer.setOnTrackChangedListener(new IPlayer.OnTrackChangedListener() {
        @Override
        public void onChangedSuccess(TrackInfo trackInfo) {
            // The listener for the success of switching between audio and video streams or between resolutions.
        }
        @Override
        public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
            // The listener for the failure of switching between audio and video streams or between resolutions.
        }
    });
    aliyunListPlayer.setOnStateChangedListener(new IPlayer.OnStateChangedListener() {
        @Override
        public void onStateChanged(int newState) {
            // The listener for the change of player status.
        }
    });
    aliyunListPlayer.setOnSnapShotListener(new IPlayer.OnSnapShotListener() {
        @Override
        public void onSnapShot(Bitmap bm, int with, int height) {
            // The listener for the capture of snapshots.
        }
    });
  3. Specify the number of videos that you want to preload.
    You can specify the number of videos that you want to preload based on your business requirements. This reduces the startup time. Sample code:
    // Specify 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 playback source and UrlSource playback source. Url is the playback URL of the video. Sample code:
    • Url: The playback URL can be the URL of an audio file or video file in ApsaraVideo VOD or on a third-party video-on-demand (VOD) platform. You can call the GetPlayInfo operation to obtain the playback URL of an audio file or video file in ApsaraVideo VOD. We recommend that you use a server SDK to obtain media playback URLs in ApsaraVideo VOD. This frees you from complex signature calculations. For more information about the GetPlayInfo operation, see OpenAPI Explorer.
    • Vid: The audio or video ID. To obtain the ID, 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 a 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 indicates 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 you did not specify, check whether you have specified the same ID for multiple videos. You can set the unique ID to any string that you prefer.
  5. Configure the user interface (UI) view.
    You can call the SurfaceView or TextureView method to configure the view.
    • The following sample code describes how to use SurfaceView to configure the view:
      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);
          }
      });
    • The following sample code describes how to use TextureView to configure the view:
      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 video source.
    After you add one or more playback sources and enable autoplay, call moveTo to play the content from the specified playback source. Sample code:
    // Enable autoplay.
    aliyunListPlayer.setAutoPlay(true);
    
    // Call the following method for URL-based playback.
    aliyunVodPlayer.moveTo(String uid);
    // Call the following method for VID-based playback. You must obtain the Security Token Service (STS) token and AccessKey pair before you call this method. For more information, see Create a RAM 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 moveToPrev to play the previous video or call moveToNext to play the next video. Sample code:
    // Enable autoplay.
    aliyunListPlayer.setAutoPlay(true);
    
    // Play the next video.  You can call this method only for URL-based playback.  
    aliyunVodPlayer.moveToNext();
    // Play the previous video. You can call this method only for URL-based playback.  
    aliyunVodPlayer.moveToPrev();
    // Play the next video. You can call this method only for VID-based playback. 
    aliyunVodPlayer.moveToNext(StsInfo info);
    // Play the previous video. You can call this method only for VID-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, ASS, or VTT format for videos. Sample code:

  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 or VTT 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) {
                // The listener for the display of subtitles in the ASS format.
            assSubtitleView.show(id,data);
    
            // The listener for 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) {
                // The listener for the hiding of subtitles in the ASS format.
                assSubtitleView.dismiss(id);
    
            // The listener for 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.
    //trackIndex: specifies whether subtitles are displayed or hidden. true indicates that subtitles are displayed and false indicates that 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

Note You must change the decoding method 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 the enableHardwareDecoder method to enable or disable the hardware decoding feature. By default, hardware decoding is enabled. If hardware decoding fails to be initialized, software decoding is automatically used to ensure video 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.
        }
    }
});

Enable adaptive bitrate streaming

Note
  • 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 in 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 describes 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 HTTP-Live-Streaming (HLS) or DASH video streams. After the prepare method is called, call getMediaInfo to obtain the stream 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 from 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. Sample code:
// 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 specific 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); // 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.
Note
  • 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 );
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 perform 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

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 the 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);

Specify the network timeout period and number of retries

ApsaraVideo Player SDK for Android provides the PlayerConfig class for you to specify 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);
Note
  • 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 the reload method provided by ApsaraVideo Player SDK for Android to reload network packets or perform other operations based on your business requirements.

Control the buffer and latency

ApsaraVideo Player SDK for Android provides the PlayerConfig class that allows you to configure buffer and latency settings. Sample code:
// 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. This parameter specifies the peak buffer duration. After the peak buffer duration elapses, the player stops loading data if the network conditions are poor. 
config.mHighBufferDuration = 3000;
// Set the startup buffer duration Unit: milliseconds. A smaller value indicates a shorter startup buffer duration. In this case, the player starts to load data sooner after the playback starts. 
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);
Important
  • Make sure that the value of the mStartBufferDuration parameter is not greater than the value of the mHighBufferDuration parameter. Make sure that the value of the mHighBufferDuration parameter is not greater than the value of the mMaxBufferDuration parameter.
  • When mMaxBufferDuration is greater than 5 minutes, the peak buffer duration is set to 5 minutes to prevent memory exceptions caused by excessive buffer size. When mMaxBufferDuration is greater than 50,000 ms (50 seconds), you can enable large cache to reduce the memory usage and improve playback performance. For more information, see Configure large cache.

Configure HTTP headers

ApsaraVideo Player SDK for Android provides the PlayerConfig class that allows 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 header.
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 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 manually enable it. You can call the enableLocalCache method in the AliPlayerGlobalSettings class. Sample code:
/**
 *  Enable local caching. After this feature is enabled, a media file is cached on your device. 
 *
 *  @param enable - Specifies whether to enable the local caching feature. Valid values: true and false. true indicates that the video preload feature is enabled and false indicates that the video preload feature is disabled. Default value: false. 
 * @param maxBufferMemoryKB -This parameter is deprecated in the new version.
 *  @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 -This parameter is deprecated in the new version. 
  * @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 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 cache files. 
  * @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 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 cache files. 
  */
 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 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 local caching 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.

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);

Configure large cache

You can set the maximum buffer duration of data to cache video in the memory during playback, which improves the playback performance and experience. If the maximum buffer duration is set too large, the buffer consumes excessive memory. You can use the large cache feature to cache videos in files, which reduces memory usage and improves player performance.

When mMaxBufferDuration is greater than 50,000 ms, you can enable local caching to automatically trigger large cache. Procedure:

  1. 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 the enableLocalCache method in the AliPlayerGlobalSettings class. For more information about the sample code, see the Enable local caching section in the Configure local caching topic.
  2. 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 in Configure local caching.

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.
Note 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);
  1. Enable the local caching feature. For more information, see Configure local caching.
  2. 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();
  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) {
            // The listener for a loading error.
        }
    
        @Override
        public void onCompleted(String s) {
            // The listener for the end of loading.
        }
    
        @Override
        public void onCanceled(String s) {
            // The listener for 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 to delete the loaded video files. You must delete the video files in the corresponding directory in your application.

Obtain the download speed

ApsaraVideo Player SDK for Android provides the getExtraValue method that allows you to obtain the download speed of specified videos. You can obtain the download speed from the onInfo callback. 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

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 improves playback performance. Sample code:
AliPlayerGlobalSettings.setUseHttp2(true);

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 and secure download modes 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

  1. Optional:Configure the security file for encryption verification. You must configure the security file only when you use the secure download mode.
    Note Make 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 Secure download.

    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 device and set this parameter to the path in which the file is stored.
  2. Create and configure a 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");
  3. Configure listeners.
    The download object provides multiple listeners. Sample code:
    mAliDownloader.setOnPreparedListener(new AliMediaDownloader.OnPreparedListener() {
       @Override
       public void onPrepared(MediaInfo mediaInfo) {
           // The listener for the preparation of the content to be downloaded.
       }
    });
    mAliDownloader.setOnProgressListener(new AliMediaDownloader.OnProgressListener() {
       @Override
       public void onDownloadingProgress(int percent) {
           // The listener for the percentage of the download progress.
       }
       @Override
       public void onProcessingProgress(int percent) {
           // The listener for the percentage of the processing progress.
       }
    });
    mAliDownloader.setOnErrorListener(new AliMediaDownloader.OnErrorListener() {
       @Override
       public void onError(ErrorInfo errorInfo) {
           // The listener for a download error.
       }
    });
    mAliDownloader.setOnCompletionListener(new AliMediaDownloader.OnCompletionListener() {
       @Override
       public void onCompletion() {
           // The listener for a successful download.
       }
    });
  4. Prepare the download source.
    You can call the prepare method to prepare a download source. VidSts and VidAuth sources are supported. The following code uses a VidSts source as an example:
    // 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)
    Note The output file is in the same format as the input file and cannot be changed.
  5. Select the content to be downloaded from the prepared download source.
    After the download source is prepared, the OnPreparedListener callback is invoked. 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) {
        // The content to be downloaded is prepared.
        List<TrackInfo> trackInfos = mediaInfo.getTrackInfos();
        // Download the information about tracks, such as the first track.
        mAliDownloader.selectItem(trackInfos.get(0).getIndex());
    }
  6. Update the download source and start the download.
    VidSts or VidAuth 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();
  7. 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 the onCompletion or onError callback is invoked. Sample code:
    mAliDownloader.stop();
    mAliDownloader.release();
  8. 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.
    AliDownloaderFactory.deleteFile("The directory of the downloaded file",vid, format,index);

Play encrypted videos

ApsaraVideo Player SDK for Android allows you to play encrypted videos on demand. It supports HLS encryption, Alibaba Cloud proprietary cryptography, or digital rights management (DRM) encryption. The SDK allows you to play only DRM-encrypted live streams. For more information, 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.

References