All Products
Search
Document Center

ApsaraVideo VOD:Advanced features

Last Updated:Mar 14, 2024

This topic describes the advanced features of ApsaraVideo Player SDK for Android and provides sample code. For more information about other features, see API operations for ApsaraVideo Player SDK for Android.

Configure playback

Enable list playback for short videos

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

Limits

To enable list playback for short videos, we recommend that you create multiple AliPlayer instances. The following items describe the limits on AliListPlayer. For more information, see Short video list player.

  • 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 or 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. 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. We recommend that you configure the following listeners: OnPreparedListener, OnErrorListener, OnCompletionListener, OnLoadingStatusListener, and OnInfoListener.

    Show code

    aliyunListPlayer.setOnCompletionListener(new IPlayer.OnCompletionListener() {
        @Override
        public void onCompletion() {
            // Listen for the end of playback.
        }
    });
    aliyunListPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
        @Override
        public void onError(ErrorInfo errorInfo) {
            // Listen for errors.
        }
    });
    aliyunListPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
        @Override
        public void onPrepared() {
            // Listen for successful preparation.
        }
    });
    aliyunListPlayer.setOnVideoSizeChangedListener(new IPlayer.OnVideoSizeChangedListener() {
        @Override
        public void onVideoSizeChanged(int width, int height) {
            // Listen for the change of video resolution.
        }
    });
    aliyunListPlayer.setOnRenderingStartListener(new IPlayer.OnRenderingStartListener() {
        @Override
        public void onRenderingStart() {
            // Listen for the display of the first frame.
        }
    });
    aliyunListPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
        @Override
        public void onInfo(int type, long extra) {
            // Listen 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() {
            // Listen for the start of buffering. 
        }
        @Override
        public void onLoadingProgress(int percent, float kbps) {
            // Listen for the buffering progress.
        }
        @Override
        public void onLoadingEnd() {
            // Listen for the end of buffering.
        }
    });
    aliyunListPlayer.setOnSeekCompleteListener(new IPlayer.OnSeekCompleteListener() {
        @Override
        public void onSeekComplete() {
            // Listen for the end of seeking.
        }
    });
    aliyunListPlayer.setOnSubtitleDisplayListener(new IPlayer.OnSubtitleDisplayListener() {
        @Override
        public void onSubtitleShow(long id, String data) {
            // Listen for the display of subtitles.
        }
        @Override
        public void onSubtitleHide(long id) {
            // Listen for the hiding of subtitles.
        }
    });
    aliyunListPlayer.setOnTrackChangedListener(new IPlayer.OnTrackChangedListener() {
        @Override
        public void onChangedSuccess(TrackInfo trackInfo) {
            // Listen for the success of switching between audio and video streams or between resolutions.
        }
        @Override
        public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
            // Listen for the failure of switching between audio and video streams or between resolutions.
        }
    });
    aliyunListPlayer.setOnStateChangedListener(new IPlayer.OnStateChangedListener() {
        @Override
        public void onStateChanged(int newState) {
            // Listen for the change of player status.
        }
    });
    aliyunListPlayer.setOnSnapShotListener(new IPlayer.OnSnapShotListener() {
        @Override
        public void onSnapShot(Bitmap bm, int with, int height) {
            // Listen 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 helps reduce the startup time. Sample code:

    // Specify the number of videos that you want to preload. The total number of loaded videos equals one plus twice the specified number. 
    aliyunListPlayer.setPreloadCount(int count);
  4. Add or remove multiple playback sources.

    List playback supports video playback based on Vid and UrlSource. You can use VidSts or VidPlayAuth to play videos based on Vid. 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 or video file in ApsaraVideo VOD. We recommend that you integrate ApsaraVideo VOD SDKs to obtain media playback URLs. This frees you from complex signature calculation. For more information about the GetPlayInfo operation, visit 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 Vid 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

    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 is not the one you specified, check whether you specify the same ID for multiple videos. You can set the unique ID to any string that you prefer.

  5. Configure the 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:

      Show code

      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:

      Show code

      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:

    Show 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);
    // Call the following method for Vid-based playback. You must obtain a playback credential for the video before you call this method and specify the PlayAuthInfo parameter when you call this method. 
    aliyunVodPlayer.moveTo(String uid, PlayAuthInfo info);
  7. Play the previous or next video in the list.

    • After you call moveTo to play a video, you can call moveToPrev to play the previous video or call moveToNext to play the next video. Sample code:

      Show code

      // Enable autoplay.
      aliyunListPlayer.setAutoPlay(true);
      
      // Play the next video. You can call this method only for URL-based playback. The method is invalid for Vid-based playback. 
      aliyunVodPlayer.moveToNext();
      // Play the previous video. You can call this method only for URL-based playback. The method is invalid for Vid-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);
      // Play the next video. You can call this method only when you use playback credentials for Vid-based playback. 
      aliyunVodPlayer.moveToNext(PlayAuthInfo info);
      // Play the previous video. You can call this method only when you use playback credentials for Vid-based playback. 
      aliyunVodPlayer.moveToPrev(PlayAuthInfo info);
    • Before you call the MoveTo or MoveToNext method, obtain the playback credential. You can apply for playback credentials by using video IDs.

      Note

      To play a video based on VidPlayAuth, you must apply for a playback credential by using the video ID.

      Show code

      requestAuth(source.getVideoId(), new OnRequestAuthResultListener() {
          @Override
          public void onResult(VidAuth vidAuth) {
              mVideoListPlayer.moveToNext(createVidAuth(vidAuth));
          }
      });
      
      private PlayAuthInfo createVidAuth(VidAuth vidAuth) {
          if (vidAuth == null) {
              return new PlayAuthInfo();
          }
          PlayAuthInfo playAuthInfo = new PlayAuthInfo();
          playAuthInfo.setPlayAuth(vidAuth.getPlayAuth());
          return playAuthInfo;
      }
  8. Optional. Enable the pre-rendering feature to ensure smooth video switching.

    Note

    This feature is supported only in ApsaraVideo Player SDK for Android V5.5.2.0 or later. You must enable local caching to use this feature. For more information, see Configure local caching.

    The getPreRenderPlayer and moveToNextWithPrerendered operations are provided in ApsaraVideo Player SDK for Android V5.5.2.0 or later. This allows you to improve the smoothness of video switching. The following section describes how to use the operations when you integrate different versions of ApsaraVideo Player SDK for Android:

    ApsaraVideo Player SDK for Android V5.5.2.0 or later integrated

    Use the getPreRenderPlayer operation. Sample code:

    Show code

    // You can use the getPreRenderPlayer operation only when you use the moveToNext operation. The local caching feature must be enabled. 
    IPlayer preRenderPlayer = listPlayer.getPreRenderPlayer();
    if (preRenderPlayer != null) {
        // Call the setSurface operation.
        preRenderPlayer.setSurface(surface);
      preRenderPlayer.start();
      listPlayer.setSurface(null);
      // Call the moveToNextWithPrerendered operation instead of the moveToNext operation if you use STS-based playback.
      listPlayer.moveToNextWithPrerendered(createStsInfo(source));
    }

    ApsaraVideo Player SDK for Android updated from an earlier version to V5.5.2.0 or later

    You must modify the code in the earlier version of ApsaraVideo Player SDK for Android. The following procedure describes how to modify the code.

    1. Modify the logic related to render views.

      Earlier versions of ApsaraVideo Player SDK for Android use a global render view. When you switch a video source, the previous render view is removed from the layout and a new render view is added. ApsaraVideo Player SDK for Android V5.5.2.0 or later supports multiple render views. You can add multiple views to the RecyclerView.ViewHolder layout. This way, you can preload the next video source before you switch the video. This ensures smooth video switching. You must delete the code of the render view from an earlier version of ApsaraVideo Player SDK for Android and add the code of multiple render views to the later version of ApsaraVideo Player SDK for Android. Sample code:

      Show code

      /*
      Delete the following code.
           The following code adds a render view to FrameLayout and removes or adds mPlayerViewContainer when you switch the video source. 
      */
      private void initPlayer() {
          //...
          mPlayerViewContainer = View.inflate(getContext(), R.layout.layout_player_view, null);
          FrameLayout frameLayout = mPlayerViewContainer.findViewById(R.id.framelayout);
          FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
          FrameLayout.LayoutParams.MATCH_PARENT);
          View renderView = createRenderView(Common.RENDER_VIEW_NAME);
          frameLayout.addView(renderView, 0, params);
          //...
      }
      
      /*
      Add or modify the following code to add multiple render views.
          Modify the layout of items in RecyclerView and ViewHolder.
      */
      
      public final class MyHolder extends RecyclerView.ViewHolder {
          //...
          private Surface mSurface;
          MyHolder(@NonNull View itemView) {
              super(itemView);
              //...
              TextureView mTextureView = itemView.findViewById(R.id.texture_view);
              mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
                  @Override
                  public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                      mSurface = new Surface(surface);
                  }
      
                  @Override
                  public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {}
      
                  @Override
                  public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                      mSurface = null;
                      return false;
                  }
      
                  @Override
                  public void onSurfaceTextureUpdated(SurfaceTexture surface) {}
              });
          }
          //...
      
          // Add the getSurface operation. This operation is publicly accessible.
          public Surface getSurface() {
              return mSurface;
          }
      }

      The following sample code provides an example on how to modify the layout of items in RecyclerView:

      Show code

      <?xml version="1.0" encoding="utf-8"?>
      <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:id="@+id/root_view"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/black">
      
          <TextureView
              android:id="@+id/texture_view"
              android:layout_width="match_parent"
              android:layout_height="match_parent" />
      
      <! -- Delete the thumbnail. If a black screen appears, you can retain the logic related to the thumbnail.  -->
      <!--    <FrameLayout-->
      <!--        android:id="@+id/player_view"-->
      <!--        android:layout_width="match_parent"-->
      <!--        android:layout_height="match_parent"-->
      <!--        android:clickable="false"-->
      <!--        android:clipChildren="false"-->
      <!--        android:focusable="false">-->
      
      <!--        <ImageView-->
      <!--            android:id="@+id/img_thumb"-->
      <!--            android:layout_width="match_parent"-->
      <!--            android:layout_height="match_parent"-->
      <!--            android:layout_gravity="center"-->
      <!--            android:adjustViewBounds="true"-->
      <!--            android:clickable="false"-->
      <!--            android:focusable="false"-->
      <!--            android:scaleType="fitXY" />-->
      
      <!--    </FrameLayout>-->
      
      </FrameLayout>
    2. Modify the logic for switching video sources.

      In ApsaraVideo Player SDK for Android V5.5.2.0 or later, the preRenderPlayer method is called when you call moveToNext. You must configure separate logic for the render view. The logic of the moveToNext, moveToPre, and moveTo operations are different. Sample code:

      Show code

      /*
          Note: mQuickPlayer is an instance of the AlivcQuickPlayer class and AlivcQuickPlayer encapsulates the ListPlayer operation. 
      */
      private void startPlay(int position, boolean isInitComplete) {
          //...
          // Query the ViewHolder instance based on the value of the position parameter.
          LittleVideoListAdapter.MyHolder holder = (LittleVideoListAdapter.MyHolder) recycler.findViewHolderForLayoutPosition(position);
      
          //...
      
          // 1. Specify Surface before you call the moveToPre operation.
          if (holder != null) {
              mQuickPlayer.setSurface(holder.getSurface());
          }
          mQuickPlayer.moveToPrev(video, position, mVideoSourceType);
      
          // 2. Specify Surface before you call the moveTo operation.
          if (holder != null) {
              mQuickPlayer.setSurface(holder.getSurface());
          }
          // Use mQuickPlayer.startPlay to call the moveTo operation in ApsaraVideo Player SDK.
          mQuickPlayer.startPlay(video, position, mVideoSourceType);
      
          // 3. Add a parameter to pass the value of Surface when you call the moveToPre operation.
          mQuickPlayer.moveToNext(video, position, mVideoSourceType, holder.getSurface());
      
          //...
      }

      The following sample code provides an example on how to modify the logic of the AlivcQuickPlayer class:

      Show code

      // Modify the logic of the moveToPre operation.
      public void moveToPrev(AlivcVideoInfo.Video source, final int position, VideoSourceType videoSourceType) {
          //...
          // Add the following code to your SDK.
          mVideoListPlayer.clearScreen();
          if (videoSourceType == VideoSourceType.TYPE_STS) {
              mVideoListPlayer.moveToPrev(createStsInfo(source));
          } else {
              mVideoListPlayer.moveToPrev();
          }
      }
      
      // Add a reload method for the moveToNext operation.
      public void moveToNext(AlivcVideoInfo.Video source, int position, VideoSourceType videoSourceType, Surface surface) {
          //...
          // Obtain and use the preRenderPlayer instance for playback when you call the moveToNext operation.
          IPlayer preRenderPlayer = mVideoListPlayer.getPreRenderPlayer();
          if (preRenderPlayer != null) {
              preRenderPlayer.clearScreen();
              preRenderPlayer.setSurface(surface);
              preRenderPlayer.start();
              mVideoListPlayer.setSurface(null);
          } else {
              mVideoListPlayer.clearScreen();
              mVideoListPlayer.setSurface(surface);
          }
      
          // STS-based playback
          if (videoSourceType == VideoSourceType.TYPE_STS) {
              // If preRenderPlayer exists, call moveToNextWithPrerendered to play videos.
              if (preRenderPlayer != null) {
                  mVideoListPlayer.moveToNextWithPrerendered(createStsInfo(source));
              } else {
                  mVideoListPlayer.moveToNext(createStsInfo(source));
              }
          } else {
              // URL-based playback
              if (preRenderPlayer != null) {
                  mVideoListPlayer.moveToNextWithPrerendered();
              } else {
                  mVideoListPlayer.moveToNext();
              }
          }
      }
    3. Optional. Modify the logic of playlist playback.

      You can modify the logic of playlist playback to start the playback of the next video when half of the view of the next video is displayed. Modify the code for the PagerLayoutManager class to switch the video source when half of the view of the next video is displayed on RecyclerView. Sample code:

      Show code

      recyclerView.addOnScrollListener(new OnScrollListener() {
          private int measuredHeight;
          private int mScrollDiff;
          @Override
          public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
              super.onScrollStateChanged(recyclerView, newState);
      
              if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                  measuredHeight = recyclerView.getMeasuredHeight();
                  mScrollDiff = 0;
              }
      
              if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                  mScrollDiff = 0;
                  View viewIdle = mPagerSnapHelper.findSnapView(PagerLayoutManager.this);
                  if (viewIdle == null) {
                      return;
                  }
                  int positionIdle = getPosition(viewIdle);
                  if (mOnViewPagerListener != null && getChildCount() == 1 && mOldPosition != positionIdle) {
                      mOnViewPagerListener.onPageSelected(positionIdle, positionIdle == getItemCount() - 1, viewIdle);
                      mOldPosition = positionIdle;
                  }
              }
          }
      
          @Override
          public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
              super.onScrolled(recyclerView, dx, dy);
              if (measuredHeight > 0 && mOnViewPagerListener != null) {
                  mScrollDiff += dy;
                  changeVideoAfterScrolled(recyclerView, dy >= 0);
              }
          }
      
          private void changeVideoAfterScrolled(RecyclerView recyclerView, boolean isNext) {
              if (Math.abs(mScrollDiff) >= measuredHeight / 2) {
                  View snapView = mPagerSnapHelper.findSnapView(PagerLayoutManager.this);
                  if (snapView != null) {
                      int position = getPosition(snapView);
                      if (mOldPosition != position) {
                          if (isNext) {
                              mOnViewPagerListener.onPageHideHalf(position - 1);
                          } else {
                              mOnViewPagerListener.onPageHideHalf(position + 1);
                          }
                          mOnViewPagerListener.onPageSelected(position, false, snapView);
                          mOldPosition = position;
                          recyclerView.smoothScrollToPosition(position);
                          mScrollDiff = 0;
                      }
                  }
              }
          }
      });

Play videos that have transparency configurations

Description

ApsaraVideo Player SDK supports rendering of videos with alpha channels to play dynamic gift videos with a transparent background. This way, you can view the dynamic effects of gifts without blocking the live video content when someone is streaming. This significantly improves the viewing and interactive experience.

Limits

You can use ApsaraVideo MediaBox SDK V6.8.0 or later and ApsaraVideo Player SDK V6.9.0 or later to render videos with transparency.

Benefits

You can use MP4 videos with transparency to play dynamic gift videos with a transparent background. This improves the performance of dynamic effects and video compatibility, reduces the video size, and simplifies development. This also optimizes the viewing experience of gift effects and improves user experience. Using MP4 videos with transparency to play dynamic gift videos has the following benefits:

  1. Higher video quality: You can use MP4 videos to display the dynamic gift effects in the original quality, such as the original image details and colors. Compared with other video formats such as APN or IXD, MP4 can display the dynamic effect in the original quality intended by the designers.

  2. Smaller video size: Compared with other video formats such as APNG or IXD, MP4 reduces file sizes in a more efficient way. This accelerates loading and reduces the consumption of network bandwidth.

  3. Better compatibility: MP4 is a general video format that is widely supported on various devices and browsers. You can play MP4 videos that are used as gift effects on mainstream devices.

  4. Higher development efficiency: The solution of using MP4 videos as dynamic gift videos requires simple development. Instead of studying and developing complex parsing and rendering logic, developers can focus on the implementation of other features to improve development efficiency.

Sample code

The setAlphaRenderMode operation is added. You can call this operation to specify the alpha channel position of the video material. For example, you can place the alpha channel at the top, bottom, left side, or right side of the video material. By default, the value is set to None.

Note
  • The alpha channel position of the material must be the same as that you specified when you call the setAlphaRenderMode operation.

  • The size of the view must be proportional to the resolution of the material.

/**
 * Set the alpha rendering mode.
 *
 * @param alphaRenderMode The mirroring mode. See {@link AlphaRenderMode}. 
 */
/****
 * Set a alpha render mode
 *
 * @param alphaRenderMode The specified alpha render mode. See {@link AlphaRenderMode}.
 */
abstract public void setAlphaRenderMode(AlphaRenderMode alphaRenderMode);
//--------------Configure the view-------------
// Configure a transparent view.
//TextureView
TextureView aliplayerView; // The view used for playback.
aliplayerView.setOpaque(false);

//SurfaceView
SurfaceView aliplayerView; // The view used for playback.
aliplayerView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
aliplayerView.setZOrderOnTop(true); // Display SurfaceView at the top of the window.

//-----------Configure AliPlayer-----------
// Set the alpha mode.
aliplayer.setAlphaRenderMode(IPlayer.AlphaRenderMode.RENDER_MODE_ALPHA_AT_RIGHT);
// Specify the material that corresponds to the alpha mode.
UrlSource urlSource = new UrlSource();
urlSource.setUri("https://alivc-player.oss-cn-shanghai.aliyuncs.com/video/%E4%B8%9A%E5%8A%A1%E9%9C%80%E6%B1%82%E6%A0%B7%E6%9C%AC/alpha%E9%80%9A%E9%81%93/alpha_right.mp4");
aliplayer.setDataSource(urlSource);
aliplayer.setOnCompletionListener(new IPlayer.OnCompletionListener() {
    @Override
    public void onCompletion() {
        // Optional. If a connection error occurs when the playback of videos in a player instance is complete, you can clear the view.
        aliplayer.clearScreen();
    }
}
aliplayer.setAutoPlay(true);
aliplayer.prepare();

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.

    Show code

    // 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.

    Show code

    mAliPlayer.setOnSubtitleDisplayListener(new IPlayer.OnSubtitleDisplayListener() {
        @Override
        public void onSubtitleExtAdded(int trackIndex, String url) { }
    
        @Override
        public void onSubtitleShow(int trackIndex, long id, String data) {
                // Listen for the display of subtitles in the ASS format.
            assSubtitleView.show(id,data);
    
            // Listen 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) {
                // Listen for the hiding of subtitles in the ASS format.
                assSubtitleView.dismiss(id);
    
            // Listen 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. Display or hide subtitles.

    After you receive the onSubtitleExtAdded callback, you can use one of the following methods to display or hide subtitles:

    //trackIndex: specifies whether to display subtitles. If the value is true, subtitles are displayed. If the value is false, subtitles are hidden.
    mAliPlayer.selectExtSubtitle(trackIndex, true);

Enable audio-only playback

You can disable the display capability for video images to enable audio-only playback. Before you call the prepare method, configure the PlayerConfig class.

PlayerConfig config = mAliPlayer.getConfig();
config.mDisableVideo = true; // Enable audio-only playback.
mAliPlayer.setConfig(config);

Switch between software decoding and hardware decoding

Note

If you want to change the decoding method, change it before the playback starts. The change that is made during playback does not take effect.

ApsaraVideo Player SDK for Android supports hardware decoding based on the H.264 and H.265 standards. You can call enableHardwareDecoder to enable or disable the hardware decoding feature. By default, hardware decoding is enabled. If hardware decoding fails to be initialized, it is switched to software decoding to ensure normal playback. Sample code:

// Enable hardware decoding. Hardware decoding is enabled by default.
mAliyunVodPlayer.enableHardwareDecoder(true);

If hardware decoding is switched to software decoding, the onInfo callback is invoked. Sample code:

mApsaraPlayerActivity.setOnInfoListener(new IPlayer.OnInfoListener() {
    @Override
    public void onInfo(InfoBean infoBean) {
        if (infoBean.getCode() == InfoCode.SwitchToSoftwareVideoDecoder) {
            // Switch to software decoding.
        }
    }
});

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 with ApsaraVideo VOD.

  • If you use Vid-based playback for adaptive bitrate streams that are transcoded by ApsaraVideo VOD, you must specify AUTO as the default playback definition. This way, the player can obtain and play adaptive bitrate streams. If you do not specify AUTO as the default playback definition, the player automatically plays video streams in low definition. For more information about the playback order based on video definitions, see FAQ about video resolution. The following sample code 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 HLS or DASH video streams. After the prepare method is called, call getMediaInfo to obtain the bitrate information that is indicated by TrackInfo. Sample code:

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

During the playback, you can call the selectTrack method to switch the bitrate. If you specify AUTO_SELECT_INDEX, adaptive bitrate streaming is enabled. Sample code:

int index = trackInfo.getIndex();
// Switch the bitrate.
aliyunVodPlayer.selectTrack(index);
// Enable adaptive bitrate streaming.
aliyunVodPlayer.selectTrack(TrackInfo.AUTO_SELECT_INDEX);

The switching result is returned in the OnTrackChangedListener callback. You must configure the OnTrackChangedListener callback before you call the selectTrack method. Sample code:

aliyunVodPlayer.setOnTrackChangedListener(new IPlayer.OnTrackChangedListener() {
    @Override
    public void onChangedSuccess(TrackInfo trackInfo) {
        // The bitrate switching is successful.
    }
    @Override
    public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
        // The bitrate switching fails. You can call the errorInfo.getMsg() method to find the cause of the failure.
    }
});

Capture snapshots

ApsaraVideo Player SDK for Android provides the snapshot method for you to capture snapshots of videos. When you capture a snapshot, the player saves the source data of the video image to be captured and converts the source data to a bitmap. Then, you can invoke OnSnapShotListener to obtain the bitmap. Sample code:

// Set the callback for snapshot capture.
aliyunVodPlayer.setOnSnapShotListener(new OnSnapShotListener(){
    @Override
    public void onSnapShot(Bitmap bm, int with, int height){
        // Obtain the bitmap and the width and height of the video image. 
    }
});
// Capture a snapshot of the current video image.
aliyunVodPlayer.snapshot();

Configure video preview

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

After you enable the preview feature, you can call the VidPlayerConfigGen.setPreviewTime() method to specify the preview duration. The following sample code provides an example. 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 implement access control. Sample code:

// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Set the referer. Example: http://example.aliyundoc.com. You must add the protocol header when you set the referer.
config.mReferrer = referrer;
....// Configure other settings.
  // Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);

Specify the User-Agent header

ApsaraVideo Player SDK for Android provides the PlayerConfig class for you to specify the request user agent. After you specify the user agent, the player includes the user agent information in its requests. Sample code:

// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Set the user agent.
config.mUserAgent = "Required user agent";
....// Configure other settings.
  // Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);

Set the network timeout period and number of retries

ApsaraVideo Player SDK for Android provides the PlayerConfig class for you to set the network timeout period and number of retries. Sample code:

// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Specify the network timeout period. Unit: milliseconds.
config.mNetworkTimeout = 5000;
// Specify the maximum number of retries upon a network timeout. The retry interval equals the timeout period specified by the NetworkTimeout parameter. The NetworkRetryCount parameter specifies the number of retries. A value of 0 indicates zero retry. The application determines the number of retries. Default value: 2.
config.mNetworkRetryCount=2;
....// Configure other settings.
  // Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);
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 of ApsaraVideo Player SDK for Android to reload network packets or perform other operations as required.

Control the buffer and latency

ApsaraVideo Player SDK for Android provides the PlayerConfig class for you to configure buffer and latency settings. Sample code:

Show 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 when the network conditions are poor. 
config.mHighBufferDuration = 3000;
// Set the startup buffer duration. Unit: milliseconds. A smaller value indicates a shorter startup 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 that occur due to the excessive buffer size. When mMaxBufferDuration is greater than 50,000 ms (50 seconds), you can enable large cache to reduce the memory usage and further improve playback performance. For more information, see Configure large cache.

Configure HTTP headers

ApsaraVideo Player SDK for Android provides the PlayerConfig class for you to add HTTP headers to requests. Sample code:

// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Define a header.
String[] headers = new String[1];
headers[0]="Host:example.com"; // For example, add the host information to the header. 
// Configure the headers.
config.setCustomHeaders(headers);
....// Configure other settings.
  // Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);

RTS playback degradation

Playback degradation is supported by Real-Time Streaming (RTS). You can specify an alternative RTS URL, such as a playback URL in the HLS or FLV format. If stream pulling over RTS fails, the video specified in this URL is automatically played. Sample code:

PlayerConfig config = player.getConfig();
// Optional. Configure playback degradation.
UrlSource urlSource = new UrlSource();
urlSource.setUri(downgradeUrl);
// Specify an alternative RTS URL.
player.enableDowngrade(urlSource, config);

Switch between left and right audio channels

outputAudioChannel specifies the output audio channel. You can switch between the left and right audio channels only if the input file contains two audio channels. If the input file contains only one audio channel, the outputAudioChannel configuration is invalid.

Note

The following output channel settings affect both audio rendering and PCM data callback.

/*
Specify OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_LEFT to use the left audio channel for playback.
Specify OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_RIGHT to use the right audio channel for playback.
Specify OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_NONE to use the audio channel settings of the input file.
*/
player.setOutputAudioChannel();

Parse audio streams

You can configure a listener to obtain information about audio and video streams. Encrypted audio and video streams cannot be parsed.

Show code

// Optional. Specify whether to return the address of the underlying data.
IPlayer.RenderFrameCallbackConfig config = new IPlayer.RenderFrameCallbackConfig();
config.mVideoDataAddr = true;// Specify whether to return only the address of the underlying video data.
config.mAudioDataAddr = true;// Specify whether to return only the address of the underlying audio data.
player.setRenderFrameCallbackConfig(config);

// Optional. Return texture_oes_id for RenderFrame after hardware decoding and return the source data for RenderFrame after software decoding.
player.enableHardwareDecoder(true);
// Configure a listener to obtain information about audio and video streams.
player.setOnRenderFrameCallback(frameInfo -> {
    if (frameInfo.frameType == FrameInfo.FrameType_video) {
        // The video data.
    } else {
        // The audio data.
    }
    return false;
});

Set the background color of the player

You can set the background color of the player when you use ApsaraVideo Player SDK for Android. The following content describes how to set the background color of the player and provides sample code:

Sample code

/**
 * Set the background color of the video.
 *
 * @param color  ARGB
 *
 */
/****
 * Set video background color
 * @param color  ARGB
 */
abstract public void setVideoBackgroundColor(int color);

Usage notes

// The value must be an 8-bit hexadecimal string, in which every two characters indicate a factor in the following sequence: R (red), G (green), B (blue), and A (alpha transparency).
// For example, 0x00ff00ff indicates green.
player.setVideoBackgroundColor(0x00ff00ff);

Specify a domain name for vidAuth-based playback

You can specify parameters such as the domain name when you use vidAuth for playback. For more information about the parameters, see GetPlayInfo. The following content describes how to specify a domain name for vidAuth-based playback and provides sample code:

Sample code

/**
 * Specify the playback parameters.
 *
 * @param playConfig The playback parameters.
 */
public void setPlayConfig(VidPlayerConfigGen playConfig);

Usage notes

Specify the playDomain parameter when you call addPlayerConfig in VidPlayerConfigGen.

vidAuth = new VidAuth();
VidPlayerConfigGen configGen = new VidPlayerConfigGen();
// Specify the playDomain parameter. For more information, visit https://www.alibabacloud.com/help/en/vod/developer-reference/api-vod-2017-03-21-getplayinfo.
configGen.addPlayerConfig("playDomain", "com.xxx.xxx");
vidAuth.setPlayConfig(configGen);

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 enableLocalCache in the AliPlayerGlobalSettings class to enable the local caching feature. Sample code:

Show 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 local caching feature is enabled and false indicates that the local caching feature is disabled. Default value: false. 
 *  @param maxBufferMemoryKB - This parameter is deprecated in V5.4.7.1 or later.
 *  @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 V5.4.7.1 or later. 
  * @param maxCapacityMB - The maximum cache size. Unit: MB. By default, the maximum cache size 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 cache size is less than or equal to the specified maximum size. 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 idle 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 idle space. 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 playback URL of a video file contains authentication parameters, the values of the authentication parameters change during the local caching and playback of the video file. You can call the setCacheUrlHashCallback operation to calculate the MD5 hash value after you remove the authentication parameters. For example, http://****.mp4?aaa is the playback URL of a video file that contains authentication parameters. In this case, the URL http://****.mp4 is used to calculate the MD5 hash value when the video file is loaded. However, if you calculate the MD5 hash value after you remove the authentication parameters in the key URL of an encrypted M3U8 video, the playback fails because different videos are hit by the same key URL. Solution: Remove the authentication parameters only from the playback URL http(s)://xxxxx.m3u8?aaaa but not the key URL http(s)://yyyyy?bbbb in the setCacheUrlHashCallback callback.进阶功能-本地缓存.png

  • If your server supports HTTP and HTTPS and a video file can be specified by using two URLs with the same elements but different protocols, you can remove the protocol headers of the URLs or use either the HTTP or HTTPS protocol to calculate the MD5 hash value. Examples:

    • If the playback URLs of a video file are https://****.mp4 and http://****.mp4, the MD5 hash value is calculated by using ****.mp4 when the video file is loaded.

    • If the playback URL of the video file is https://****.mp4, the MD5 hash value is calculated by using the URL http://****.mp4 when the video file is loaded.

  • For ApsaraVideo Player SDK V5.5.4.0 or later, if you want to play an HLS stream whose playback URL contains authentication parameters, configure PlayerConfig.mEnableStrictAuthMode to specify the authentication mode. By default, PlayerConfig.mEnableStrictAuthMode is set to false. Valid values of PlayerConfig.mEnableStrictAuthMode:

    • false: caches the video content and performs authentication. If a video is not completely cached, the player sends a URL signing request by using the authentication information about the cached content when you play the uncached video content. If the validity period of the signed URL is too short, playback errors occur.

    • true: performs authentication and does not cache video content. URL signing is required for every playback. No network connections lead to playback failures.

Enable or disable local caching for a single URL

You can enable or disable local caching for a single URL in player config.

// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Configure whether to enable local caching for the playback URL. Default value: true. Local caching for the URL takes effect only when local caching is enabled in AliPlayerGlobalSettings and the value of this parameter is true. If the value of this parameter is false, the local caching for the URL is disabled. 
config.mEnableLocalCache = false;
....// Configure other settings.

// Configure the settings for the player.
mAliyunVodPlayer.setConfig(config);

Configure large cache

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

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

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

  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 Advanced features.

  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.

    Show code

    /**
     * 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.

Dynamic preloading

The dynamic preloading feature allows you to manage cache of the video that is being played and videos that are preloaded. You can also control the number of videos that are preloaded. This helps maintain a balance between playback experience and cost.

Show code

// Enable the dynamic preloading feature and use the default configurations.
ListPlayer.setPreloadScene(IListPlayer.SceneType.SCENE_SHORT);

// Configure the baseline preload duration.
// Set the preload duration to 1,000 milliseconds.
PreloadConfig config = new PreloadConfig();
config.mPreloadDuration = 1000;
ListPlayer.updatePreloadConfig(config);

// Configure the number of videos that you can preload. Forward and backward are supported.
// 1 specifies the number of videos that can be preloaded forwards and 3 specifies the number of videos that can be preloaded backwards.
ListPlayer.setPreloadCount(1, 3);

// Configure the decreasing offset for dynamic preloading.
ListPlayer.enablePreloadStrategy(IListPlayer.StrategyType.STRATEGY_DYNAMIC_PRELOAD_DURATION, true);
ListPlayer.setPreloadStrategy(IListPlayer.StrategyType.STRATEGY_DYNAMIC_PRELOAD_DURATION, "{\"algorithm\": \"sub\",\"offset\": \"200\"}");

Obtain the download speed

ApsaraVideo Player SDK for Android provides the getExtraValue method for you to query the download speed of specified videos. The onInfo callback is invoked to obtain the query result. Sample code:

mAliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
    @Override
    public void onInfo(InfoBean infoBean) {
        if(infoBean.getCode() == InfoCode.CurrentDownloadSpeed){
            // The download speed.
            long extraValue = infoBean.getExtraValue();
        }
    }
});

Configure the network

HTTPDNS

The HTTPDNS feature uses the DNS resolution technology to send domain name resolution requests to the specific HTTPDNS server and obtain the resolution results in a quick and stable manner. This prevents DNS hijacking.

You can use one of the following HTTPDNS features based on your business requirements.

Type

Description

Standard HTTPDNS

Provide HTTPDNS services for various domain names.

Enhanced HTTPDNS

Provide HTTPDNS services for domain names that are accelerated by Alibaba Cloud CDN. You can use the enhanced HTTPDNS feature to implement precise scheduling and ensure that the real-time domain resolution results immediately take effect. This improves the network performance.

Note

To use the enhanced HTTPDNS feature, submit a request on Yida or contact your account manager.

Sample code for using the standard HTTPDNS feature

// Enable the standard HTTPDNS feature.
AliPlayerGlobalSettings.enableHttpDns(true);
// Optional. Add an HTTPDNS pre-resolved domain name.
DomainProcessor.getInstance().addPreResolveDomain("player.***cdn.com");

Sample code for using the enhanced HTTPDNS feature

You can use the enhanced HTTPDNS feature only for accelerated domain names. Before you use the feature, make sure that an accelerated domain name is added and configured. For more information about how to add and configure a domain name for CDN to ApsaraVideo VOD, see Add a domain name for CDN. For more information about accelerated domain names, see What is Alibaba Cloud CDN?.

// Enable the enhanced HTTPDNS feature.
AliPlayerGlobalSettings.enableEnhancedHttpDns(true);
// Required. Add and configure a domain name for CDN. Make sure that the domain name can provide online services. 
DomainProcessor.getInstance().addEnhancedHttpDnsDomain("player.***alicdn.com");
// Optional. Add an HTTPDNS pre-resolved domain name.
DomainProcessor.getInstance().addPreResolveDomain("player.***alicdn.com");

Configure the priority of HTTPDNS

You can configure the priority levels of HTTPDNS and local DNS. Standard HTTPDNS and enhanced HTTPDNS are supported.

// AliPlayerGlobalSettings.SET_DNS_PRIORITY_LOCAL_FIRST specifies the priority of HTTPDNS.
// true indicates that local DNS takes precedence and false indicates that HTTPDNS takes precedence.
AliPlayerGlobalSettings.setOption(AliPlayerGlobalSettings.SET_DNS_PRIORITY_LOCAL_FIRST, false);

HTTP/2

Note

By default, HTTP/2 is enabled for ApsaraVideo Player SDK for Android V5.5.0.0 or later.

ApsaraVideo Player SDK for Android supports HTTP/2. You can enable HTTP/2 to implement the multiplexing of requests. This prevents head-of-line (HOL) blocking and improves playback performance. Sample code:

AliPlayerGlobalSettings.setUseHttp2(true);

HTTP/3

Note
  • In 2022, Internet Engineering Task Force (IETF) published HTTP/3 as a proposed standard. ApsaraVideo Player SDK for Android supports only IETF Quick UDP Internet Connections (QUIC) h3-v1. Google QUIC is not supported.

  • If the playback times out or fails after you enable HTTP/3, requests are automatically sent over HTTP/2.

HTTP/3 is supported in ApsaraVideo Player SDK for Android. To enable HTTP/3 for an accelerated domain name, submit a request on Yida. Then, you can play videos that are stored in ApsaraVideo VOD over HTTP/3 by using the accelerated domain name. You can also configure ApsaraVideo Player to access playback URLs over HTTP/3 to better respond to poor network conditions. Sample code:

// Obtain the configuration information.
PlayerConfig config = mAliyunVodPlayer.getConfig();
// Send requests over HTTP/3.
config.mEnableHttp3 = true;
....// Configure other settings.
// Apply the configurations to the player.
mAliyunVodPlayer.setConfig(config);

Configure video download

ApsaraVideo Player SDK for Android allows you to download videos to local devices for offline playback in ApsaraVideo Player. The normal download mode and secure download mode are supported.

  • Normal download

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

  • Secure download

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

Usage notes

  • You can download only videos that are played based on VidSts or VidAuth.

  • To use the video download feature, you must enable the feature and configure the download mode in the ApsaraVideo VOD console. For more information, see Configure download settings.

  • Resumable download is supported.

Procedure

  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 phone and set this parameter to the path in which the file is stored.
  2. Create and set a video downloader.

    Use the AliDownloaderFactory class to create a download object. Sample code:

    AliMediaDownloader mAliDownloader = null;
    ......
    // Create a download object.
    mAliDownloader = AliDownloaderFactory.create(getApplicationContext());
    // Specify the path for storing downloaded files.
    mAliDownloader.setSaveDir("The storage path");
  3. Configure listeners.

    The downloader provides multiple listeners. Sample code:

    Show code

    mAliDownloader.setOnPreparedListener(new AliMediaDownloader.OnPreparedListener() {
       @Override
       public void onPrepared(MediaInfo mediaInfo) {
           // Listen for the preparation of the content to be downloaded.
       }
    });
    mAliDownloader.setOnProgressListener(new AliMediaDownloader.OnProgressListener() {
       @Override
       public void onDownloadingProgress(int percent) {
           // Listen for the percentage of the download progress.
       }
       @Override
       public void onProcessingProgress(int percent) {
           // Listen for the percentage of the processing progress.
       }
    });
    mAliDownloader.setOnErrorListener(new AliMediaDownloader.OnErrorListener() {
       @Override
       public void onError(ErrorInfo errorInfo) {
           // Listen for download errors.
       }
    });
    mAliDownloader.setOnCompletionListener(new AliMediaDownloader.OnCompletionListener() {
       @Override
       public void onCompletion() {
           // Listen 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. Sample code:

    • VidSts

      // Create the VidSts download source.
      VidSts aliyunVidSts = new VidSts();
      aliyunVidSts.setVid("Vid");// The ID of the video. 
      aliyunVidSts.setAccessKeyId("<yourAccessKeyId>");// The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS. 
      aliyunVidSts.setAccessKeySecret"<yourAccessKeySecret>");// The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS. 
      aliyunVidSts.setSecurityToken("<yourSecurityToken>");// The STS token. To obtain the STS token, call the AssumeRole operation in STS. 
      aliyunVidSts.setRegion("Access region");// The region in which ApsaraVideo VOD is activated. Default value: cn-shanghai. 
      // Prepare the download source.
      mAliDownloader.prepare(aliyunVidSts)
    • VidAuth

      // Create the VidAuth download source.
      VidAuth vidAuth = new VidAuth();
      vidAuth.setVid("Vid"); // The ID of the video. 
      vidAuth.setPlayAuth("<yourPlayAuth>");// The playback credential. To obtain the playback credential, call the GetVideoPlayAuth operation. 
      vidAuth.setRegion("Access region"); // This parameter is deprecated in ApsaraVideo Player SDK V5.5.5.0 or later. If you use ApsaraVideo Player SDK V5.5.5.0 or later, the player automatically parses the region information. If you use ApsaraVideo Player SDK V5.5.5.0 or earlier, this parameter is required. Specify the ID of the region in which ApsaraVideo VOD is activated for this parameter. Default value: cn-shanghai. 
      // Prepare the download source.
      mAliDownloader.prepare(vidAuth);
    Note

    The output file and the input file are in the same format 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 fired. The value of the TrackInfo parameter indicates the information about video tracks such as video definitions. Select a track to download. Sample code:

    public void onPrepared(MediaInfo mediaInfo) {
        // Prepare the content to be downloaded.
        List<TrackInfo> trackInfos = mediaInfo.getTrackInfos();
        // Download the information about tracks, such as the first track.
        mAliDownloader.selectItem(trackInfos.get(0).getIndex());
        // Start the download.
        mAliDownloader.start();
    }
  6. Optional. Update the download source.

    VidSts or VidAuth sources may expire before the download. Therefore, we recommend that you update the download source before you start the download. Sample code:

    // Update the download source.
    mAliDownloader.updateSource(VidSts);
    // Start the download.
    mAliDownloader.start();
  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. Optional. Delete a downloaded file.

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

    // Delete the file by using the download object.
    mAliDownloader.deleteFile();
    // Delete the file by using the static method. If 0 is returned, the file is deleted.
    AliDownloaderFactory.deleteFile("The path of the downloaded file","Video ID","Video format","The index of the downloaded video");

What to do next

Perform the following operations to play downloaded videos by using ApsaraVideo Player: update PHP SDK to the latest version:

  1. Obtain the absolute path of the downloaded video file.

    String path = mAliDownloader.getFilePath();
  2. Set UrlSource to the absolute path of the downloaded video file to play the video.

     UrlSource urlSource = new UrlSource();
            urlSource.setUri("Playback URL");// Specify the absolute path of the downloaded video file. 
            aliPlayer.setDataSource(urlSource);

Play encrypted videos

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

Configure Native RTS SDK

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

References