This topic describes how to create a player instance and use basic features of ApsaraVideo Player SDK for Android, such as setting the volume, performing video seeking, monitoring playback status, enabling loop playback, configuring the playback speed, and switching audio tracks.
Create a player
This section describes how to use ApsaraVideo Player SDK for Android to play videos. Manual playback and autoplay are supported.
Create a player.
Call the AliPlayerFactory
class to create an AliPlayer object.
Note
ApsaraVideo VOD supports the playback quality monitoring, single-point tracing, and statistical analysis features based on the event tracking logs. You can use the playback quality monitoring feature to query statistics about overall playback quality and use the single-point tracing feature to locate the specific user or device, analyze the playback behavior, and identify the error in an efficient manner. For more information, see Playback quality monitoring, Single-point tracing, and Statistical analysis.
You can configure the setTraceId
parameter to use the features. The following content describes the configurations:
If you leave the setTraceId
parameter empty, the event tracking logs are automatically uploaded. You can use only the playback quality monitoring and statistical analysis features. By default, this parameter is left empty.
If you specify the unique identifier of the device or the user for the setTraceId
parameter, the event tracking logs are automatically uploaded. You can use the playback quality monitoring feature and the single-point tracing feature. For example, you can specify the user ID or device ID such as the International Mobile Equipment Identity (IMEI) or the Identifier for Advertisers (IDFA) for this parameter.
If you specify DisableAnalytics
for the setTraceId
parameter, the event tracking logs are not uploaded. You cannot use the playback quality monitoring, single-point tracing, or statistical analysis feature.
AliPlayer aliPlayer = AliPlayerFactory.createAliPlayer(context);
aliPlayer.setTraceId("traceId");
Note
The event tracking logs are uploaded to nodes in the China (shanghai) region. The Singapore region will be available soon.
Configure listeners.
You can configure multiple listeners for your player.
You must configure OnPreparedListener
. This way, you can 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() {
@Override
public void onError(ErrorInfo errorInfo) {
ErrorCode errorCode = errorInfo.getCode()
String errorMsg =errorInfo.getMsg();
String errorExtra= errorInfo.getExtra();
aliPlayer.stop();
}
});
aliPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
@Override
public void onPrepared() {
aliPlayer.start();
}
});
aliPlayer.setOnCompletionListener(new IPlayer.OnCompletionListener() {
@Override
public void onCompletion() {
aliPlayer.stop();
}
});
aliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
@Override
public void onInfo(InfoBean infoBean) {
InfoCode code = infoBean.getCode();
String msg = infoBean.getExtraMsg();
long value = infoBean.getExtraValue();
}
});
aliPlayer.setOnLoadingStatusListener(new IPlayer.OnLoadingStatusListener() {
@Override
public void onLoadingBegin() {
}
@Override
public void onLoadingProgress(int percent, float netSpeed) {
}
@Override
public void onLoadingEnd() {
}
});
Configure a playback source.
ApsaraVideo Player SDK for Android supports video-on-demand (VOD) playback based on UrlSource, VidAuth, and VidSts. 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 streaming.
Note
UrlSource is used for URL-based playback, and VidSts and VidAuth are used for Vid-based playback.
For more information about regions, see Region IDs of ApsaraVideo VOD.
Play a video on demand
UrlSource
(Recommended) VidAuth
VidSts
Encrypted playback
If you play an on-demand video based on UrlSource, you must set the setUrl parameter to the playback URL of the video.
You can call the GetPlayInfo operation to obtain playback URLs in ApsaraVideo VOD. We recommend that you integrate ApsaraVideo VOD SDKs to obtain media playback URLs in ApsaraVideo VOD. This frees you from complex signature calculations. For more information about the GetPlayInfo operation, visit OpenAPI Explorer.
Make sure that you are authorized to call API operations to obtain the full path of the local file if you want to play a local video. Example: /sdcard/xxx/xxx/xxx.mp4
or content://xxx/xxx/xx.mp4
.
UrlSource urlSource = new UrlSource();
urlSource.setUri("Playback URL");
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.
After you upload an audio or video file, you can log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video to view the ID of the audio or video file. Alternatively, you can call the SearchMedia operation provided by the ApsaraVideo VOD SDK to obtain the ID.
You can call the GetVideoPlayAuth operation to obtain the playback credential. We recommend that you integrate ApsaraVideo VOD SDK to obtain credentials for media playback in ApsaraVideo VOD. This frees you from complex signature calculations. For more information about the GetVideoPlayAuth operation, visit OpenAPI Explorer.
We recommend that you use this playback method in ApsaraVideo VOD. Compared with STS-based playback, VidAuth-based playback is easier to use and more secure. For more information about the differences between the two playback methods, see Comparison between credentials and STS.
If you enable parameter pass-through for HLS encryption in the ApsaraVideo VOD console, the default parameter name is MtsHIsUriToken. For more information, see Parameter pass-through for HLS encryption. You can use the following code to add the value of MtsHIsUriToken to the VOD source.
VidAuth vidAuth = new VidAuth();
vidAuth.setVid("Vid");
vidAuth.setPlayAuth("yourPlayAuth");
vidAuth.setRegion("Access region");
VidPlayerConfigGen vidConfig = new VidPlayerConfigGen();
vidConfig.setMtsHlsUriToken("<yourMtsHlsUriToken>");
vidAuth.setPlayerConfig(config);
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 and an AccessKey pair (AccessKey ID and AccessKey secret) before you play videos on demand. For more information about how to obtain an STS token, see Use STS to upload videos.
If you enable parameter pass-through for HLS encryption in the ApsaraVideo VOD console, the default parameter name is MtsHIsUriToken. For more information, see Parameter pass-through for HLS encryption. You can use the following code to add the value of MtsHIsUriToken to the VOD source.
VidSts vidSts = new VidSts();
vidSts.setVid("Video ID");
vidSts.setAccessKeyId("<yourAccessKeyId>");
vidSts.setAccessKeySecret("<yourAccessKeySecret>");
vidSts.setSecurityToken("<yourSecurityToken>");
vidSts.setRegion("Access region");
VidPlayerConfigGen vidConfig = new VidPlayerConfigGen();
vidConfig.setMtsHlsUriToken("<yourMtsHlsUriToken>");
vidSts.setPlayerConfig(config);
aliPlayer.setDataSource(vidSts);
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, see Play an encrypted video.
Live streaming
UrlSource-based playback
DRM-encrypted live streaming
If you play a live stream based on UrlSource, you must set the setUrl parameter to the streaming URL of the video. 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 streaming URLs. For more information, see Live URL generator.
UrlSource urlSource = new UrlSource();
urlSource.setUri("Streaming URL");
aliPlayer.setDataSource(urlSource);
Configure the view.
You can call the SurfaceView or TextureView method to configure the view.
Optional. Enable the autoplay feature. By default, the autoplay feature is disabled.
aliPlayer.setAutoPlay(true);
Prepare the player.
Call the aliPlayer.prepare()
method to read and parse data.
Start the playback.
If the autoplay feature is not enabled, you must call the aliPlayer.start()
method after the OnPrepared
callback is fired 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.
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 the playback
You can call the start
method to start the playback. Sample code:
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 when the video is resumed from a specific point in time. Sample code:
aliyunVodPlayer.seekTo(long position);
You can call the setStartTime method to set the start time of a video. The configuration take effect only once. This feature is used when you start the playback of a video from a specific point in time. Sample code:
aliyunVodPlayer.setStartTime(time, seekMode);
Pause the playback
You can call the pause
method to pause the playback. Sample code:
Stop the playback
You can call the stop
method to stop the playback. Sample code:
Destroy the player
You can synchronously or asynchronously destroy the player. Sample code:
aliyunVodPlayer.release();
aliyunVodPlayer.releaseAsync();
Note
The synchronous destroy operation returns the result after the player resources are released. If you have high requirements on the response speed of the UI, we recommend that you call the asynchronous destroy operation. Usage notes:
Do not perform any other operations on the player object during asynchronous destroy.
The asynchronous destroy operation includes an asynchronous stop process. Therefore, you do not need to manually stop the player before calling the asynchronous destroy operation.
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 setScaleMode
to scale in or scale out a video without changing the original aspect ratio, or stretch a video. Sample code:
aliyunVodPlayer.setScaleMode(ScaleMode.SCALE_ASPECT_FIT);
aliyunVodPlayer.setScaleMode(ScaleMode.SCALE_ASPECT_FILL);
aliyunVodPlayer.setScaleMode(ScaleMode.SCALE_TO_FILL);
Rotating
You can call setRotateMode
to specify a rotation angle for video images. You can query the rotation angle after it is set. Sample code:
aliyunVodPlayer.setRotateMode(RotateMode.ROTATE_0);
aliyunVodPlayer.setRotateMode(RotateMode.ROTATE_90);
aliyunVodPlayer.setRotateMode(RotateMode.ROTATE_180);
aliyunVodPlayer.setRotateMode(RotateMode.ROTATE_270);
aliyunVodPlayer.getRotateMode();
Mirroring
You can call setMirrorMode
to specify a mirroring mode. Horizontal mirroring, vertical mirroring, and no mirroring are supported. Sample code:
aliyunVodPlayer.setMirrorMode(MirrorMode.MIRROR_MODE_NONE);
aliyunVodPlayer.setMirrorMode(MirrorMode.MIRROR_MODE_HORIZONTAL);
aliyunVodPlayer.setMirrorMode(MirrorMode.MIRROR_MODE_VERTICAL);
Obtain the playback information
ApsaraVideo Player SDK for Android allows you to obtain playback information, such as the current playback progress, playback duration, and buffering progress.
Obtain the playback progress
You can call getExtraValue
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){
long extraValue = infoBean.getExtraValue();
}
}
});
Obtain the playback 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 getDuration
after the onPrepared event is invoked to query the video duration. Sample code:
long duration = mAliPlayer.getDuration();
Obtain the actual playback duration
You can obtain the actual playback duration in real time, which does not include the time when the playback is paused or stuck. Sample code:
long duration = player.getPlayedDuration();
Obtain the buffer position
You can call getExtraValue
in the onInfo callback to query the current buffering progress. Sample code:
mAliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
@Override
public void onInfo(InfoBean infoBean) {
if(infoBean.getCode() == InfoCode.BufferedPosition){
long extraValue = infoBean.getExtraValue();
}
}
});
Obtain the rendering frame rate, audio and video bitrate, and network downlink bitrate in real time
Sample code:
mAliPlayer.getOption(IPlayer.Option.RenderFPS);
mAliPlayer.getOption(IPlayer.Option.VideoBitrate);
mAliPlayer.getOption(IPlayer.Option.AudioBitrate);
mAliPlayer.getOption(IPlayer.Option.DownloadBitrate);
Obtain the player 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) {
}
});
Callback for audio and video out of sync
You can specify to fire a callback when audio and video are out of sync. Out of sync occurs when decoding is slower than playback in extreme cases such as software decoding 4K videos and high-speed playback of HD H.265 videos on low-end devices. Sample code:
mAliPlayer.setOnAVNotSyncStatusListener(new IPlayer.OnAVNotSyncStatusListener() {
@Override
public void onAVNotSyncStart(int type) {
if (type == 0) {
if (player.getSpeed() > 1) {
player.setSpeed(1);
}
}
Toast.makeText(getContext(), "Out-of-sync starts" , Toast.LENGTH_SHORT).show();
}
@Override
public void onAVNotSyncEnd() {
Toast.makeText(getContext(), "Out-of-sync ends" , Toast.LENGTH_SHORT).show();
}
});
Specify the volume
You can set the mute mode and the volume.
Change the volume
You can change the volume of a video to up to twice the original volume. If you set the volume to a value higher than 1, noise may occur. We recommend that you do not set the volume to a value higher than 1. Call setVolume
to change the volume. You can also obtain the current volume. Sample code:
aliyunVodPlayer.setVolume(1f);
aliyunVodPlayer.getVolume();
Mute the player
Call setMute
to mute a video that is being played. Sample code:
aliyunVodPlayer.setMute(true);
Configure the playback speed
ApsaraVideo Player SDK for Android allows you to call setSpeed
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:
aliyunVodPlayer.setSpeed(1.0f);
Configure multi-definition playback
Configure UrlSource-based live streaming
Note
You can play live streams based on URLs in ApsaraVideo Live or URLs of the transcoded live streams. Default transcoding and custom transcoding are supported. For more information about how to transcode live streams, see Transcoding management. For more information about how to obtain streaming URLs, see Ingest and streaming URLs.
You can switch between live streams in different definitions. Only Real-Time Messaging Protocol (RTMP) and Flash Video (FLV) streams are supported.
You must set the group of pictures (GOP) size to 2 seconds and the timestamp to the time when the source video is pushed.
If you change the streaming URL to a URL that does not meet the preceding requirements, the switching fails.
Switching between definitions
Call the switchStream
method to switch between live streams in different definitions. Specify the URL of the live stream that you want to play.
mAliPlayer.switchStream(newUrl);
Set the callbacks for definition switching
Set the callbacks for the successful and failed definition switching.
mAliPlayer.setOnStreamSwitchedListener(new IPlayer.OnStreamSwitchedListener() {
@Override
public void onSwitchedSuccess(String url) {
Log.i("SwitchStream", "switch success, url = " + url);
}
@Override
public void onSwitchedFail(String url, ErrorInfo errorInfo) {
Log.i("SwitchStream", "switch failed, url = " + url + ", error=" + errorInfo.getMsg());
}
});
Configure VidAuth or VidSts-based playback
If you use VidAuth or VidSts to play on-demand videos, no additional settings are required. ApsaraVideo Player SDK for Android automatically obtains video definitions from ApsaraVideo VOD.
Query the definition
After the video is loaded, you can obtain the definitions of the video.
List<TrackInfo> trackInfos = mAliPlayer.getMediaInfo().getTrackInfos();
for (TrackInfo trackInfo : trackInfos) {
if(trackInfo.getType() == TrackInfo.Type.TYPE_VOD){
String vodDefinition = trackInfo.getVodDefinition();
}
}
Switch between definitions
You can call selectTrack
and specify the index that corresponds to the definition to which you want to switch. You can obtain the index from the TrackInfo 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) { }
});
Quick switching
After you enable the quick switching mode, you can call selectTrack
to quickly switch tracks.
playerConfig.mSelectTrackBufferMode = 1;
mAliPlayer.setConfig(playerConfig)
Enable loop playback
ApsaraVideo Player SDK for Android supports loop playback. Call setLoop
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);
The onInfo
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){
}
}
});
Switch audio tracks
ApsaraVideo Player SDK for Android supports audio track switching. This allows you to switch audio tracks in different languages during video playback.
Usage notes
You can switch audio tracks in streams that are not used for list playback such as MP4 streams, single-bitrate mixed HLS streams, audio tracks in single-bitrate HLS streams, and substreams in multi-bitrate mixed HLS streams. The following table describes different types of video streams.
Type | Video stream suffix | Bitrate quantity | M3U8 file quantity | Substream type | Description |
Type | Video stream suffix | Bitrate quantity | M3U8 file quantity | Substream type | Description |
Non-list stream (such as MP4 stream) | .mp4 | 1 | - | A stream that contains a video track, multiple audio tracks, and multiple subtitle tracks. | You can switch between audio tracks. |
Single-bitrate mixed HLS stream | .m3u8 | 1 | 1 | A stream that contains a video track, multiple audio tracks, and multiple subtitle tracks. | You can switch between audio tracks. |
Single-bitrate HLS stream | .m3u8 | 1 | n | An M3U8 stream that contains only video tracks, audio tracks, or subtitle tracks. | You can switch between audio tracks. |
Multi-bitrate mixed HLS stream | .m3u8 | n | n | An M3U8 stream that contains a video track, multiple audio tracks, and multiple subtitle tracks. The bitrate of the substreams are different. | You can switch between different substreams. You cannot switch between the audio tracks of a substream. |
Usage notes
Configure callbacks.
mAliyunVodPlayer.setOnSubTrackReadyListener(new IPlayer.OnSubTrackReadyListener() {
@Override
public void onSubTrackReady(MediaInfo mediaInfo) {
if (mPlayerTrackFragment != null) {
MediaInfo subMediaInfo = mAliyunVodPlayer.getSubMediaInfo();
TrackInfos = subMediaInfo.getTrackInfos();
myTrack = myfunc(TrackInfos)
}
}
});
Switch to the desired track.
index = myTrack.getIndex();
mAliyunVodPlayer.selectTrack(index);
Obtain SDK logs
SDK logs are generated when you use ApsaraVideo Player SDK. The logs contain detailed information such as request status, invocation results, and permission application results. You can debug code and troubleshoot problems by viewing the SDK logs to facilitate development. You can use one of the following methods to obtain SDK logs.
Method 1: Use the console of your development tool
This method captures logs on your local device. It is suitable for scenarios where you can reliably reproduce the error on your device.
Enable the logging feature and set the log level.
Logger.getInstance(context).enableConsoleLog(true);
Logger.getInstance(context).setLogLevel(Logger.LogLevel.AF_LOG_LEVEL_INFO);
Configure frame-level logs.
Logger.getInstance(this).setLogOption(Logger.LogOption.FRAME_LEVEL_LOGGING_ENABLED,value);
Note
This feature is used in troubleshooting scenarios.
Collect logs.
Reproduce the error and obtain the error log in the console of your development tool such as Logcat.
Method 2: Set LogCallback to receive ApsaraVideo Player SDK logs
This method uses the LogCallback method. It is suitable for scenarios where the error occurs on the client side but you cannot reliably reproduce the error and capture logs on your device. You can call LogCallback to listen to the log export of ApsaraVideo Player SDK and automatically export error logs to the log channel of your application.
Enable the logging feature and set the log level.
Logger.getInstance(context).setLogLevel(Logger.LogLevel.AF_LOG_LEVEL_INFO);
Logger.getInstance(mContext).setLogCallback(newLogger.OnLogCallback(){
@Override
public void onLog(Logger.LogLevel logLevel,Strings){
}
});
Collect logs.
After an error occurs, the system automatically exports the error log to the log channel of your application.