This topic describes how to configure the basic features of ApsaraVideo Player SDK for Android.

Create a player

This section describes how to use ApsaraVideo Player SDK for Android to play videos. Manual playback and autoplay are supported.

  1. Create a player.
    Call the AliPlayerFactory class to create an ApsaraVideo Player.
    // Create a player.
    AliPlayer aliPlayer = AliPlayerFactory.createAliPlayer(context);
    // By default, event tracking logs are uploaded. Set tranceId to DisableAnalytics to disable this feature. If you set traceId to a value other than DisableAnalytics, the event tracking logs are uploaded. 
    // We recommend that you specify traceId to facilitate log tracking. traceId is the unique identifier of the device or user. Generally, tranceId is set to the value of imei or idfa. 
    aliPlayer.setTraceId("traceId");  
  2. Configure listeners.
    You can configure multiple listeners for your player.
    • You must configure OnPreparedListener because you need to call aliPlayer.start() in the OnPreparedListener callback to start manual playback.
    • We recommend that you configure OnErrorListener, OnCompletionListener, OnLoadingStatusListener, and OnInfoListener.
    aliPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
        // This callback is returned if an error occurs when you use the player. 
    
        @Override
        public void onError(ErrorInfo errorInfo) {
            ErrorCode errorCode = errorInfo.getCode() // The error code. 
            String errorMsg =errorInfo.getMsg(); // The error message. 
            // Stop the player if an error occurs. 
            aliPlayer.stop();
        }
    });
    aliPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
        // The player starts to read and parse data after you call the aliPlayer.prepare() method. This callback is returned after data is parsed. 
    
        @Override
        public void onPrepared() {
            // Call the start method to start the playback. 
            aliPlayer.start();
        }
    });
    aliPlayer.setOnCompletionListener(new IPlayer.OnCompletionListener() {
        // This callback is returned after the playback ends. 
        @Override
        public void onCompletion() {
            // Call the stop method to stop the playback. 
            aliPlayer.stop();
        }
    });
    aliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
        // The information about the player, such as the current playback progress and buffer position. 
        @Override
        public void onInfo(InfoBean infoBean) {
            InfoCode code = infoBean.getCode(); // The information code. 
            String msg = infoBean.getExtraMsg(); // The information content. 
            long value = infoBean.getExtraValue(); // The information value. 
    
            // Call InfoCode.CurrentPosition to obtain the current playback position.
            // Call InfoCode.BufferedPosition to obtain the current buffered position.
        }
    });
    aliPlayer.setOnLoadingStatusListener(new IPlayer.OnLoadingStatusListener() {
        // The loading status. If the network is unstable, this method is called to display the loading status. 
    
        @Override
        public void onLoadingBegin() {
            // Starts loading. In this case, video and audio streams cannot be played. 
            // The loading circle is displayed. 
        }
    
        @Override
        public void onLoadingProgress(int percent, float netSpeed) {
            // The loading progress. The loading percentage and network speed are displayed. 
        }
    
        @Override
        public void onLoadingEnd() {
            // The loading ends. In this case, video and audio streams can be played. 
            // The loading circle is hidden. 
        }
    });
  3. Configure a playback source.
    • ApsaraVideo Player SDK for Android supports video-on-demand (VOD) playback based on UrlSource, VidAuth, VidSts, and VidMps. Encrypted VOD playback is also supported. We recommend that you play videos based on VidAuth in ApsaraVideo VOD.
    • ApsaraVideo Player SDK for Android supports UrlSource-based and encrypted live stream playback.
    Note
    • UrlSource is used for URL-based playback, and VidSts and VidAuth are used for Vid-based playback.
    • For more information about regions, see VOD centers and endpoints.
    • For more information about video playback in ApsaraVideo Media Processing (MPS), see Play videos.

    Play on-demand videos

    If you play an on-demand video based on UrlSource, you must set the source of the player to the playback URL of the video. The playback URL is generated by ApsaraVideo VOD or a third-party service. You can also use the URL of a local video. You can call the GetPlayInfo operation to obtain a playback URL that is generated by 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. Make sure that you are authorized to access the local video. The playback URL is converted from the path in which the local video is stored, such as /sdcard/xxx/xxx/xxx.mp4 or content://xxx/xxx/xx.mp4.

    Sample code

     UrlSource urlSource = new UrlSource();
            urlSource.setUri("Playback URL");// The playback URL of the video. The URL is generated by ApsaraVideo VOD or a third-party service. You can also use the URL of a local video. 
            aliPlayer.setDataSource(urlSource);

    If you play an on-demand video based on VidAuth, you must set vid to the media ID and playAuth to the credential for media playback. You can call the SearchMedia operation to obtain the media ID. Alternatively, you can log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video to view the media ID. You can call the GetVideoPlayAuth operation to obtain the credential for media playback. We recommend that you use a server SDK to obtain credentials for media playback in ApsaraVideo VOD. This frees you from complex signature calculations. For more information about the GetVideoPlayAuth operation, see OpenAPI.

    We recommend that you use VidAuth for video playback in ApsaraVideo VOD. Compared with STS-based playback, VidAuth-based playback is easier to use and more secure. For more information about the comparison between the two playback methods, see Comparison between credentials and STS.

    Sample code

    VidAuth vidAuth = new VidAuth();
            vidAuth.setVid("Video ID"); // The video ID.
            vidAuth.setPlayAuth("Playback credential"); // The playback credential.
            vidAuth.setRegion("Access region ID"); // The ID of the region in which ApsaraVideo VOD is activated. Default value: cn-shanghai.
            aliPlayer.setDataSource(vidAuth);

    If you play an on-demand video based on VidSts, a temporary STS token is used instead of a playback credential. In this case, you must obtain an STS token before you play videos on demand. For more information, see Create a role and grant temporary access permissions to the role by using STS. If you play an on-demand video based on VidSts, you must set securityToken to the temporary STS token and specify the temporary AccessKey pair.

    Sample code

    VidSts vidSts = new VidSts();
            vidSts.setVid("Video ID"); // The video ID.
            vidSts.setAccessKeyId("<Your AccessKey ID>"); // The AccessKey ID.
            vidSts.setAccessKeySecret("<Your AccessKey secret"); // The AccessKey secret.
            vidSts.setSecurityToken("<Security token>"); // The STS token.
            vidSts.setRegion("Access region ID"); // The region in which ApsaraVideo VOD is activated. Default value: cn-shanghai.
            aliPlayer.setDataSource(vidSts);

    ApsaraVideo Player SDK for Android supports video playback based on VidMps in MPS. You must obtain the following information before you use VidMps for playback.

    • vid: the ID of the media file in MPS.
    • AccessKeyId and AccessKeySecret: the AccessKey pair that is generated when the temporary STS token is issued.
    • SecurityToken: the temporary STS token.
    • domainRegion: the region in which the media file is stored.
    • authInfo: the authorization information.

    For more information, see Play videos.

    Sample code

    VidMps vidMps = new VidMps();
            vidMps.setRegion("Access region ID"); // The ID of the region in which ApsaraVideo VOD is activated. Default value: cn-shanghai.
            vidMps.setMediaId("Media ID");// The media ID. The value is the same as VideoId.
            vidMps.setAuthInfo("Authorization information");// The authorization information.
            vidMps.setAccessKeyId("<Your AccessKey ID>"); // The AccessKey ID.
            vidMps.setSecurityToken("<Security token>"); // The STS token.
            vidMps.setPlayDomain("Playback domain");// The domain name for playback.
            vidMps.setHlsUriToken("HlsUriToken");// The HlsUriToken.
            vidMps.setAccessKeySecret("<Your AccessKey secret>"); // The AccessKey secret.
            aliPlayer.setDataSource(vidMps);

    ApsaraVideo VOD supports HTTP-Live-Streaming (HLS) encryption, Alibaba Cloud proprietary cryptography, and digital rights management (DRM) encryption. For more information, see Play an encrypted video.

    Live streaming

    If you play a live stream based on UrlSource, you must set urlSource to the streaming URL of the live stream. The streaming URL is generated by ApsaraVideo Live or a third-party service. You can generate a streaming URL for a live stream by using the URL generator in the ApsaraVideo Live console. For more information, see OpenAPI.

    Sample code

    UrlSource urlSource = new UrlSource();
            urlSource.setUri("Streaming URL");// The streaming URL. The URL is generated by ApsaraVideo Live or a third-party service. 
            aliPlayer.setDataSource(urlSource);

    For more information about how to play DRM-encrypted videos, see Play an encrypted video.

  4. 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:
      SurfaceView surfaceView = findViewById(R.id.surface_view);
      surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
          @Override
          public void surfaceCreated(SurfaceHolder holder) {
              aliPlayer.setSurface(holder.getSurface());
          }
      
          @Override
          public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
              aliPlayer.surfaceChanged();
          }
      
          @Override
          public void surfaceDestroyed(SurfaceHolder holder) {
              aliPlayer.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) {
              aliPlayer.setSurface(new Surface(surface));
          }
      
          @Override
          public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
              aliPlayer.surfaceChanged();
          }
      
          @Override
          public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
              aliPlayer.setSurface(null);
              return false;
          }
      
          @Override
          public void onSurfaceTextureUpdated(SurfaceTexture surface) {
      
          }
      });
  5. Optional:Enable the autoplay feature. By default, this feature is disabled.
    aliPlayer.setAutoPlay(true);
  6. Prepare the player.
    Call the aliPlayer.prepare() method to read and parse data.
    aliPlayer.prepare();
  7. Start the playback.
    • If the autoplay feature is not enabled, you must call the aliPlayer.start() method in the OnPrepard callback to start the playback.
    • If the autoplay feature is enabled, you do not need to call the aliPlayer.start() method. After the data is parsed, the video is automatically played.
    aliPlayer.start();// After the playback starts, you can call the pause() method to pause the playback. 

Manage playback

ApsaraVideo Player SDK for Android allows you to manage media playback. For example, you can start, pause, or stop the playback, or start the playback from a specific point in time.

Start playback

You can call the start method to start the playback. Sample code:
aliyunVodPlayer.start();

Play a video from a specified point in time

You can call the seekTo method to play a video from a specified point in time. This feature is used when the user drags the slider on the progress bar or the video is resumed from a specific point in time. Sample code:
// The position parameter specifies the point in time when playback starts. Unit: milliseconds. 
aliyunVodPlayer.seekTo(long position);

Pause playback

You can call the pause method to pause the playback. Sample code:
aliyunVodPlayer.pause();

Stop playback

You can call the stop method to stop the playback. Sample code:
aliyunVodPlayer.stop();

Set the video display mode

ApsaraVideo Player SDK for Android allows you to configure display settings for playback. For example, you can specify how video images are scaled, rotated, or mirrored.

Scaling

You can call the setScaleMode method to scale in or scale out the video images without changing the original aspect ratio, or stretch the video images. Sample code:
// Scale in the video to fit the view. The aspect ratio of the video is maintained.
aliyunVodPlayer.setScaleMode(ScaleMode.SCALE_ASPECT_FIT);
// Scale out the video to fill the view. The aspect ratio of the video is maintained.
aliyunVodPlayer.setScaleMode(ScaleMode.SCALE_ASPECT_FILL);
// Stretch the video to fill the view. The aspect ratio of the video is not maintained. Image distortion may occur if the aspect ratios of the video and the view are different.
aliyunVodPlayer.setScaleMode(ScaleMode.SCALE_TO_FILL);

Rotating

You can call the setRotateMode method to specify a rotation angle for video images. You can also query the rotation angle. Sample code:
// Set the rotation angle to 0° in the clockwise direction.
aliyunVodPlayer.setRotateMode(RotateMode.ROTATE_0);
// Set the rotation angle to 90° in the clockwise direction.
aliyunVodPlayer.setRotateMode(RotateMode.ROTATE_90);
// Set the rotation angle to 180° in the clockwise direction.
aliyunVodPlayer.setRotateMode(RotateMode.ROTATE_180);
// Set the rotation angle to 270° in the clockwise direction.
aliyunVodPlayer.setRotateMode(RotateMode.ROTATE_270);
// Query the rotation angle.
aliyunVodPlayer.getRotateMode();

Mirroring

You can call the setMirrorMode method to specify a mirroring mode. Horizontal mirroring, vertical mirroring, and no mirroring are supported. Sample code:
// Specify no mirroring for the video images.
aliyunVodPlayer.setMirrorMode(MirrorMode.MIRROR_MODE_NONE);
// Specify horizontal mirroring for the video images.
aliyunVodPlayer.setMirrorMode(MirrorMode.MIRROR_MODE_HORIZONTAL);
// Specify vertical mirroring for the video images.
aliyunVodPlayer.setMirrorMode(MirrorMode.MIRROR_MODE_VERTICAL);

Obtain playback information

ApsaraVideo Player SDK for Android allows you to obtain playback information, such as the current playback progress, video duration, and buffering progress.

Obtain the current playback position

You can call the getExtraValue method in the onInfo callback to obtain the current playback position. Sample code:
mAliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
    @Override
    public void onInfo(InfoBean infoBean) {
        if(infoBean.getCode() == InfoCode.CurrentPosition){
            // Th extraValue parameter indicates the current playback position. Unit: milliseconds.
            long extraValue = infoBean.getExtraValue();
        }
    }
});

Obtain the video duration

You can query the total duration of a video. The video duration can be obtained only after the video is loaded. You can call the getDuration method after the onPrepared event is invoked to query the video duration. Sample code:
long duration = mAliPlayer.getDuration();

Obtain the buffered position

You can call the getExtraValue method in the onInfo callback to query the current buffered position. Sample code:
mAliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
    @Override
    public void onInfo(InfoBean infoBean) {
        if(infoBean.getCode() == InfoCode.BufferedPosition){
            // The extraValue parameter indicates the current buffered position. Unit: milliseconds.
            long extraValue = infoBean.getExtraValue();
        }
    }
});

Obtain the rendering frame rate, audio and video bitrate, and network downlink bitrate in real time

Sample code:
// Obtain the current frame rate for video rendering. The returned data is of the FLOAT data type. 
mAliPlayer.getOption(IPlayer.Option.RenderFPS);
// Obtain the current video bitrate. The returned data is of the FLOAT data type. 
mAliPlayer.getOption(IPlayer.Option.VideoBitrate);
// Obtain the current audio bitrate. The returned data is of the FLOAT data type. Unit: bit/s. 
mAliPlayer.getOption(IPlayer.Option.AudioBitrate);
// Obtain the current network downlink bitrate. The returned data is of the FLOAT data type. Unit: bit/s. 
mAliPlayer.getOption(IPlayer.Option.DownloadBitrate);

Listen to the playback status

You can listen to the player status in the onStateChanged callback. Sample code:
mAliPlayer.setOnStateChangedListener(new IPlayer.OnStateChangedListener() {
    @Override
    public void onStateChanged(int newState) {
        /*
          int idle = 0;
          int initalized = 1;
          int prepared = 2;
          int started = 3;
          int paused = 4;
          int stopped = 5;
          int completion = 6;
          int error = 7;
      */
    }
});

Configure the volume

You can adjust the player volume or configure the mute mode for the playback.

Change the volume

You can change the volume of a video to up to twice the original volume. Noise may occur if you set the volume to a value higher than 1. Call the setVolume method to change the volume. You can also obtain the current volume. Sample code:
// Set the volume to a real number from 0 to 2. 
aliyunVodPlayer.setVolume(1f);
// Obtain the volume information. 
aliyunVodPlayer.getVolume();

Configure the mute mode

Call the setMute method to mute a video during the playback. Sample code:
aliyunVodPlayer.setMute(true);

Configure the playback speed

ApsaraVideo Player SDK for Android allows you to call the setSpeed method to change the playback speed. Playback speeds ranging from 0.5x to 5x are supported. The audio pitch remains unchanged at different speeds. Sample code:
// Playback speeds ranging from 0.5x to 5x are supported. Common playback speeds are multiples of 0.5x, such as 0.5x, 1x, and 1.5x.
aliyunVodPlayer.setSpeed(1.0f);

Configure multi-definition settings

If you play a video based on VidAuth or VidSts, you do not need to configure multi-definition settings for the playback. ApsaraVideo Player SDK for Android automatically obtains video definitions from ApsaraVideo VOD. The SDK allows you to obtain video definitions and switch between definitions. This feature is not supported for UrlSource-based playback.

Obtain video definitions

After the video is loaded, you can obtain the video definitions.

// Obtain information about all streams of the video.
List<TrackInfo> trackInfos = mAliPlayer.getMediaInfo().getTrackInfos();
// Traverse all streams to obtain the video definitions.
for (TrackInfo trackInfo : trackInfos) {
     if(trackInfo.getType() == TrackInfo.Type.TYPE_VOD){
             // Obtain the video definition.
        String vodDefinition = trackInfo.getVodDefinition();
     }
}

Switching between definitions

You can call the selectTrack method to set TrackInfo to the index that corresponds to the definition in which you want to play the video.

mAliPlayer.selectTrack(index);

Send a notification about definition changes

Set the callbacks for the successful and failed definition switching.

mAliPlayer.setOnTrackChangedListener(new IPlayer.OnTrackChangedListener() {
    @Override
    public void onChangedSuccess(TrackInfo trackInfo) { }

    @Override
    public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) { }
});

Enable loop playback

ApsaraVideo Player SDK for Android supports loop playback. Call the setLoop method to enable loop playback. The loop playback feature allows you to play a video again from the beginning after the video playback ends. Sample code:
aliyunVodPlayer.setLoop(true);
TheonInfo callback is returned when loop playback starts. Sample code:
aliyunVodPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
    @Override
    public void onInfo(InfoBean infoBean) {
        if (infoBean.getCode() == InfoCode.LoopingStart){
            // The loop playback starts. 
        }
    }
});