You can create a short video list player by using ApsaraVideo Player SDK. This topic describes how to create a short video list player for Android and iOS devices and provides the sample code.

Download the installation package and demo

ApsaraVideo Player SDKDownload linkDemo source code description
ApsaraVideo Player SDK for Android
  • AliyunRenderView: A custom class that encapsulates AliyunPlayer and TextureView. You can associate one TextureView instance with an AliyunPlayer instance.
  • AliPlayerPool: A class that is used to specify the number of AliyunPlayer instances. You can use this class to specify three AliyunRenderView objects. RecyclerViewAdapter obtains the first AliyunRenderView object from the queue in AliPlayerPool.
  • AliPlayerPreload: A class that encapsulates MediaLoader to implement the video preload feature.
  • CustomLayoutManager: The custom LayoutManager. Multiple listeners are configured to monitor the view status.

Usage notes for Android devices

The short video list player supports video preload and pre-rendering features by using multiple AliPlayer instances and the MediaLoader class encapsulated in ApsaraVideo Player SDK. You can create multiple AliPlayer instances, play short videos based on PlayAuth, and play videos in the M3U8 format. Compared with AliListPlayer, AliPlayer is easier to use and more flexible.

Note
  • For more information about the logic and sample code of the short video list player, see the demo. The following section describes the key features of the short video list player.
  • If memory crashes occur because multiple AliPlayer instances are created, we recommend that you use existing AliPlayer instances instead of creating new ones.

Video swiping and playback

The PagerSnapHelper class is integrated with the RecyclerView system component to allow you to swipe through videos. You can swipe up and down to play the previous and the next videos.

Video preload

ApsaraVideo Player SDK for Android provides the video preload feature by using MediaLoader. In the demo, if the buffer duration of the video that is being played is greater than or equal to 5 seconds, the player starts to load the next video based on the sequence of video sources. After one video is loaded, the player starts to load the next video in sequence. If you swipe to switch to another video when a video is loading, the player stops loading the current video and starts to load the video that you want to play. Sample code:

// Listen to the onInfo event.
mAliPlayer.setOnInfoListener(infoBean -> {
    // Listen to the buffer duration.
    if (infoBean.getCode() == InfoCode.BufferedPosition) {
        long buffer = infoBean.getExtraValue();
        if(buffer >= 5000){
            // Start video preload.
        }
    }
});
// Create a MediaLoader object.
MediaLoader mMediaLoader = MediaLoader.getInstance();
// Configure listeners.
mMediaLoader.setOnLoadStatusListener(new MediaLoader.OnLoadStatusListener() {
    @Override
    public void onError(String s, int i, String s1) {
        // Load the next video based on the URL after the current video fails to be loaded.
        loadNext();
    }

    @Override
    public void onCompleted(String s) {
        // Load the next video based on the URL after the current video is loaded.
        loadNext();
    }

    @Override
    public void onCanceled(String s) {
    }
}

// Cancel video preload.
mMediaLoader.cancel(url);
// Start video preload.
mMediaLoader.load(url,duration);

First frame pre-rendering

To use the first frame pre-rendering feature, you must configure the data source and rendering view and call the prepare method in ApsaraVideo Player. Call the seekTo(0) method immediately after the onPrepared callback is invoked. Then, specify a point in time and call the start method to start the playback. Sample code:

// Configure the rendering view.
mAliPlayer.setSurface(new Surface(surfaceTexture));
// Listen to the prepare event.
mAliPlayer.setOnPreparedListener(() -> {
    // Call the seekTo method in the player to render the first frame.
    mAliPlayer.seekTo(0);
});

// Configure the playback source.
mAliPlayer.setDataSource(urlSource);
mAliPlayer.prepare();

// Call start at a specified point in time to start the playback.
mAliPlayer.start();

Usage notes for iOS devices

  1. Create a list player.
    Create a short video list player and configure the parameters. Sample code:
    // Required. Create a short video list player.
    self.listPlayer = [[AliListPlayer alloc]init];
    // Enable hard decoding.
    self.listPlayer.enableHardwareDecoder = YES;
    // Enable loop playback.
    self.listPlayer.loop = YES;
    // Enable autoplay.
    self.listPlayer.autoPlay = YES;
    // Specify the rendering mode.
    self.listPlayer.scalingMode = AVP_SCALINGMODE_SCALEASPECTFIT;
    // Specify the delegate.
    self.listPlayer.delegate = self;
    // Specify the resolution of the short videos to be preloaded.
    self.listPlayer.stsPreloadDefinition = @"FD";
    // Configure the view.
    self.listPlayer.playerView = self.simplePlayScrollView.playView;
    // Specify the number of videos that you want to preload. This example preloads three videos: the video that is being played and the previous and the next videos in the playlist. 
    mVideoListPlayer.setPreloadCount(1);
  2. Add multiple video sources.
    You can use the short video list player to play videos based on URLs and VIDs. You must use Security Token Service (STS) tokens to play videos from ApsaraVideo VOD. Sample code:
    // Add a video from ApsaraVideo VOD.
    [self.listPlayer addVidSource:"VID" uid:"Unique ID of the video"];
    // Add a video from a specified URL.
    [self.listPlayer addUrlSource:"Video URL" uid: "Unique ID of the video"];
    Important The short video list player identifies videos based on unique IDs. A playback error occurs if you add videos with the same unique ID. Make sure that the videos that are added to the player have unique IDs.
  3. Start the playback.
    The short video list player provides the following methods for you to locate and play videos. Sample code:
    // Locate a video and start the playback.
    [self.listPlayer moveTo:"Unique ID of the video"]; //The video URL.
    [self.listPlayer moveTo:"Unique ID of the video" accId:accId accKey:accKey token:token region:region]; // The ID of the video in ApsaraVideo VOD. You must use STS tokens to play videos from ApsaraVideo VOD.
    // Play the previous video in the playlist.
    [self.listPlayer moveToPrev:"Unique ID of the video"]; //The video URL.
    [self.listPlayer moveToPrev:"Unique ID of the video" accId:accId accKey:accKey token:token region:region]; // The ID of the video in ApsaraVideo VOD. You must use STS tokens to play videos from ApsaraVideo VOD.
    // Play the next video in the playlist.
    [self.listPlayer moveToNext:"Unique ID of the video"]; //The video URL.
    [self.listPlayer moveToNext:"Unique ID of the video" accId:accId accKey:accKey token:token region:region]; // The ID of the video in ApsaraVideo VOD. You must use STS tokens to play videos from ApsaraVideo VOD.
  4. Manage video swiping and playback.
    1. Tap the screen to pause or resume the playback. Sample code:
      - (void)tap {
          if ([self.delegate respondsToSelector:@selector(AVPSimplePlayScrollViewTapGestureAction:)]) {
              [self.delegate AVPSimplePlayScrollViewTapGestureAction:self];
          }
      }
      - (void)AVPSimplePlayScrollViewTapGestureAction:(AVPSimplePlayScrollView *)simplePlayScrollView {
          if (self.playerStatus == AVPStatusStarted) {
              // Pause the video if the video is being played.
              [self.listPlayer pause];
          }else if (self.playerStatus == AVPStatusPaused) {
              // Play the video if the video is paused.
              [self.listPlayer start];
          }
      }
    2. Manage video swiping.
      If you quickly swipe through multiple videos at a time, the moveTo method is called to locate and play the specified video. Sample code:
      - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
          CGFloat indexFloat = scrollView.contentOffset.y/self.frame.size.height;
          NSInteger index = (NSInteger)indexFloat;
          .......
            // Swipe down to the next video.
             if (index - self.currentIndex == 1) {
                  if ([self.delegate respondsToSelector:@selector(AVPSimplePlayScrollView:motoNextAtIndex:)]) {
                      [self.delegate AVPSimplePlayScrollView:self motoNextAtIndex:index];
                  }
              }
              // Swipe up to the previous video.
              else if (self.currentIndex - index == 1){
                  if ([self.delegate respondsToSelector:@selector(AVPSimplePlayScrollView:motoPreAtIndex:)]) {
                      [self.delegate AVPSimplePlayScrollView:self motoPreAtIndex:index];
                  }
              }
              // Swipe through multiple videos.
              else {
                  if ([self.delegate respondsToSelector:@selector(AVPSimplePlayScrollView:scrollViewDidEndDeceleratingAtIndex:)]) {
                      [self.delegate AVPSimplePlayScrollView:self scrollViewDidEndDeceleratingAtIndex:index];
                  }
              }
      }
      /**
       Locate the specified video after continuous swiping:
       @param simplePlayScrollView simplePlayScrollView
       @param index The count from the current video to the video that you want to play.
       */
      - (void)AVPSimplePlayScrollView:(AVPSimplePlayScrollView *)simplePlayScrollView scrollViewDidEndDeceleratingAtIndex:(NSInteger)index {
          // Find the video that you want to play.
          AVPDemoResponseVideoListModel *model = [self findModelFromIndex:index];
          // Call the moveTo method to locate and play the video.
          [self moveToCurrentModel];
      }
  5. Hide the video thumbnail.
    The video thumbnail is hidden during playback. Sample code:
    -(void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType {
        switch (eventType) {
            case AVPEventPrepareDone: {
            }
                break;
            case AVPEventFirstRenderedStart: {
                // Hide the thumbnail.
                [self.simplePlayScrollView showPlayView];
            }
                break;
            default:
                break;
        }
    }
  6. Destroy the player.
    You must release the player after use. Otherwise, memory leaks may occur. Sample code:
    [self.listPlayer stop];
    [self.listPlayer destroy];
    self.listPlayer = nil;