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

Play a video

This section describes how to play a video by using ApsaraVideo Player SDK for Android. You can create a player for manual playback or autoplay.

  1. Create a player.
    Create an AliPlayer object by using the AliPlayerFactory class.
    AliPlayer aliPlayer = AliPlayerFactory.createAliPlayer(context);
    aliPlayer.setTraceId("traceId");  // The trace ID is the unique identifier of the device used by the user. In most cases, the value is the International Mobile Equipment Identity (IMEI) or the Identifier for Advertisers (IDFA) of the device.
  2. Set listeners.
    You can configure multiple listeners for your player.
    • You must configure the OnPreparedListener listener because you must call the aliPlayer.start() method to start playback after the OnPreparedListener callback is invoked.
    • We recommend that you configure the following listeners: OnErrorListener, OnCompletionListener, OnLoadingStatusListener, and OnInfoListener.
    aliPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
        // If an error occurs when you use the player, this callback is invoked. 
    
        @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() {
        // After you call the aliPlayer.prepare() method, the player starts to read and parse data. If the preparation is successful, this callback is invoked. 
    
        @Override
        public void onPrepared() {
            // The aliPlayer.start() method is called to start the playback.
            aliPlayer.start();
        }
    });
    aliPlayer.setOnCompletionListener(new IPlayer.OnCompletionListener() {
        // After the playback is complete, this callback is invoked. 
        @Override
        public void onCompletion() {
            // The aliPlayer.stop() method is called to stop the playback.
            aliPlayer.stop();
        }
    });
    aliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
        // Listen to specific information, such as the current 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.
    
            // Current progress: InfoCode.CurrentPosition
            // Current buffer position: InfoCode.BufferedPosition
        }
    });
    aliPlayer.setOnLoadingStatusListener(new IPlayer.OnLoadingStatusListener() {
        // Listen to the loading status. If the network is unstable, this callback is invoked to display the loading status. 
    
        @Override
        public void onLoadingBegin() {
            // Listen to the start of loading. In this case, video and audio streams cannot be played. 
            // In general, the loading circle is displayed.
        }
    
        @Override
        public void onLoadingProgress(int percent, float netSpeed) {
            // Listen to the loading progress. The loading percentage and network speed are displayed. 
        }
    
        @Override
        public void onLoadingEnd() {
            // Listen to the end of loading. In this case, video and audio streams can be played. 
            // In general, the loading circle is hidden.
        }
    });
  3. Configure a playback source.
    • ApsaraVideo Player SDK for Android supports UrlSource, VidAuth, VidSts, VidMps, and encrypted sources for video-on-demand (VOD) playback. We recommend that you use VidAuth sources.
    • ApsaraVideo Player SDK for Android supports UrlSource and encrypted sources for live streaming.
    Note
    • You can use UrlSource sources for URL-based playback, and use VidSts and VidAuth sources for video ID-based playback.
    • For more information about the endpoints of various regions, see Region IDs of ApsaraVideo VOD.
    • For more information about playback in ApsaraVideo Media Processing (MPS), see Play videos.

    VOD playback

    To use UrlSource for URL-based playback, you must set the source parameter to specify the streaming URL. You can specify the streaming URL of a file stored in a third-party VOD service or in ApsaraVideo VOD. You can call the GetPlayInfo operation to obtain the streaming URL of a file stored in ApsaraVideo VOD. We recommend that you integrate ApsaraVideo VOD server operation SDK to obtain the streaming URL of a file stored in ApsaraVideo VOD. This way, you do not need to calculate the signature. For more information about the GetPlayInfo operation, visit OpenAPI Explorer.

    Demo of UrlSource

     UrlSource urlSource = new UrlSource();
            urlSource.setUri("Streaming URL");// The streaming URL of a file stored in a third-party VOD service or in ApsaraVideo VOD. 
            aliPlayer.setDataSource(urlSource);

    To use VidAuth sources for VOD playback, you must set the Vid parameter to specify the audio or video ID and set the playAuth parameter to specify the playback credential. After you upload an audio or video file, you can view the audio or video ID in the ApsaraVideo VOD console. After you log on to the ApsaraVideo VOD console, choose Media Files > Audio /Video. On the page that appears, you can view the audio or video ID. Alternatively, you can call the SearchMedia operation by using a server operation SDK. For more information, see SearchMedia. You can call the GetVideoPlayAuth operation to obtain the playback credential. We recommend that you integrate ApsaraVideo VOD server operation SDK to obtain the playback credential. This way, you do not need to calculate the signature. For more information about the GetVideoPlayAuth operation, visit OpenAPI Explorer.

    We recommend that you use VidAuth sources for playback. Compared with Security Token Service (STS)-based playback, playback implemented based on playback credentials is easier to use and more secure. For more information about the comparison between the two playback methods, see Comparison between credentials and STS.

    Demo of VidAuth

    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 from which you want to access ApsaraVideo VOD. Default value: cn-shanghai.
            aliPlayer.setDataSource(vidAuth);

    If you use VidSts sources, a temporary STS token rather than a playback credential is used. You must obtain the temporary STS token in advance. For more information, see Create a role and grant temporary access permissions to the role by using STS. You must set the SecurityToken parameter to specify the obtained STS token and set the AccessKeyId and AccessKeySecret parameters to specify the AccessKey ID and AccessKey secret that are generated based on the STS token.

    Demo of VidSts

    VidSts vidSts = new VidSts();
            vidSts.setVid("Video ID"); // The video ID.
            vidSts.setAccessKeyId("<Your AccessKey ID>"); // The AccessKey ID used for authentication.
            vidSts.setAccessKeySecret("<Your AccessKey secret"); // The AccessKey secret used for authentication.
            vidSts.setSecurityToken("<Security token>"); // The security token.
            vidSts.setRegion("Access region ID"); // The region from which you want to access ApsaraVideo VOD. Default value: cn-shanghai.
            aliPlayer.setDataSource(vidSts);

    You can use VidMps sources for playback if you use the ApsaraVideo Media Processing (MPS) service. You must obtain the following information in advance:

    • Vid: the ID of the media asset in MPS.
    • AcessKeyId and AccessKeySecret: the AccessKey pair that is issued together with the temporary STS token.
    • SecurityToken: the temporary STS token.
    • domainRegion: the region in which the media asset resides.
    • authInfo: the authorization information.

    For information about media assets in MPS, see Play videos.

    Demo of VidMps

    VidMps vidMps = new VidMps();
            vidSts.setRegion("Access region ID"); // The ID of the region from which you want to access ApsaraVideo VOD. Default value: cn-shanghai.
            vidMps.setMediaId("Media ID");// The media ID, which also indicates the video ID.
            vidMps.setAuthInfo("Authentication information");// The authentication information.
            vidSts.setAccessKeyId("<Your AccessKey ID>"); // The AccessKey ID used for authentication.
            vidSts.setSecurityToken("<Security token>"); // The security token.
            vidMps.setPlayDomain("Streaming domain");// The streaming domain.
            vidMps.setHlsUriToken("HlsUriToken");// The HlsUriToken.
            vidMps.setAccessKeySecret("<Your AccessKey secret>"); // The AccessKey secret used for authentication.
            aliPlayer.setDataSource(vidMps);

    ApsaraVideo VOD supports three types of encryption methods: HTTP-Live-Streaming encryption (HLS), Alibaba Cloud proprietary cryptography, and digital rights management (DRM) encryption. For more information about how to play encrypted videos, see Encrypt videos for playback.

    Live streaming

    To use UrlSource for URL-based playback, you must call the setUrl method to specify the source URL. You can specify the source URL of the live stream in a third-party live service or in ApsaraVideo Live. The ApsaraVideo Live console provides a URL generator to help you generate source URLs. For more information, see URL generator.

    Demo of UrlSource sources for live streaming

    UrlSource urlSource = new UrlSource();
            urlSource.setUri("Source URL");// The source URL of the live stream in a third-party live service or in ApsaraVideo Live. 
            aliPlayer.setDataSource(urlSource);

    For more information about how to play DRM-encrypted videos, see Encrypt videos for playback.

  4. Set the UI view.
    SurfaceView and TextureView are supported. Set the UI view to SurfaceView or TextureView.
    • Sample code for SurfaceView:
      SurfaceView surfaceView = findViewById(R.id.surface_view);
      surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
          @Override
          public void surfaceCreated(SurfaceHolder holder) {
              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);
          }
      });
    • Sample code for TextureView:
      TextureView textureView = findViewById(R.id.texture_view);
      textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
          @Override
          public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
              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, the autoplay feature is disabled.
    aliPlayer.setAutoPlay(true);
  6. Prepare the player.
    Call the aliPlayer.prepare() method to start reading and parsing 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 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. 

Control the playback

ApsaraVideo Player SDK for Android allows you to control the playback. For example, you can start, pause, and stop the playback and play a video from a specific position.

Start the playback

Start the playback by calling the start method. The following sample code provides an example:
aliyunVodPlayer.start();

Play a video from a specific position

Play a video from a specific position by calling the seekTo method. This feature is applicable to scenarios in which you want to start playback from a specific position. For example, you want to seek video content or resume the video playback from the paused position. The following sample code provides an example:
// Set the position parameter to specify the point in time from which you want to start the playback. Unit: seconds. 
aliyunVodPlayer.seekTo(long position);

Pause the playback

Pause the playback by calling the pause method. The following sample code provides an example:
aliyunVodPlayer.pause();

Stop the playback

Stop the playback by calling the stop method. The following sample code provides an example:
aliyunVodPlayer.stop();

Set the video display mode

ApsaraVideo Player SDK for Android provides multiple methods for you to control video images. You can set the scaling mode, rotation angle, and mirroring mode for video images.

Set the scaling mode

Set the scaling mode to aspect ratio-based fitting, aspect ratio-based padding, or stretching by calling the setScalingMode method. The following sample code provides an example:
// Set the scaling mode to aspect ratio-based fitting. In this mode, the video images are scaled down into the UI view without changing the aspect ratio. This prevents image distortion.
aliyunVodPlayer.setScaleMode(ScaleMode.SCALE_ASPECT_FIT);
// Set the scaling mode to aspect ratio-based padding. In this mode, the video images are scaled up to fill the UI view without changing the aspect ratio. This prevents image distortion.
aliyunVodPlayer.setScaleMode(ScaleMode.SCALE_ASPECT_FILL);
// Set the scaling mode to stretching. In this mode, the video images are stretched to fill the UI view. This may cause image distortion if the video images and the UI view do not match in the aspect ratio.
aliyunVodPlayer.setScaleMode(ScaleMode.SCALE_TO_FILL);

Set the rotation angle

Set the rotation angle for video images by calling the setRotateMode method. You can query the rotation angle after it is set. The following sample code provides an example:
// 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();

Set the mirroring mode

Set the mirroring mode to horizontal mirroring, vertical mirroring, or no mirroring by calling the setMirrorMode method. The following sample code provides an example:
// Disable mirroring.
aliyunVodPlayer.setMirrorMode(MirrorMode.MIRROR_MODE_NONE);
// Set the mirroring mode to horizontal mirroring.
aliyunVodPlayer.setMirrorMode(MirrorMode.MIRROR_MODE_HORIZONTAL);
// Set the mirroring mode to vertical mirroring.
aliyunVodPlayer.setMirrorMode(MirrorMode.MIRROR_MODE_VERTICAL);

Obtain the playback information

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

Obtain the current playback position

Obtain the current playback position by calling the getExtraValue method. The information about the playback position can be obtained after the onInfo callback is invoked. The following sample code provides an example:
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

After the video is loaded and the onPrepared event is triggered, you can obtain the video duration by calling the getDuration method. The following sample code provides an example:
long duration = mAliPlayer.getDuration();

Obtain the buffering progress

Obtain the buffering progress by calling the getExtraValue method. The buffering progress can be obtained in the onInfo callback. The following sample code provides an example:
mAliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
    @Override
    public void onInfo(InfoBean infoBean) {
        if(infoBean.getCode() == InfoCode.BufferedPosition){
            // The extraValue parameter indicates the buffering progress. Unit: milliseconds.
            long extraValue = infoBean.getExtraValue();
        }
    }
});

Listen to the player status

You can listen to the player status. The parameters of the onPlayerStatusChanged callback indicate the player status. The following sample code provides an example:
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;
      */
    }
});

Set the volume

You can set the mute mode and the volume.

Set the volume

You can set the volume by calling the setVolume method. You can obtain the volume after it is set. The following sample code provides an example:
// Set the player volume to a real number ranging from 0 to 1. 
aliyunVodPlayer.setVolume(1f);
// Obtain the volume. 
aliyunVodPlayer.getVolume();

Mute the player

Mute the player by calling the setMute method. The following sample code provides an example:
aliyunVodPlayer.setMute(true);

Set the playback speed

ApsaraVideo Player SDK for Android allows you to set the playback speed. You can call the setSpeed method to change the playback speed from 0.5x to 5x. The audio pitch remains unchanged at different speeds. The following sample code provides an example:
// Set the playback speed. You can set the playback speed from 0.5x to 5x. The value must be a multiple of 0.5, such as 0.5, 1, and 1.5.
aliyunVodPlayer.setSpeed(1.0f);

Configure multi-definition playback

If you use VidAuth and VidSts sources for playback, you do not need to manually set parameters for multi-definition playback. ApsaraVideo Player SDK for Android obtains the definitions supported by ApsaraVideo VOD. You can query and switch the video definition as needed. If you use UrlSource sources, you cannot configure multi-definition playback.

Obtain the video definitions

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

// 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();
     }
}

Switch to another video definition

You can switch to another video definition by calling the selectTrack method and setting the index parameter.

mAliPlayer.selectTrack(index);

Set the callbacks for definition switching

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. To configure the loop playback feature, call the setLoop method. The loop playback feature allows the player to play a video again when the player plays the video to the end position. The following sample code provides an example:
aliyunVodPlayer.setLoop(true);
The onInfo callback is invoked for the start of loop playback. The following sample code provides an example:
aliyunVodPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
    @Override
    public void onInfo(InfoBean infoBean) {
        if (infoBean.getCode() == InfoCode.LoopingStart){
            // Listen to the start of loop playback. 
        }
    }
});