Unoptimized Short Video | Optimized Short Video |
| |
// If you are using the professional version of the SDK,// use: api 'com.tencent.liteav:LiteAVSDK_Professional:latest.release'api 'com.tencent.liteav:LiteAVSDK_Player:latest.release'implementation (name:'tuiplayercore-release_x.x.x', ext:'aar')implementation (name:'tuiplayershortvideo-release_x.x.x', ext:'aar')implementation 'androidx.appcompat:appcompat:1.0.0'implementation 'androidx.viewpager2:viewpager2:1.0.0'
x.x.x
in tuiplayercore-release
and tuiplayershortvideo-release
represents the version number, note that the version numbers of the two aar files must match.<uses-permission android:name="android.permission.INTERNET" />
-keep class com.tencent.** { *; }
TUIPlayerConfig config = new TUIPlayerConfig.Builder().enableLog(true).licenseKey("Your license key").licenseUrl("Your license url").build();TUIPlayerCore.init(context, config);
<com.tencent.qcloud.tuiplayer.shortvideo.ui.view.TUIShortVideoViewandroid:id="@+id/my_video_view"android:layout_height="match_parent"android:layout_width="match_parent"/>
mSuperShortVideoView.setActivityLifecycle(getLifecycle());
mSuperShortVideoView.setListener(new TUIShortVideoListener() {@Overridepublic void onPageChanged(int index, TUIVideoSource videoSource) {if (index >= mSuperShortVideoView.getCurrentDataCount() - 1) {// append next page datamSuperShortVideoView.appendModels(data);}}@Override public void onCreateVodLayer(TUIVodLayerManager layerManger, int viewType) {// add your vod layer to here layerManger.addLayer(new TUICoverLayer()); } @Override public void onCreateLiveLayer(TUILiveLayerManager layerManager, int viewType) {// add your live layer to here }@Override public void onCreateCustomLayer(TUICustomLayerManager layerManager, int viewType) {// add your custom layer to here }@Overridepublic void onNetStatus(TUIVideoSource model, Bundle bundle) {}});
onPageChanged
method will be called back, where you can implement capabilities similar to paginated loading.
When the list creates its layout, it will call back the onCreateVodLayer
, onCreateLiveLayer
, or onCreateCustomLayer
methods based on the type of data you add. Specifically, if the data is of type TUIVideoSource
when setting models, onCreateVodLayer
will be called back; if it's of type TUILiveSource
, onCreateLiveLayer
will be called back; and if it's a custom data type implemented by inheriting from TUIPlaySource
, onCreateCustomLayer
will be called back.
Here, the extViewType
from TUIPlayerSource
will also be called back, which can be used for the business to distinguish different layer groups based on the viewType. The creation of layers will be discussed in the section on custom layers.
After the video starts playing, the network status of the currently playing video will be called back through onNetStatus
. For details on the callback, please refer to here.setModels
can set the data and clear the original data. The video will also restart playback from the first video of the newly set data source. Using appendModels
can append data, which is used for pagination operations. After filling the data, it will automatically start playing from the first video. If automatic playback is not needed, you can call setAutoPlay
on the first video and set it to false
.// vod TUIVideoSource videoSource = new TUIVideoSource(); videoSource.setCoverPictureUrl(model.placeholderImage); // Fill in the fileId. Only one of fileId and url needs to be filled in. videoSource.setAppId(model.appid); videoSource.setPSign(model.pSign); videoSource.setFileId(model.fileid); // Fill in the fileId url videoSource.setVideoURL(model.videoURL); shortVideoData.add(videoSource); // live TUILiveSource liveSource = new TUILiveSource(); // live url liveSource.setUrl(liveUrl); liveSource.setCoverPictureUrl(coverUrl); shortVideoData.add(liveSource); // Custom data. DemoImgSource inherits from TUIPlaySource, providing custom data.// Here, different data can be customized according to business requirements. DemoImgSource imgSource = new DemoImgSource("imgUrl"); shortVideoData.add(imgSource);// set datamSuperShortVideoView.setModels(shortVideoData);// For pagination operations, you can choose to append data.mSuperShortVideoView.appendModels(shortVideoData);
TUIVodLayer
, TUILiveLayer
, and TUICustomLayer
, respectively. Different layers can be inherited according to requirements. Different layer base classes provide interfaces and callbacks that fit their scenarios.onBindData
.LifeCycle Name | Description |
onBindData | Indicates that the current Layer has been bound to data. In this lifecycle, some static UI data initialization work can be done. |
onControllerBind | This page is already the one currently displayed in the short video list. Except for the custom page TUICustomLayer , calling getPlayer() and getController() at this time will no longer return null, allowing operations on the player and page container. |
onControllerUnBind | The page has been swiped away, and after this lifecycle, it will no longer be possible to obtain the player and videoView. This lifecycle can be used to perform resource recycling and interface resetting tasks. |
onViewRecycled | The page has been recycled and will be used with other data and players. It is recommended to reset all data on the interface and recycle related resources in this lifecycle. |
onShortVideoDestroyed | The TUI component has been destroyed, meaning the TUIShortVideoView's release method has been called. |
@Overridepublic View createView(ViewGroup parent) {LayoutInflater inflater = LayoutInflater.from(parent.getContext());View view = inflater.inflate(R.layout.player_video_info_layer, parent, false);mSeekBar = view.findViewById(R.id.vsb_tui_video_progress);mTvProgress = view.findViewById(R.id.tv_tui_progress_time);mIvPause = view.findViewById(R.id.iv_tui_pause);mSeekBar.setListener(this);return view;}@Overridepublic String tag() {return "TUIVideoInfoLayer";}
@Overridepublic void onBindData(TUIVideoSource videoSource) {show();}
@Overridepublic void onPlayBegin() {super.onPlayBegin();if (null != mIvPause) {mIvPause.setVisibility(View.GONE);}}@Overridepublic void onPlayPause() {super.onPlayPause();if (null != mIvPause) {mIvPause.setVisibility(View.VISIBLE);}}@Overridepublic void onPlayProgress(long current, long duration, long playable) {videoDuration = duration;if (null != mSeekBar) {// ensure a refresh at every percentage pointint progressInt = (int) (((1.0F * current) / duration) * 100);if(lastProgressInt != progressInt) {setProgress(progressInt / 100F);lastProgressInt = progressInt;}}}
@Overridepublic void onDragDone(VideoSeekBar seekBar) {TUIPlayerController controller = getPlayerController();if (null != controller && videoDuration > 0) {controller.seekTo((int) ((videoDuration * seekBar.getBarProgress()) / 1000));}if (null != mTvProgress) {mTvProgress.setVisibility(View.GONE);}}
@Override public void onViewRecycled(TUIBaseVideoView videoView) { // release your resource }
@Overridepublic void onControllerUnBind(TUIPlayerController controller) {super.onControllerUnBind(controller);show();}
@Overridepublic void onRecFileVideoInfo(TUIFileVideoInfo params) {if(isShowing()) {TUIBaseVideoView videoView = getVideoView();if (null != videoView && null != params) {String coverUrl = params.getCoverUrl();if (!TextUtils.isEmpty(coverUrl)) {ImageView imageView = getView();Glide.with(videoView).load(coverUrl).centerCrop().into(imageView);coverUrlFromServer = coverUrl;}}}}
@Overridepublic void onRcvFirstIframe() {hidden();}
mSuperShortVideoView.setListener(new TUIShortVideoListener() {// ......@Override public void onCreateVodLayer(TUIVodLayerManager layerManger, int viewType) { layerManger.addLayer(new TUIVideoInfoLayer(mShortVideoView, ShortVideoFragment.this)); layerManger.addLayer(new TUICoverLayer()); layerManger.addLayer(new TUILoadingLayer()); layerManger.addLayer(new TUIErrorLayer()); } @Override public void onCreateLiveLayer(TUILiveLayerManager layerManager, int viewType) { layerManager.addLayer(new TUILiveEntranceLayer(mShortVideoView, ShortVideoFragment.this)); layerManager.addLayer(new TUILiveLoadingLayer()); layerManager.addLayer(new TUILiveErrorLayer()); } @Override public void onCreateCustomLayer(TUICustomLayerManager layerManager, int viewType) { if (viewType == SVDemoConstants.CustomSourceType.SINGLE_IMG_TYPE) { layerManager.addLayer(new PicDisplayLayer()); } }});
viewType
is the video type of the current page. If you have customized extViewType
in TUIPlayerSource
, the viewType
here will be what you defined. If not defined, it will return ITEM_TYPE_VOD
, ITEM_TYPE_LIVE
, or ITEM_TYPE_CUSTOM
according to the page type.unbindLayerManager
method will be called back in the layer.layerManger.removeLayer(layer);
layerManger.indexOfLayer(layer);
public class DemoImgSource extends TUIPlaySource { private String mImgUrl; public DemoImgSource(String imgUrl) { mImgUrl = imgUrl; // You can specify different viewType parameters to distinguish between types of custom pages setExtViewType(SVDemoConstants.CustomSourceType.SINGLE_IMG_TYPE); } public String getImgUrl() { return mImgUrl; } public void setImgUrl(String imgUrl) { this.mImgUrl = imgUrl; } }
public class PicDisplayLayer extends TUICustomLayer { private ImageView mDisplayImgView; @Override public View createView(ViewGroup parent) {// Constructing a Page view LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.tuiplayer_img_display_layer, parent, false); mDisplayImgView = view.findViewById(R.id.iv_img_display); return view; } @Override public void onBindData(TUIPlaySource videoSource) { super.onBindData(videoSource);// Data is bound to the page, allowing access to the corresponding data source of the page if (videoSource.getExtViewType() == SVDemoConstants.CustomSourceType.SINGLE_IMG_TYPE) { DemoImgSource source = (DemoImgSource) videoSource; Glide.with(mDisplayImgView).load(source.getImgUrl()) .into(mDisplayImgView); } } @Override public String tag() { return "PicDisplayLayer"; } }
mSuperShortVideoView.setListener(new TUIShortVideoListener() {// ......@Override public void onCreateCustomLayer(TUICustomLayerManager layerManager, int viewType) {// custom layer if (viewType == SVDemoConstants.CustomSourceType.SINGLE_IMG_TYPE) { layerManager.addLayer(new PicDisplayLayer()); } }});
// Customize data, DemoImgSource inherits from TUIPlaySource, customize data,// different data can be customized here according to business needs DemoImgSource imgSource = new DemoImgSource("imgUrl"); shortVideoData.add(imgSource);// fill datamSuperShortVideoView.setModels(shortVideoData);
TUIPlayerConfig config = new TUIPlayerConfig.Builder().enableLog(true).licenseKey(LICENCE_KEY).licenseUrl(LICENCE_URL).build();TUIPlayerCore.init(getApplicationContext(), config);
mSuperShortVideoView.setActivityLifecycle(getLifecycle());
mSuperShortVideoView.setListener(new TUIShortVideoListener() {@Override public void onCreateVodLayer(TUIVodLayerManager layerManger, int viewType) { layerManger.addLayer(new TUIVideoInfoLayer(mShortVideoView, ShortVideoFragment.this)); layerManger.addLayer(new TUICoverLayer()); layerManger.addLayer(new TUILoadingLayer()); layerManger.addLayer(new TUIErrorLayer()); } @Override public void onCreateLiveLayer(TUILiveLayerManager layerManager, int viewType) { layerManager.addLayer(new TUILiveEntranceLayer(mShortVideoView, ShortVideoFragment.this)); layerManager.addLayer(new TUILiveLoadingLayer()); layerManager.addLayer(new TUILiveErrorLayer()); } @Override public void onCreateCustomLayer(TUICustomLayerManager layerManager, int viewType) { if (viewType == SVDemoConstants.CustomSourceType.SINGLE_IMG_TYPE) { layerManager.addLayer(new PicDisplayLayer()); } } @Override public void onPageChanged(int index, TUIPlaySource videoSource) { if (index >= mShortVideoView.getCurrentDataCount() - 1) { mShortViewRefresh.setRefreshing(true); ShortVideoModel.getInstance().loadMore(false); } } @Override public void onNetStatus(TUIPlaySource model, Bundle bundle) { }});
Method | Description |
setPreloadCount | Set the maximum concurrent preload quantity, default is 3. |
setPreDownloadSize | Set the preload cache size, default is 1MB, unit is MB. |
setPreLoadBufferSize | Set the pre-play cache size, default is 0.5MB, unit is MB. |
setMaxBufferSize | Set the video cache size during playback, default is 10MB, unit is MB. |
setPreferredResolution | Set the preferred resolution for video playback, default is 720 x 1280. |
setProgressInterval | Playback progress callback interval, default is 500 milliseconds, unit is milliseconds. |
setRenderMode | Render tiling mode, default is 0. In liteavPlayer, 0 represents full screen, 1 represents rendering according to the actual ratio of the video, which may have black borders. |
setExtInfo | Set additional information. |
setMediaType | When the media type to be played is known in advance, the media type can be set through this interface to reduce the detection of playback types within the player SDK and improve the startup speed. |
enableAutoBitrate | Set whether to enable bitrate adaptation. |
setResumeMode | Set the resume mode, which is divided into three modes: TUIConstants.TUIResumeMode.NONE: Do not resume playback. TUIConstants.TUIResumeMode.RESUME_LAST: Resume playback from the last time played. TUIConstants.TUIResumeMode.RESUME_PLAYED: Resume playback of all watched videos. |
setDisplayViewFactory | Set a custom video layer, which can be customized by implementing IDisplayViewFactory |
setEnableAccurateSeek | Set whether to enable precise seeking. After enabling precise seeking, the accuracy of seeking will be greatly improved, but seeking will take time. After disabling it, the actual seeking time may differ from the expected time, depending on the distribution of key frames in the video, but the seeking time will become shorter. |
setAudioNormalization | Set volume equalization, with a loudness range of -70 to 0 (LUFS), and also supports custom values. Note: Supported starting from version 11.7 of the advanced player. Predefined values can be filled in, related constant class TXVodConstants, Off: AUDIO_NORMALIZATION_OFF On: AUDIO_NORMALIZATION_STANDARD (standard) AUDIO_NORMALIZATION_LOW (low) AUDIO_NORMALIZATION_HIGH (high) |
setIsRetainPreVod | Whether to keep the previous player to speed up the startup of the previous player |
setRetryCount | Set the number of on-demand retry attempts under weak network conditions. If set to 0, no retries will be performed. |
mSuperShortVideoView.setModels(shortVideoBeanList);
mSuperShortVideoView.appendModels(shortVideoBeanList);
Method | Param Type | |
setVideoURL | String | Video link, it is recommended to fill in this field, which will speed up the preloading process. |
setCoverPictureUrl | String | Video cover, which will be callback to the layer, and handled by the customer. |
setAppId | int | Video appId. |
setFileId | String | Video fileId. |
setPSign | String | Video encryption pSign. |
setExtViewType | int | Custom page type, this value will be callback through the second parameter of the Layer creation callback, for the business to distinguish different types of pages. |
setExtInfoAndNotify | Object | For business to extend additional parameters on their own, using this method can notify messages to the existing layer in real-time. This method will only be valid after obtaining Source through TUIDataManager. |
setVideoConfig | TUIPlayerVideoConfig | Video independent configuration. |
setExternalSubtitle | List<TUISubtitleSource> | Set external subtitles, which will be loaded into the on-demand player automatically, and must be supported by the advanced version of the player. |
setAutoPlay | boolean | Set whether this video should play automatically. |
Method | Param Type | Description |
setPreloadBufferSizeInMB | float | Set a separate pre-play cache size for the video, optional. |
setPreferredResolution | long | Set a separate playback and preload resolution for the video, optional. |
setPreDownloadSize | float | Set a separate pre-download cache size for the video, optional. |
Method | Param Type | Description |
setUrl | String | Live streaming link |
setCoverPictureUrl | String | Video Cover, which will be callback to the layer, and handled by the customer. |
setExtViewType | int | Custom page type, this value will be callback through the second parameter of the Layer creation callback, for the business to distinguish different types of pages. |
setExtInfoAndNotify | Object | For business to extend additional parameters on their own, using this method can notify messages to the existing layer in real-time. This method will only be valid after obtaining Source through TUIDataManager. |
setLiveConfig | TUIPlayerLiveConfig | Independent configuration. |
setAutoPlay | boolean | Set whether to play automatically. When this field is set to false for live streaming, there will be no picture at first, and a cover image is needed to cover it. |
Method | Param Type | Description |
setCacheMinTime | float | Minimum time for automatic cache adjustment, the value must be greater than 0. [Default Value]: 1. |
setCacheMaxTime | float | Maximum time for automatic cache adjustment, the value must be greater than 0. [Default Value]: 5 |
Method | Param Type | Description |
setExtViewType | int | Custom page type, this value will be callback out through the second parameter of the Layer creation callback, for the business to distinguish different types of pages. |
setExtInfoAndNotify | Object | Used for the business to extend additional parameters on their own, this method can notify messages to an existing layer in the interface in real-time. This method will only be valid after being called by a Source obtained through TUIDataManager.
6. Operation list data |
// Obtain the data operation object TUIShortVideoDataManager dataManager = mSuperShortVideoView.getDataManager();
Method | Returned Param | Passed Param | Description |
removeData | void | index: The position of the page to be removed | Remove the corresponding page and data |
removeRangeData | void | index: The starting position of the page to be removed count: The number to be removed from the starting position, excluding the last digit of count | Remove a range of pages and data |
removeDataByIndex | void | removeIndexList: A collection of positions of the pages to be removed | Remove all pages and data within the index collection according to the passed index |
addData | void | source: The data to be inserted index: The position where the data is to be inserted | Insert the passed data into the specified position based on the position where the data is to be inserted |
addRangeData | void | sources: A collection of data to be inserted startIndex: The starting position for inserting data | Insert the data collection into the specified position based on the passed starting position |
replaceData | void | source: The data to be replaced index: The position to be replaced | Replace the data at the specified position with the passed data based on the passed position |
replaceRangeData | void | sources: A collection of data to be replaced startIndex: The starting position for replacement | Replace the specified position with the passed data collection based on the passed starting position |
getDataByPageIndex | TUIVideoSource | index: Page position | Obtain the page data at the specified position based on the passed position |
getCurrentDataCount | int | - | Get the total number of all data in the current list |
getCurrentIndex | int | - | Get the position of the currently displayed page |
getCurrentModel | TUIVideoSource | - | Get the data of the currently displayed page |
mSuperShortVideoView.getCurrentModel()
mSuperShortVideoView.pause()
// index is the specified page position.mSuperShortVideoView.startPlayIndex(index);// index is the position to navigate to, true indicates that smooth switching is required,// and the default is false. mSuperShortVideoView.startPlayIndex(index, true);
TUIVideoConst.ListPlayMode.MODE_LIST_LOOP
, which automatically plays the next video after the current one finishes, and after playing the last one, it automatically returns to the first video to continue playback. And single video loop playback TUIVideoConst.ListPlayMode.MODE_ONE_LOOP
, which will keep repeating the current video until the user manually swipes to flip the page. It can also be set to TUIVideoConst.ListPlayMode.MODE_CUSTOM, allowing the business to take over the playback logic. When not set, the default is MODE_ONE_LOOP
. The setting method is as follows:// set to MODE_ONE_LOOP mSuperShortVideoView.setPlayMode(TUIVideoConst.ListPlayMode.MODE_ONE_LOOP);
mSuperShortVideoView.release()
mSuperShortVideoView.resume()
mSuperShortVideoView.switchResolution(720 * 1080, TUIConstants.TUIResolutionType.CURRENT);
Param | Description |
GLOBAL | Set global resolution |
CURRENT | Set current video resolution |
Other values greater than or equal to 0 | Set resolution at specified position |
// pause all preloadmSuperShortVideoView.pausePreload();// start preload from current video indexmSuperShortVideoView.resumePreload();
Param | Type | Description |
layerManger | TUIVodLayerManager, TUILiveLayerManager And TUICustomLayerManager | Layer management object |
viewType | int | Current video playback type TUIVideoConst.ItemType.ITEM_TYPE_VOD: On-demand TUIVideoConst.ItemType.ITEM_TYPE_LIVE: Live broadcast TUIVideoConst.ItemType.ITEM_TYPE_CUSTOM: Custom interface Other custom types passed by PlayerSource |
layerManger.addLayer(new TUICoverLayer());layerManger.addLayer(new TUIVideoInfoLayer());layerManger.addLayer(new TUILoadingLayer());layerManger.addLayer(new TUIErrorLayer());
layerManger.removeLayer(layer);
layerManger.removeAllLayer();
layerManger.indexOfLayer(layer);
mSuperShortVideoView.setPageScroller(new LinearSmoothScroller(getContext()){ @Override protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) { // Return the time taken for each pixel to slide, measured in milliseconds return 25f/displayMetrics.densityDpi; } });
setUserInputEnabled
method of TUIShortVideoView
. Here's an example:// false:disables user sliding mSuperShortVideoView.setUserInputEnabled(false);
ITUILayer
callbacks, player event notifications, and component events from the videoView. After inheriting from TUIVodLayer
, TUILiveLayer
, and TUICustomLayer
, you can receive callbacks for video playback according to your functional requirements. Currently, the callback functions are as follows:Method | Return Type | Param | Description |
isShowing | boolean | - | Whether the current layer is being displayed. |
createView | View | parent: Layer container | Abstract method, needs to be implemented by yourself, used to create the View of the layer. |
tag | String | - | The tag of the layer, used to distinguish different layers. |
unBindLayerManager | void | - | The layer is unbound from the manager, which generally happens when the layer is removed. |
show | void | - | Display the current layer. |
hidden | void | - | Hide the current layer. |
getView | T extends View | - | Get the View of the current layer. |
getVideoView | TUIBaseVideoView | - | Get the current VideoView, if the layerManager has not yet bound with the VideoView, it will return empty. |
getPlayerController | TUIPlayerController | - | Get the current playback Controller, if it has not yet bound with the Controller, it will return empty. |
getPlayer | ITUIVodPlayer | - | Get the current player, if it has not yet bound with the Controller, it will return empty. |
getRenderMode | int | - | Get the rendering fill mode of the current player screen. |
onControllerBind | void | controller: Current video playback controller | The current VideoView is bound to the playback controller, that is, the current video becomes the video playing in the list. |
onControllerUnBind | void | controller: Current video playback controller | The VideoView is unbound from the playback controller, which generally indicates that the page has slid out of the interface. |
onBindData | void | videoSource: Video data | The current VideoView has bound video data. |
onViewRecycled | void | videoView: Current player view container | The current videoView has been recycled. |
onExtInfoChanged | void | videoSource: Changed video source | When extInfo is set through TUIPlaySource, the layer will notify events through this callback. |
onShortVideoDestroyed | void | - | When the entire short video component is destroyed, it will notify the layer through this callback for the layer to release resources. |
Method | Return Type | Param | Description |
isShowing | boolean | - | Whether the current layer is currently being displayed. |
createView | View | parent: Layer container | Abstract method that needs to be implemented by oneself, used for creating the View of the layer. |
tag | String | - | The tag of the layer, used to differentiate between different layers. |
unBindLayerManager | void | - | The layer is unbound from the manager, which typically occurs when the layer is removed. |
show | void | - | Show the current layer. |
hidden | void | - | Hide the current layer. |
getView | T extends View | - | Obtain the View of the current layer. |
getVideoView | TUIBaseVideoView | - | Get the current VideoView; if the layerManager has not yet bound to the VideoView, it will return empty. |
getPlayerController | TUIPlayerController | - | Obtain the current playback Controller; if it has not yet bound to the Controller, it will return empty. |
getPlayer | ITUILivePlayer | - | Get the current player; if it has not yet bound to the Controller, it will return empty. |
getRenderMode | int | - | Get the rendering fill mode of the current player screen. |
onControllerBind | void | controller: Current video playback controller | The current VideoView is bound to the playback controller, meaning the current video becomes the one playing in the list. |
onControllerUnBind | void | controller: Current video playback controller | The VideoView is unbound from the playback controller, typically indicating that the page has slid off the interface. |
onBindData | void | videoSource: Video data | The current VideoView has bound video data. |
onViewRecycled | void | videoView: Current player view container | The current videoView has been recycled. |
onExtInfoChanged | void | videoSource: Changed video source | After setting extInfo through TUIPlaySource, the layer will notify events through this callback. |
onShortVideoDestroyed | void | - | When the entire short video component is destroyed, it will notify the layer through this callback so that the layer can release resources. |
Method | Return Type | Param | Description |
isShowing | boolean | - | Whether the current layer is being displayed. |
createView | View | parent: Layer container | Abstract method that needs to be implemented by oneself, used for creating the View of the layer. |
tag | String | - | The tag of the layer, used to distinguish different layers. |
unBindLayerManager | void | - | The layer is unbound from the manager, which generally occurs when the layer is removed. |
show | void | - | Display the current layer. |
hidden | void | - | Hide the current layer. |
getView | T extends View | - | Obtain the View of the current layer. |
onControllerBind | void | - | The current VideoView is bound to the playback controller, meaning the current video is displayed in the list. |
onControllerUnBind | void | - | The VideoView is unbound from the playback controller, typically indicating that the page has slid off the interface. |
onBindData | void | videoSource: Video data | The current VideoView has bound video data. |
onViewRecycled | void | videoView: Current player view container | The current videoView has been recycled. |
onExtInfoChanged | void | videoSource: Changed video source | After setting extInfo through TUIPlaySource, the layer will notify events through this callback. |
onShortVideoDestroyed | void | - | When the entire short video component is destroyed, it will notify the layer through this callback so that the layer can release resources. |
Method | Return Type | Param | Description |
onPlayPrepare | void | - | Video is ready. |
onPlayBegin | void | - | Video starts playing. |
onPlayPause | void | - | Video pauses. |
onPlayStop | void | - | Video stops. |
onPlayLoading | void | - | Video begins loading. |
onPlayLoadingEnd | void | - | Video loading completes. |
onPlayProgress | void | current: The current video playback progress, in milliseconds, of type long. duration: The total duration of the current video, in milliseconds, of type long. playable: The playable duration of the current video, in milliseconds, of type long. | Video playback progress. |
onSeek | void | position: The progress of the video to jump to. In seconds, of type int. | Video progress seeked. |
onError | void | code: Video error code. message: Error description. | An error occurred during video playback. |
onRcvFirstIframe | void | - | Received the first frame event. |
onRcvTrackInformation | void | infoList: Video tracks. | Received video track information. |
onRcvSubTitleTrackInformation | void | infoList: Video subtitle information. | Received video subtitle information. |
onRecFileVideoInfo | void | params: Video file information. | Received video file information, which generally only triggers this callback when playing using fileId. |
onResolutionChanged | void | width: Video width.
height: Video height. | The current video resolution changes. |
onPlayEvent | void | player: Player.
event: Event ID.
bundle: Event content. | All event notifications from the player. |
onPlayEnd | void | - | The current video playback has ended. |
Medthod | Param | Description |
onError | player: Current live broadcast player
code: Error code
msg: Error message
extraInfo: Additional message | An error occurred during playback. |
onWarning | player: Current live broadcast player
code: Error code
msg: Warning message
extraInfo: Additional message | A warning occurred in the player. |
onVideoResolutionChanged | player: Current live broadcast player
width: Video width
height: Video height | The player's resolution has changed. |
onConnected | player: Current live broadcast player
extraInfo: Additional information | Data stream connection successful. |
onVideoPlaying | player: Current live broadcast player
firstPlay: Whether it is the first playback, which can be used to determine the first frame
extraInfo: Additional information | Video playback has started. |
onAudioPlaying | player: Current live broadcast player
firstPlay: Whether it is the first playback
extraInfo: Additional information | Audio playback has started. |
onVideoLoading | player: Current live broadcast player
extraInfo: Additional information | Video loading has begun. |
onAudioLoading | player: Current live broadcast player
extraInfo: Additional information | Audio loading has begun. |
onPlayoutVolumeUpdate | player: Current live broadcast player
volume: Changed volume | Player volume size callback. |
onStatisticsUpdate | player: Current live broadcast player
statistics: Data details | Live broadcast player statistics callback. |
onSnapshotComplete | player: Current live broadcast player
image: Screenshot image | Screenshot callback. |
onRenderVideoFrame | player: Current live broadcast player
videoFrame: Image frame | Custom video rendering callback, enabled by calling enableObserveVideoFrame. |
onPlayoutAudioFrame | player: Current live broadcast player
audioFrame: Audio frame | Custom audio data callback, enabled by calling enableObserveAudioFrame. |
onReceiveSeiMessage | player: Current live broadcast player
payloadType: SEI payloadType of the callback data.
data: Data | Callback for receiving SEI messages, sent by the sender through sendSeiMessage in V2TXLivePusher. |
onStreamSwitched | player: Current live broadcast player
url: Switched URL
code: Status code, 0: Success, -1: Switching timed out, -2: Switching failed, server error, -3: Switching failed, client error | Resolution seamless switching callback. |
onLocalRecordBegin | player: Current live broadcast player
code: Status code.
0: Recording task started successfully.
-1: Internal error caused recording task startup failure.
-2: Incorrect file extension (such as unsupported recording format).
-6: Recording has already started, need to stop recording first.
-7: Recording file already exists, need to delete the file first.
-8: Recording directory has no write permission, please check the directory permission issue.
storagePath: Recorded file address. | Event callback for the start of recording tasks. |
onLocalRecording | player: Current live broadcast player
durationMs: Recording duration
storagePath: Recorded file address. | Progress event callback for recording tasks in progress. |
onLocalRecordComplete | player: Current live broadcast player
code: Status code.
0: End recording task successfully.
-1: Recording failed.
-2: Switching resolution or landscape/portrait screen caused recording to end.
-3: Recording time is too short, or no video or audio data has been collected, please check the recording duration, or whether audio and video collection has been enabled.
storagePath: Recorded file address. | Event callback for recording tasks that have ended. |
Medthod | Return Type | Param | Description |
prePlay | void | model: Video data, type TUIVideoSource | Preload the video, with deduplication mechanism inside. |
resumePlay | void | - | Continue playing the current video. |
seekTo | void | time: The time point to jump to, in seconds, of type int. | Jump to the specified playback position. |
isPlaying | boolean | - | Check if the current video is playing. |
startPlay | void | model: Video data, type TUIVideoSource. | Play the video. |
pause | void | - | Pause the playback. |
stop | void | needClearLastImg: Optional parameter, whether to clear the current image. | Stop the playback. |
getCurrentPlayTime | float | - | Get the current playback time, in seconds. |
setDisplayView | void | videoView: Video rendering View, type TUIVideoRenderView. | Set the View to be rendered by the player. |
setSurface | void | surface:render surface | Set the surface to be rendered by the video. |
addPlayerObserver | void | observer: Player observer, type TUIVodObserver. | Set the player observer. |
removePlayerObserver | void | observer: Player observer, type TUIVodObserver. | Remove the player observer. |
setConfig | void | config: Video configuration, type TXVodPlayConfig. | Set the video configuration. |
setRenderMode | void | renderMode: Rendering mode, FULL_FILL_SCREEN: Maintain aspect ratio and fill the screen ADJUST_RESOLUTION: Maintain aspect ratio and display the video | Set the render mode. |
setStartTime | void | startTime: Start playing time, in seconds. float type | Set the start playback time, valid before playback, only takes effect once. Loop playback will start from the beginning. |
setLoop | void | isLoop: Whether to loop | Set whether the video is looped. |
setBitrateIndex | void | index: Bitrate index | Set the current bitrate. |
switchResolution | void | resolution: Resolution, i.e., width × height | Set the player's resolution for this playback, if there is a corresponding resolution, it will be switched and only take effect for this playback. |
getSupportResolution | List<TUIPlayerBitrateItem> | - | Get the list of resolutions of the video being played. |
getBitrateIndex | int | - | Get the bitrate index of the video being played. |
setRate | void | rate: Video speed, normal speed is 1.0 | Set the playback speed of the current player. |
getCurrentPlaybackTime | float | - | Get the time already played by the current player, in seconds. |
getBufferDuration | float | - | Get the buffered time of the current video, in seconds. |
getDuration | float | - | Get the total duration of the current video, in seconds. |
getPlayableDuration | float | - | Get the playable time of the current video, in seconds. |
getWidth | int | - | Get the width of the video being played. |
getHeight | int | - | Get the height of the video being played. |
setRenderRotation | void | rotation: Angle | Set the rotation angle of the current video. |
enableHardwareDecode | boolean | enable: Whether to enable hardware decoding | Set whether the current player uses hardware decoding. |
setMute | void | mute: Whether to mute | Set whether the currently playing video is muted. |
setAudioPlayoutVolume | void | volume: Video volume, 0 to 100 | Set the output volume of the current video. |
setRequestAudioFocus | boolean | requestFocus: Whether to get audio focus | Set whether the current player gets audio focus. |
snapshot | void | listener: TXLivePlayer.ITXSnapshotListener type, screenshot callback | Take a screenshot of the video being played by the current player. |
setMirror | void | mirror: Whether to mirror | Set whether the current video is mirrored. |
setToken | void | token: Encrypted HLS token | Set the encrypted HLS token. |
isLoop | boolean | - | Check if the current player is in loop playback. |
attachTRTC | void | trtcCloud: trtc service object | Push the audio and video streams of the player through TRTC, more TRTC services can be found in TRTC product overview. |
detachTRTC | void | - | Unbind TRTC service from the player. |
setStringOption | void | key: Business parameter key value
value: Business parameter value | Set the business parameters of the player. |
setSubtitleView | void | subtitleView: Subtitle component | Set the subtitle component of the video. |
addSubtitleSource | void | url: Subtitle link
name: Subtitle name
mimeType: Subtitle format | Add subtitle sources to the video. |
selectTrack | void | trackIndex: Audio/video track | Add/select audio/video tracks, commonly used for multi-audio track and subtitle selection. |
deselectTrack | void | trackIndex: Audio/video track | Remove selected audio/video tracks. |
setAudioNormalization | void | value: Loudness range: -70 to 0 (LUFS), with custom values supported. Note: The player advanced version 11.7 starts to support this feature. Fill in the preset value, related constants TXVodConstants,
Off: AUDIO_NORMALIZATION_OFF
On:
AUDIO_NORMALIZATION_STANDARD (Standard)
AUDIO_NORMALIZATION_LOW (Low)
AUDIO_NORMALIZATION_HIGH (High) | Set volume equalization. |
setSubtitleStyle | void | renderModel: Subtitle format | Set subtitle format. |
getSubtitleTrackInfo | List<TXTrackInfo> | - | Get imported subtitle track information, valid after the prepare event. |
getAudioTrackInfo | List<TXTrackInfo> | - | Get imported audio track information, valid after the prepare event. |
Method | Return Type | Description |
getIndex | int | Current resolution bitrate index. |
getWidth | int | Current resolution video width. |
getHeight | int | Current resolution video height. |
getBitrate | int | Current resolution video bitrate. |
Medthod | Return Type | Param | Description |
prePlay | void | model: Video data, type TUILiveSource | Preload live streaming, with deduplication mechanism inside. |
resumePlay | void | - | Continue playing the current video. |
setConfig | void | config: Live streaming configuration | Set player configuration. |
addLiveObserver | void | observer: Live event observer | Subscribe to live events. |
removeLiveObserver | void | observer: Live event observer | Unsubscribe from live event subscriptions. |
switchStream | int | model: The data source to be switched | Switch to other resolution streams of the current live source, returning 0 represents success. |
setRenderRotation | int | rotation: Rotation direction | Set the current screen rotation direction. |
setPlayoutVolume | int | volume: Volume size, ranging from 0 to 100.【Default】: 100 | Set the current volume size. |
getStreamList | ArrayList<V2TXLiveDef.V2TXLiveStreamInfo> | - | Get current bitrate information. |
enableVolumeEvaluation | int | value: Determines the trigger interval of the onPlayoutVolumeUpdate callback, in milliseconds, with a minimum interval of 100ms. If it is less than or equal to 0, the callback will be turned off, and it is recommended to set it to 300ms;【Default】: 0, not enabled | Enable playback volume size prompt. |
snapshot | int | - | Capture video frames during playback.
Return value: V2TXLiveCode.
V2TXLIVE_OK: Success.
V2TXLIVE_ERROR_REFUSED: The player is in the stopped state and does not allow the screenshot operation to be called. |
enableReceiveSeiMessage | int | enable: true: Enable receiving SEI messages; false: Disable receiving SEI messages.【Default】: false.
payloadType: Specify the payloadType to receive SEI messages, supporting 5 and 242, and keep it consistent with the payloadType of the sending end. | Enable receiving SEI messages. |
showDebugView | void | isShow: Whether to display.【Default】: false. | Whether to display the debug overlay of the player status information. |
setProperty | int | key: The key corresponding to the advanced API.
value: The parameter needed when calling the advanced API corresponding to the key. | Call the advanced API interface of V2TXLivePlayer. |
startLocalRecording | int | params: Local recording audio and video configuration | Start recording audio and video streams.
Return value V2TXLiveCode.
V2TXLIVE_OK : Success.
V2TXLIVE_ERROR_INVALID_PARAMETER : Invalid parameter, such as filePath is empty.
V2TXLIVE_ERROR_REFUSED : API is refused, streaming has not started yet. |
stopLocalRecording | void | - | Stop recording audio and video streams. After stopping streaming, if the video is still being recorded, the SDK will automatically end the recording. |
mShortVideoView.setItemAnimator(new DefaultItemAnimator());
TUIPreloadApi.getInstance().addObserver(new TUIPreloadObserver() { @Override public void onVodPreloadStatusChanged(TUIVideoSource vodSource, int state, long resolution) { } });
TUIConstants#TUIPreLoadState
.// get data controller TUIShortVideoDataManager dataManager = mSuperShortVideoView.getDataManager(); // get dataSource TUIPlaySource videoSource = dataManager.getDataByPageIndex(0); Map<String, String> data = new HashMap<>(); data.put("key1", "data1"); // set extInfo and notify to layer videoSource.setExtInfoAndNotify(data);
onExtInfoChanged
callback, allowing UI modifications to the current page. The example is as follows:@Override public void onExtInfoChanged(TUIVideoSource videoSource) { super.onExtInfoChanged(videoSource); Map<String, String> data = (Map<String, String>) videoSource.extInfo; Log.i("tag", "get data:" + data); }
onExtInfoChanged
will only be triggered after binding data with onBindData
./** Supports custom numerical values, loudness range: -70 to 0 (LUFS)* Preset values: Off: TXVodConstants#AUDIO_NORMALIZATION_OFF* On (Low): TXVodConstants#AUDIO_NORMALIZATION_LOW* On (Standard): TXVodConstants#AUDIO_NORMALIZATION_STANDARD* On (High): TXVodConstants#AUDIO_NORMALIZATION_HIGH*/ TUIPlayerVodStrategy vodStrategy = new TUIPlayerVodStrategy.Builder() .setAudioNormalization(TXVodConstants.AUDIO_NORMALIZATION_STANDARD) .build(); mShortVideoView.setVodStrategy(vodStrategy);
computeVerticalScrollOffset
: The current vertical scroll offset (in pixels).computeVerticalScrollRange
: The vertical scroll range of the RecyclerView (total height, in pixels).computeComputeVerticalScrollExtent
: The total height of visible items in the current scroll view (in pixels).computeVerticalScrollOffset
method returns a value less than or equal to 0, it indicates that the list has scrolled to the top. At this point, the touch event can be passed to the outer layout to perform a pull-to-refresh.computeVerticalScrollExtent
and the distance already scrolled computeVerticalScrollOffset
. If the sum is greater than or equal to the total height computeVerticalScrollRange
, it can be judged whether the list has scrolled to the bottom. The code is as follows:int verticalScrollOffset = recyclerView.computeVerticalScrollOffset();int verticalScrollRange = recyclerView.computeVerticalScrollRange();int verticalScrollExtent = recyclerView.computeVerticalScrollExtent();boolean isAtBottom = verticalScrollOffset + verticalScrollExtent >= verticalScrollRange;
Was this page helpful?