TXCloudVideoView
for video rendering by default. First, add the following code to the layout XML file:<com.tencent.rtmp.ui.TXCloudVideoViewandroid:id="@+id/video_view"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_centerInParent="true"android:visibility="gone"/>
setPlayerView
API to associate the object with the video_view control just added to the UI.// `mPlayerView` is the video rendering view added in step 3TXCloudVideoView mPlayerView = findViewById(R.id.video_view);// Create a player objectTXVodPlayer mVodPlayer = new TXVodPlayer(getActivity());// Associate the player object with the video rendering viewmVodPlayer.setPlayerView(mPlayerView);
TXVodPlayer
supports two playback modes for you to choose as needed:TXVodPlayer
will internally recognize the playback protocol automatically. You only need to pass in your playback URL to the startVodPlay
function.// Play back a video resource at a URLString url = "http://1252463788.vod2.myqcloud.com/xxxxx/v.f20.mp4";mVodPlayer.startVodPlay(url);// Play back a local video resourceString localFile = "/sdcard/video.mp4";mVodPlayer.startVodPlay(localFile);// Starting from version 11.8, the player supports content:// URI video resources and asset catalog video resources// Play content:// URI video resourcesString localFile = "content://xxx/xxx/video.mp4";mVodPlayer.startVodPlay(localFile);// Play asset catalog video resources, the passed address must start with asset://String localFile = "asset://video.mp4";mVodPlayer.startVodPlay(localFile
// We recommend you use the following new API:// `psign` is a player signature. For more information on the signature and how to generate it, see [Player Signature](https://www.tencentcloud.com/document/product/266/38099).TXPlayInfoParams playInfoParam = new TXPlayInfoParams(1252463788, // `appId` of the Tencent Cloud account"4564972819220421305", // `fileId` of the video"psignxxxxxxx"); // The player signaturemVodPlayer.startVodPlay(playInfoParam);// Legacy API, which is not recommendedTXPlayerAuthBuilder authBuilder = new TXPlayerAuthBuilder();authBuilder.setAppId(1252463788);authBuilder.setFileId("4564972819220421305");mVodPlayer.startVodPlay(authBuilder);
FileId
, and the player will request the backend for the real playback URL. If the network is abnormal or the FileId
doesn't exist, the TXLiveConstants.PLAY_ERR_GET_PLAYINFO_FAIL
event will be received; otherwise, TXLiveConstants.PLAY_EVT_GET_PLAYINFO_SUCC
will be received, indicating that the request succeeded.startVodPlay
. This can prevent memory leak and screen flashing issues.onDestroy()
function for the rendering view. This can prevent memory leak and "Receiver not registered" alarms.@Overridepublic void onDestroy() {super.onDestroy();mVodPlayer.stopPlay(true); // `true` indicates to clear the last-frame imagemPlayerView.onDestroy();}
stopPlay
indicates whether to clear the last-frame image. Early versions of the live player of the RTMP SDK don't have an official pause feature; therefore, this boolean value is used to clear the last-frame image.// Start playbackmVodPlayer.startVodPlay(url)
// Pause the videomVodPlayer.pause();
// Resume the videomVodPlayer.resume();
// Stop the videomVodPlayer.stopPlay(true);
seek
can be called to start playback at the specified position. The Player SDK supports accurate seek.int time = 600; // In seconds if the value is of `int` type// float time = 600; // In seconds if the value is of `float` type// Adjust the playback progressmVodPlayer.seek(time);
float time = 600; // Unit is seconds for float type// Adjust progressmVodPlayer.seek(time, true); // Precise seekmVodPlayer.seek(time, false); // Imprecise seek
long pdtTimeMs = 600; // Unit is millisecondsmVodPlayer.seekToPdtTime(time);
startVodPlay
for the first time.float startTimeInSecond = 60; // Unit: SecondmVodPlayer.setStartTime(startTimeInSecond); // Set the playback start timemVodPlayer.startVodPlay(url);
video_view
control added in the Add a view step during SDK integration.Value | Definition |
RENDER_MODE_FULL_FILL_SCREEN | Images are scaled to fill the entire screen, and the excess parts are cropped. There are no black bars in this mode, but images may not be displayed entirely. |
RENDER_MODE_ADJUST_RESOLUTION | Images are scaled so that the long side of the video fits the screen. Neither side exceeds the screen after scaling. Images are centered, and there may be black bars visible. |
Value | Definition |
RENDER_ROTATION_PORTRAIT | Normal playback (the Home button is below the video image) |
RENDER_ROTATION_LANDSCAPE | Clockwise rotation of the image by 270 degrees (the Home button is on the left of the video image) |
// Fill the screen at the original aspect ratiomVodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN);// Normal playback (the Home button is below the video image)mVodPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);
setRate
API to set the VOD playback speed, such as 0.5x, 1.0x, 1.2x, and 2x speed.// Set playback at 1.2X ratemVodPlayer.setRate(1.2);
// Set playback loopmVodPlayer.setLoop(true);// Get the current playback loop statusmVodPlayer.isLoop();
// Mute or unmute the player. true: Mute; false: UnmutemVodPlayer.setMute(true);
// Take a screenshotmVodPlayer.snapshot(new ITXSnapshotListener() {@Overridepublic void onSnapshot(Bitmap bmp) {if (null != bmp) {// Get the screenshot bitmap}}});
autoPlay
is set to NO
, the player will load the video normally but will not immediately start playing it back.resume
API will be called to start video playback.mVodPlayer.setAutoPlay(false); // Set manual playbackmVodPlayer.startVodPlay(url); // The video will be loaded after `startVodPlay` is called and won't be played back automatically after being loaded successfully.// ......// Display the ad on the player UI// ......mVodPlayer.resume(); // Call `resume` to start playing back the video after the ad display ends
headers
in TXVodPlayConfig
can be used to set HTTP request headers, such as the Referer
field commonly used to prevent the URL from being copied arbitrarily (Tencent Cloud provides a more secure signature-based hotlink protection solution) and the Cookie
field for client authenticationTXVodPlayConfig mPlayConfig = new TXVodPlayConfig();Map<String, String> headers = new HashMap<>();headers.put("Referer", "${Refer Content}");mPlayConfig.setHeaders(headers);mVodPlayer.setConfig(mPlayConfig);
mVodPlayer.stopPlay(true);mVodPlayer.enableHardwareDecode(true);mVodPlayer.startVodPlay(flvUrl, type);
// Get the array of multiple bitrates. The TXBitrateItem class fields mean: index - bitrate index; width - video width; height - video height; bitrate - video bitrateArrayList<TXBitrateItem> bitrates = mVodPlayer.getSupportedBitrates();int index = bitrates.get(i).index; // Specify the bitrate index to be playedmVodPlayer.setBitrateIndex(index); // Switch the bitrate to the desired clarity// Get the index of the currently played bitrate. The return value of -1000 is the default value, indicating that no bitrate has been set; the return value of -1 indicates that adaptive streaming is enabledint index = mVodPlayer.getBitrateIndex();
mVodPlayer.setBitrateIndex(int)
at any time to switch the bitrate. During the switch, the data of another stream will be pulled. The SDK is optimized for Tencent Cloud multi-bitrate files to implement smooth switching.mVodPlayer.setBitrateIndex(-1); // Pass in `-1` for the `index` parameter
mVodPlayer.setBitrateIndex(int)
at any time to switch to another bitrate. After the switch, adaptive bitrate streaming will be disabled.TXVodPlayConfig mPlayConfig = new TXVodPlayConfig();// If it is set to `true`, the bitrate can be switched smoothly when IDR frames are aligned. If it is set to `false`, multi-bitrate URLs are opened faster.mPlayConfig.setSmoothSwitchBitrate(true);mVodPlayer.setConfig(mPlayConfig);
TXVodPlayer
object, and the progress notification will be called back to your application through the PLAY_EVT_PLAY_PROGRESS event. The event information contains the above two progress metrics.mVodPlayer.setVodListener(new ITXVodPlayListener() {@Overridepublic void onPlayEvent(TXVodPlayer player, int event, Bundle param) {if (event == TXLiveConstants.PLAY_EVT_PLAY_PROGRESS) {// Loading progress in msint playable_duration_ms = param.getInt(TXLiveConstants.EVT_PLAYABLE_DURATION_MS);mLoadBar.setProgress(playable_duration_ms); // Set the loading progress bar// Playback progress in msint progress_ms = param.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS);mSeekBar.setProgress(progress_ms); // Set the playback progress bar// Total video duration in msint duration_ms = param.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS);// It can be used to set duration display, etc.// Get the PDT time. This function is supported starting from version 11.6 of the player's advanced edition.long pdt_time_ms = param.getLong(TXVodConstants.EVT_PLAY_PDT_TIME_MS);}}@Overridepublic void onNetStatus(TXVodPlayer player, Bundle bundle) {}});
NET_STATUS_NET_SPEED
of onNetStatus
to get the current network speed. For detailed directions, see Playback status feedback (onNetStatus).PLAY_EVT_PLAY_LOADING
event is detected, the current network speed will be displayed.PLAY_EVT_VOD_LOADING_END
event is received, the view showing the current network speed will be hidden.mVodPlayer.setVodListener(new ITXVodPlayListener() {@Overridepublic void onPlayEvent(TXVodPlayer player, int event, Bundle param) {if (event == TXLiveConstants.PLAY_EVT_PLAY_LOADING) {// Show the current network speed} else if (event == TXLiveConstants.PLAY_EVT_VOD_LOADING_END) {// Hide the view showing the current network speed}}@Overridepublic void onNetStatus(TXVodPlayer player, Bundle bundle) {// Get the real-time speed in Kbpsint speed = bundle.getInt(TXLiveConstants.NET_STATUS_NET_SPEED);}});
NET_STATUS_VIDEO_WIDTH
and NET_STATUS_VIDEO_HEIGHT
of onNetStatus
to get the video width and height. For detailed directions, see Playback status feedback (onNetStatus).TXVodPlayer.getWidth()
and TXVodPlayer.getHeight()
to get the current video width and height after receiving the PLAY_EVT_VOD_PLAY_PREPARED
event callback from the player.mVodPlayer.setVodListener(new ITXVodPlayListener() {@Overridepublic void onPlayEvent(TXVodPlayer player, int event, Bundle param) {}@Overridepublic void onNetStatus(TXVodPlayer player, Bundle bundle) {// Get the video widthint videoWidth = bundle.getInt(TXLiveConstants.NET_STATUS_VIDEO_WIDTH);// Get the video heightint videoHeight = bundle.getInt(TXLiveConstants.NET_STATUS_VIDEO_HEIGHT);}});// Get the video width and height. The values can be returned only after the `PLAY_EVT_VOD_PLAY_PREPARED` event callback is received from the playermVodPlayer.getWidth();mVodPlayer.getHeight();
TXVodPlayConfig config = new TXVodPlayConfig();config.setMaxBufferSize(10); // Maximum buffer size during playback in MBmVodPlayer.setConfig(config); // Pass in `config` to `mVodPlayer`
File sdcardDir = getApplicationContext().getExternalFilesDir(null);if (sdcardDir != null) {// Set the global cache directory of the playback engineTXPlayerGlobalSetting.setCacheFolderPath(sdcardDir.getPath() + "/txcache");// Set the global cache directory and cache size in MB of the playback engineTXPlayerGlobalSetting.setMaxCacheSize(200);}// Use the player
TXVodPlayConfig#setMaxCacheItems
API used for configuration on earlier versions has been deprecated and is not recommended.// For DRM playback, please configure it through TXVodPlayer#setSurface before playback, otherwise playback exceptions may occur.mVodPlayer.setSurface(mPlayerView.getHolder().getSurface());// psign is the signature of the player. For information on generating and using player signatures, please refer to the following link:https://www.tencentcloud.com/document/product/266/42436?from_cn_redirect=1TXPlayInfoParams playInfoParam = new TXPlayInfoParams(${appId}, // Tencent Cloud account's appId${fieId}, // The fileId of the DRM-encrypted video${psgin}); // The player signature of the encrypted videomVodPlayer.startVodPlay(playInfoParam);
// For DRM playback, please configure it through TXVodPlayer#setSurface before playback, otherwise playback exceptions may occur.mVodPlayer.setSurface(mPlayerView.getHolder().getSurface());// Step 1: Set the DRM certificate provider environment. This step is not required by default.// The Google DRM certificate provider environment defaults to the googleapis.com domain, but can be set to the googleapis.cn domain using the following API:TXPlayerGlobalSetting.setDrmProvisionEnv(TXPlayerGlobalSetting.DrmProvisionEnv.DRM_PROVISION_ENV_CN); // googleapis.cn domain certificate location// Step 2: Play using the TXVodPlayer#startPlayDrm interface.TXPlayerDrmBuilder builder = new TXPlayerDrmBuilder();builder.setPlayUrl(${url}); // Set the URL of the video to be played.builder.setKeyLicenseUrl(${keyLicneseUrl}); // Set decryption key URLmVodPlayer.startPlayDrm(builder);
// Add TXSubtitleView to the layout XML where the player is located.<com.tencent.rtmp.ui.TXSubtitleViewandroid:id="@+id/subtitle_view"android:layout_width="wrap_content"android:layout_height="wrap_content"/>mSubtitleView = findViewById(R.id.subtitle_view);// Set the subtitle rendering target object.mVodPlayer.setSubtitleView(mSubtitleView);
// Pass in the subtitle URL, subtitle name, and subtitle type. It is recommended to add subtitles before starting the playback.mVodPlayer.addSubtitleSource("https://mediacloud-76607.gzc.vod.tencent-cloud.com/DemoResource/subtitleVTT.vtt", "subtitleName", TXVodConstants.VOD_PLAY_MIMETYPE_TEXT_VTT);
// After starting to play the video, select the added external subtitle. Please call it after receiving theVOD_PLAY_EVT_VOD_PLAY_PREPARED
event.@Overridepublic void onPlayEvent(TXVodPlayer player, int event, Bundle param) {if (event == TXVodConstants.VOD_PLAY_EVT_VOD_PLAY_PREPARED) {List<TXTrackInfo> subtitleTrackInfoList = mVodPlayer.getSubtitleTrackInfo();for (TXTrackInfo track : subtitleTrackInfoList) {Log.d(TAG, "TrackIndex= " + track.getTrackIndex() + " ,name= " + track.getName());if (TextUtils.equals(track.getName(), "subtitleName")) {// Selected SubtitlesmVodPlayer.selectTrack(track.trackIndex);} else {// If other subtitles are not required, proceed with deselectTrack.mVodPlayer.deselectTrack(track.trackIndex);}}}}// If needed, you can listen for track switching messages.mVodPlayer.setVodListener(new ITXVodPlayListener() {@Overridepublic void onPlayEvent(TXVodPlayer player, int event, Bundle param) {if (event == TXVodConstants.VOD_PLAY_EVT_SELECT_TRACK_COMPLETE) {int trackIndex = param.getInt(TXVodConstants.EVT_KEY_SELECT_TRACK_INDEX);int errorCode = param.getInt(TXVodConstants.EVT_KEY_SELECT_TRACK_ERROR_CODE);Log.d(TAG, "receive VOD_PLAY_EVT_SELECT_TRACK_COMPLETE, trackIndex=" + trackIndex + " ,errorCode=" + errorCode);}}@Overridepublic void onNetStatus(TXVodPlayer player, Bundle status) {}});
// For detailed parameter configuration, please refer to the API documentation.TXSubtitleRenderModel model = new TXSubtitleRenderModel();model.canvasWidth = 1920; // Width of the subtitle rendering canvasmodel.canvasHeight = 1080; // Height of the subtitle rendering canvas modelmodel.fontColor = 0xFFFFFFFF; // Set the font color of the subtitle, default is white and opaquemodel.isBondFontStyle = false; // Set whether the subtitle font is boldmVodPlayer.setSubtitleStyle(model);
// Returns a list of audio track informationList<TXTrackInfo> soundTrackInfoList = mVodPlayer.getAudioTrackInfo();for (TXTrackInfo trackInfo : soundTrackInfoList) {if (trackInfo.trackIndex == 0) {// Switch to the required audio track by checking the trackIndex or namemVodPlayer.selectTrack(trackInfo.trackIndex);} else {// Deselect the unwanted audio trackmVodPlayer.deselectTrack(trackInfo.trackIndex);}}
setAutoPlay
in TXVodPlayer
to implement the feature as follows:
// Play back video A: If `autoPlay` is set to `true`, the video will be immediately loaded and played back when `startVodPlay` is calledString urlA = "http://1252463788.vod2.myqcloud.com/xxxxx/v.f10.mp4";playerA.setAutoPlay(true);playerA.startVodPlay(urlA);// To preload video B when playing back video A, set `setAutoPlay` to `false`String urlB = @"http://1252463788.vod2.myqcloud.com/xxxxx/v.f20.mp4";playerB.setAutoPlay(false);playerB.startVodPlay(urlB); // The video won't be played back immediately but will start to be loaded
resume
function to immediately play back video B.autoPlay
is set to false
, make sure that video B has been prepared before calling resume
, that is, you should call it only after the PLAY_EVT_VOD_PLAY_PREPARED
event of video B (2013: the player has been prepared, and the video can be played back) is detected.public void onPlayEvent(TXVodPlayer player, int event, Bundle param) {// When video A ends, directly start playing back video B for seamless switchif (event == PLAY_EVT_PLAY_END) {playerA.stop();playerB.setPlayerView(mPlayerView);playerB.resume();}}
AutoPlay
of the player is set to false
before video playback starts).TXVodPlayConfig config = new TXVodPlayConfig();config.setMaxPreloadSize(2); // Maximum preloading buffer size in MB. Set it based on your business conditions to reduce the traffic consumptionmVodPlayer.setConfig(config); // Pass in `config` to `mVodPlayer`
TXVodPlayConfig config = new TXVodPlayConfig();config.setMaxBufferSize(10); // Maximum buffer size during playback in MBmVodPlayer.setConfig(config); // Pass in `config` to `mVodPlayer`
TXPlayerGlobalSetting
is the global cache setting API, and the original TXVodConfig
API has been deprecated.TXVodConfig
of the player.// Set the global cache directory and cache size of the playback engineFile sdcardDir = getApplicationContext().getExternalFilesDir(null);// Set the global cache directory and cache size of the playback engineif (sdcardDir != null) {TXPlayerGlobalSetting.setCacheFolderPath(sdcardDir.getPath() + "/PlayerCache");TXPlayerGlobalSetting.setMaxCacheSize(200); // Unit: MB}String palyrl = "http://****";// Start predownloadingfinal TXVodPreloadManager downloadManager = TXVodPreloadManager.getInstance(getApplicationContext());final int taskID = downloadManager.startPreload(playUrl, 3, 1920*1080, new ITXVodPreloadListener() {@Overridepublic void onComplete(int taskID, String url) {Log.d(TAG, "preload: onComplete: url: " + url);}@Overridepublic void onError(int taskID, String url, int code, String msg) {Log.d(TAG, "preload: onError: url: " + url + ", code: " + code + ", msg: " + msg);}});// Cancel predownloadingdownloadManager.stopPreload(taskID);
// Set the global cache directory and cache size for the playback engine FileFile sdcardDir = getApplicationContext().getExternalFilesDir(null);// Set the global cache directory and cache size for the playback engineif (sdcardDir != null) {TXPlayerGlobalSetting.setCacheFolderPath(sdcardDir.getPath() + "/PlayerCache");TXPlayerGlobalSetting.setMaxCacheSize(200); // Unit: MB}// Start preloadingRunnable task = new Runnable() {@Overridepublic void run() {TXPlayInfoParams playInfoParams = new TXPlayInfoParams(${appId}, "${fileId}","${psign}");// Note: This is a time-consuming operation, do not call it on the main thread! // Calling it on the main thread will throw an illegal call exception.mPreLoadManager.startPreload(playInfoParams, 3, 1920 * 1080, new ITXVodFilePreloadListener() {@Overridepublic void onStart(int taskID, String fileId, String url, Bundle bundle) {// The onStart method will be called when the file URL is successfully obtained using the fileId.Log.d(TAG, "preload: onStart: taskID: " + taskID + ", fileId: " + fileId + ", url: " + url + ",bundle: " + bundle);}@Overridepublic void onComplete(int taskID, String url) {Log.d(TAG, "preload: onComplete: url: " + url);}@Overridepublic void onError(int taskID, String url, int code, String msg) {Log.d(TAG, "preload: onError: url: " + url + ", code: " + code + ", msg: " + msg);}});}};new Thread(task).start();// Cancel preloadingdownloadManager.stopPreload(taskID);
TXVodDownloadManager
to implement offline HLS playback.File sdcardDir = context.getExternalFilesDir(null);TXPlayerGlobalSetting.setCacheFolderPath(sdcardDir.getPath() + "/txcache");
TXVodDownloadManager
is designed as a singleton; therefore, you cannot create multiple download objects. It is used as follows:TXVodDownloadManager downloader = TXVodDownloadManager.getInstance();
Fileid
, you need to pass in AppID
, Fileid
, and qualityId
at least. For signed videos, you also need to pass in pSign
. If no specific value is passed in to userName
, it will be default
by default.Fileid
and must enter the psign
parameter.// QUALITY_240P 240p// QUALITY_360P 360P// QUALITY_480P 480p// QUALITY_540P 540p// QUALITY_720P 720p// QUALITY_1080P 1080p// QUALITY_2K 2k// QUALITY_4K 4k// The quality parameter can be customized to take the minimum value of the resolution width and height (for example, if the resolution is 1280*720 and you want to download the stream with this resolution, pass in QUALITY_720P)// The player SDK will select a stream that is less than or equal to the passed-in resolution for downloading.TXVodDownloadDataSource source = new TXVodDownloadDataSource(1252463788, "4564972819220421305", QUALITY_720P, "pSignxxxx", ""); //pSign encrypted video signature, mandatory download via fileIddownloader.startDownload(source)
userName
, it will be default
by default.downloader.startDownloadUrl("http://1500005830.vod2.myqcloud.com/43843ec0vodtranscq1500005830/00eb06a88602268011437356984/video_10_0.m3u8", "");
downloader.setListener(this);
Callback Message | Description |
void onDownloadStart(TXVodDownloadMediaInfo mediaInfo) | The task started, that is, the SDK started the download. |
void onDownloadProgress(TXVodDownloadMediaInfo mediaInfo) | Task progress. During download, the SDK will frequently call back this API. You can use mediaInfo.getProgress() to get the current progress. |
void onDownloadStop(TXVodDownloadMediaInfo mediaInfo) | The task stopped. When you call stopDownload to stop the download, if this message is received, the download is stopped successfully. |
void onDownloadFinish(TXVodDownloadMediaInfo mediaInfo) | Download was completed. If this callback is received, the entire file has been downloaded, and the downloaded file can be played back by TXVodPlayer . |
void onDownloadError(TXVodDownloadMediaInfo mediaInfo, int error, String reason) | A download error occurred. If the network is disconnected during download, this API will be called back and the download task will stop. The error code is in TXVodDownloadManager . |
Error Code | Value | Description |
DOWNLOAD_SUCCESS | 0 | Download succeeded. |
DOWNLOAD_AUTH_FAILED | -5001 | Request for video information from the VOD console failed. Check whether the fileId and psign parameters are correct. |
DOWNLOAD_NO_FILE | -5003 | The file of the specified definition does not exist. |
DOWNLOAD_FORMAT_ERROR | -5004 | The downloaded file format is not supported. |
DOWNLOAD_DISCONNECT | -5005 | Network disconnected. Check whether the network is normal. |
DOWNLOAD_HLS_KEY_ERROR | -5006 | Failed to obtain the HLS decryption key. |
DOWNLOAD_PATH_ERROR | -5007 | Failed to access the download directory. Check whether you have the permission to access the download directory. |
DOWNLOAD_403FORBIDDEN | -5008 | Authentication information failed to pass when downloading. Check whether the signature (psign) has expired. |
TXVodDownloadMediaInfo
object. You can access the URL or dataSource
to determine the download source and get other information such as download progress and file size.downloader.stopDownload()
method to stop the download. The parameter is the object returned by downloader.startDownload()
. The SDK supports checkpoint restart. If the download directory is not changed, when you resume downloading a file, the download will start from the point where it stopped.// Get the download lists of all users// You can distinguish between the download lists of different users by `userName` in the download information// getDownloadMediaInfoList is a time-consuming function. Please do not call it in the main thread.List<TXVodDownloadMediaInfo> downloadInfoList = downloader.getDownloadMediaInfoList();if (downloadInfoList == null || downloadInfoList.size() <= 0) return;// Get the download list of the `default` userList<TXVodDownloadMediaInfo> defaultUserDownloadList = new ArrayList<>();for(TXVodDownloadMediaInfo downloadMediaInfo : downloadInfoList) {if ("default".equals(downloadMediaInfo.getUserName())) {defaultUserDownloadList.add(downloadMediaInfo);}}
Fileid
, such as the current download status and progress, you need to pass in AppID
, Fileid
, and qualityId
.// Get the download information of a `fileId`TXVodDownloadMediaInfo downloadInfo = downloader.getDownloadMediaInfo(1252463788, "4564972819220421305", QUALITYHD);// Get the total size of the file being downloaded in bytes. This API takes effect only for download through `fileid`.// Note: The total size refers to the size of the original file uploaded to the VOD console. Currently, the substream size after adaptive bitrate streaming cannot be obtained.int size = downloadInfo.getSize(); // Get the total size of the file being downloadedint duration = downloadInfo.getDuration(); // Get the total durationint playableDuration = downloadInfo.getPlayableDuration(); // Get the playable duration of the downloaded videofloat progress = downloadInfo.getProgress(); // Get the download progressString playPath = downloadInfo.getPlayPath(); // Get the offline playback path, which can be passed in to the player to start offline playback.int downloadState = downloadInfo.getDownloadState(); // Get the download status. For more information, see the `STATE_xxx` constant.boolean isDownloadFinished = downloadInfo.isDownloadFinished(); // If `true` is returned, the download is completed.
// Get the download information of a URLTXVodDownloadMediaInfo downloadInfo = downloader.getDownloadMediaInfo("http://1253131631.vod2.myqcloud.com/26f327f9vodgzp1253131631/f4bdff799031868222924043041/playlist.m3u8");
TXVodDownloadMediaInfo
parameter.// Delete the download informationboolean deleteRst = downloader.deleteDownloadMediaInfo(downloadInfo);
TXVodDownloadMediaInfo#getPlayPath
for playback.// `getDownloadMediaInfoList` is a time-consuming function. Please do not call it in the main thread.List<TXVodDownloadMediaInfo> mediaInfoList = TXVodDownloadManager.getInstance().getDownloadMediaInfoList();// Business logic finds the media object that needs to be played according to actual needsfor (TXVodDownloadMediaInfo mediaInfo : mediaInfoList) {if (mediaInfo.getDownloadState() == TXVodDownloadMediaInfo.STATE_FINISH) { // Check if the download is completemVodPlayer.startVodPlay(mediaInfo.getPlayPath()); // Play the downloaded video}}
appId
as well as the encrypted video's fileId
and psign
in the Tencent Cloud console, you can play back the video as follows:// `psign` is a player signature. For more information on the signature and how to generate it, see [Player Signature](https://www.tencentcloud.com/document/product/266/38099).TXPlayInfoParams playInfoParam = new TXPlayInfoParams(1252463788, // `appId` of the Tencent Cloud account"4564972819220421305", // `fileId` of the video"psignxxxxxxx"); // The player signaturemVodPlayer.startVodPlay(playInfoParam);
statPlay
, you can call setConfig
to configure the player parameters, such as player connection timeout period, progress callback interval, and maximum number of cached files. TXVodPlayConfig
allows you to configure detailed parameters. For more information, see Basic Configuration API. Below is the configuration sample code:TXVodPlayConfig config = new TXVodPlayConfig();config.setEnableAccurateSeek(true); // Set whether to enable accurate seek. Default value: trueconfig.setMaxCacheItems(5); // Set the maximum number of cached files to 5config.setProgressInterval(200); // Set the progress callback interval in msconfig.setMaxBufferSize(50); // Set the maximum preloading buffer size in MBmVodPlayer.setConfig(config); // Pass in `config` to `mVodPlayer`
setBitrateIndex
to switch to the required bitstream.TXVodPlayConfig config = new TXVodPlayConfig();// The parameter passed in is the product of the video width and height. You can pass in a custom value.config.setPreferredResolution(TXLiveConstants.VIDEO_RESOLUTION_720X1280);mVodPlayer.setConfig(config); // Pass in `config` to `mVodPlayer`
TXVodPlayConfig#setMediaType
to reduce the internal playback type detection of the player SDK.TXVodPlayConfig config = new TXVodPlayConfig();config.setMediaType(TXVodConstants.MEDIA_TYPE_FILE_VOD); // Used to improve MP4 playback startup speed// config.setMediaType(TXVodConstants.MEDIA_TYPE_HLS_VOD); // Used to improve HLS playback startup speedmVodPlayer.setConfig(config);
TXVodPlayConfig config = new TXVodPlayConfig();config.setProgressInterval(200); // Set the progress callback interval in msmVodPlayer.setConfig(config); // Pass in `config` to `mVodPlayer`
// Step 1: Turn on the HttpDNS resolution switchTXLiveBase.enableCustomHttpDNS(true);// Step 2: Set the HttpDNS resolution callbackTXLiveBase.setListener(new TXLiveBaseListener() {@Overridepublic void onCustomHttpDNS(String hostName, List<String> ipList) {// After resolving the hostName to an IP address, save it to the iPList and return it to the SDK internally. Note: Do not perform asynchronous operations here.// MSDKDnsResolver is the HTTPDNS SDK resolution interface provided by Tencent CloudString ips = MSDKDnsResolver.getInstance().getAddrByName(hostname);String[] ipArr = ips.split(";");if (0 != ipArr.length) {for (String ip : ipArr) {if ("0".equals(ip)) {continue;}ipList.add(ip);}}}});
// Set backup playback linkString backupPlayUrl = "${backupPlayUrl}"; // Alternative playback linkmVodPlayer.setStringOption(TXVodConstants.VOD_KEY_MIMETYPE, TXVodConstants.VOD_PLAY_MIMETYPE_H265); // Specify the original HEVC video encoding typemVodPlayer.setStringOption(TXVodConstants.VOD_KEY_BACKUP_URL, backupPlayUrl); // Set the backup playback link address for formats such as H.264// Set the original HEVC playback linkString hevcPlayUrl = "${hevcPlayUrl}";mVodPlayer.startVodPlay(hevcPlayUrl);
TXVodPlayer#setAudioNormalization
to set the volume normalization, with a loudness range of -70 to 0 (LUFS), and custom values are also supported.
Note: Supported from player version 11.7 of the premium version./**Can be set to preset values (related classes or files: Android: TXVodConstants; iOS: TXVodPlayConfig.h)Off: AUDIO_NORMALIZATION_OFFOn: AUDIO_NORMALIZATION_STANDARD (standard)AUDIO_NORMALIZATION_LOW (low)AUDIO_NORMALIZATION_HIGH (high)Custom values can be set: from low to high, range -70 to 0 LUFS*/mVodPlayer.setAudioNormalization(TXVodConstants.AUDIO_NORMALIZATION_STANDARD); // Enable volume normalizationmVodPlayer.setAudioNormalization(TXVodConstants.AUDIO_NORMALIZATION_OFF); // Disable volume normalization
TXVodPlayListener
listener to the TXVodPlayer
object to use onPlayEvent
(event notification) and onNetStatus
(status feedback) to sync information to your application.Event ID | Code | Description |
PLAY_EVT_PLAY_BEGIN | 2004 | Video playback started. |
PLAY_EVT_PLAY_PROGRESS | 2005 | The video playback progress (including the current playback progress, loading progress, and total video duration). |
PLAY_EVT_PLAY_LOADING | 2007 | The video is being loaded. The LOADING_END event will be reported if video playback resumes. |
PLAY_EVT_VOD_LOADING_END | 2014 | Video loading ended, and video playback resumed. |
TXVodConstants.VOD_PLAY_EVT_SEEK_COMPLETE | 2019 | Seeking was completed. The seeking feature is supported by v10.3 or later. |
VOD_PLAY_EVT_LOOP_ONCE_COMPLETE | 6001 | A round of loop was completed. The loop feature is supported by v10.8 or later. |
TXVodConstants.VOD_PLAY_EVT_HIT_CACHE | 2002 | Cache hit event during playback (supported by v11.2 or later). |
TXVodConstants.VOD_PLAY_EVT_VIDEO_SEI | 2030 | Received SEI frame event (supported from player version 11.6 of the premium version). |
VOD_PLAY_EVT_HEVC_DOWNGRADE_PLAYBACK | 2031 | HEVC downgrade playback occurs (supported by the player's advanced version 12.0). |
VOD_PLAY_EVT_FIRST_VIDEO_PACKET | 2017 | The player receives the first frame data packet event (supported by version 12.0). |
@Override public void onPlayEvent(TXVodPlayer player, int event, Bundle param) { if (event == TXVodConstants.VOD_PLAY_EVT_VIDEO_SEI) { int seiType = param.getInt(TXVodConstants.EVT_KEY_SEI_TYPE); // the type of video SEI int seiSize = param.getInt(TXVodConstants.EVT_KEY_SEI_SIZE); // the data size of video SEI byte[] seiData = param.getByteArray(TXVodConstants.EVT_KEY_SEI_DATA); // the byte array data of video SEI } }
Event ID | Code | Description |
PLAY_EVT_PLAY_END | 2006 | Video playback ended. |
PLAY_ERR_NET_DISCONNECT | -2301 | The network was disconnected and could not be reconnected after multiple retries. You can restart the player to perform more connection retries. |
PLAY_ERR_HLS_KEY | -2305 | Failed to get the HLS decryption key. |
Event ID | Code | Description |
PLAY_WARNING_VIDEO_DECODE_FAIL | 2101 | Failed to decode the current video frame. |
PLAY_WARNING_AUDIO_DECODE_FAIL | 2102 | Failed to decode the current audio frame. |
PLAY_WARNING_RECONNECT | 2103 | The network was disconnected, and automatic reconnection was performed (the PLAY_ERR_NET_DISCONNECT event will be thrown after three failed attempts). |
PLAY_WARNING_HW_ACCELERATION_FAIL | 2106 | Failed to start the hardware decoder, and the software decoder was used instead. |
Event ID | Code | Description |
PLAY_EVT_VOD_PLAY_PREPARED | 2013 | The player has been prepared and can start playback. If autoPlay is set to false , you need to call resume after receiving this event to start playback. |
PLAY_EVT_RCV_FIRST_I_FRAME | 2003 | The network received the first renderable video data packet (IDR). |
Event ID | Code | Description |
PLAY_EVT_CHANGE_RESOLUTION | 2009 | The video resolution changed. |
PLAY_EVT_CHANGE_ROTATION | 2011 | The MP4 video was rotated. |
Event ID | Code | Description |
TXLiveConstants.PLAY_EVT_GET_PLAYINFO_SUCC | 2010 | Obtained the information of the file played back successfully. |
fileId
and the playback request succeeds (called API::startVodPlay(TXPlayInfoParams playInfoParams)
), the SDK will notify the upper layer of some request information, and you can parse param
to get the video information after receiving the TXLiveConstants.PLAY_EVT_GET_PLAYINFO_SUCC
event.Video Information | Description |
EVT_PLAY_COVER_URL | Video thumbnail URL |
EVT_PLAY_URL | Video playback address |
EVT_PLAY_DURATION | Video duration |
EVT_DESCRIPTION | Event description |
EVT_PLAY_NAME | Video name |
TXVodConstants.EVT_IMAGESPRIT_WEBVTTURL | Download URL of the image sprite WebVTT file, which is supported by v10.2 or later |
TXVodConstants.EVT_IMAGESPRIT_IMAGEURL_LIST | The download URL of the image sprite image, which is supported by v10.2 or later. |
TXVodConstants.EVT_DRM_TYPE | The encryption type, which is supported by v10.2 or later. |
TXVodConstants.EVT_KEY_WATER_MARK_TEXT | Ghost watermark text content (supported from version 11.6). |
onPlayEvent
to get the video playback information:mVodPlayer.setVodListener(new ITXVodPlayListener() {@Overridepublic void onPlayEvent(TXVodPlayer player, int event, Bundle param) {if (event == TXLiveConstants.PLAY_EVT_VOD_PLAY_PREPARED) {// The player preparation completion event is received, and you can call the `pause`, `resume`, `getWidth`, and `getSupportedBitrates` APIs.} else if (event == TXLiveConstants.PLAY_EVT_PLAY_BEGIN) {// The playback start event is received} else if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {// The playback end event is received}}@Overridepublic void onNetStatus(TXVodPlayer player, Bundle bundle) {}});
Event ID | Value | Description |
PLAY_ERR_NET_DISCONNECT | -2301 | Video data error that cannot be recovered by retrying. For example, network anomaly or data download error that causes demultiplexing timeout or failure. |
PLAY_ERR_HLS_KEY | -2305 | Failed to obtain HLS decryption key. |
VOD_PLAY_ERR_SYSTEM_PLAY_FAIL | -6004 | System player playback error. |
VOD_PLAY_ERR_DECODE_VIDEO_FAIL | -6006 | Video decoding error, video format not supported. |
VOD_PLAY_ERR_DECODE_AUDIO_FAIL | -6007 | Audio decoding error, audio format not supported. |
VOD_PLAY_ERR_DECODE_SUBTITLE_FAIL | -6008 | Subtitle decoding error. |
VOD_PLAY_ERR_RENDER_FAIL | -6009 | Video rendering error. |
VOD_PLAY_ERR_PROCESS_VIDEO_FAIL | -6010 | Video post-processing error. |
VOD_PLAY_ERR_GET_PLAYINFO_FAIL | -2306 | Failed to obtain the on-demand file information. It is recommended to check whether the AppId, FileId or Psign is filled in correctly. |
Parameter | Description |
NET_STATUS_CPU_USAGE | Current instantaneous CPU utilization |
NET_STATUS_VIDEO_WIDTH | Video resolution - width |
NET_STATUS_VIDEO_HEIGHT | Video resolution - height |
NET_STATUS_NET_SPEED | Current network data reception speed in KBps |
NET_STATUS_VIDEO_FPS | Current video frame rate of streaming media |
NET_STATUS_VIDEO_BITRATE | Current video bitrate in bps of streaming media |
NET_STATUS_AUDIO_BITRATE | Current audio bitrate in bps of streaming media |
NET_STATUS_VIDEO_CACHE | Buffer (`jitterbuffer`) size. If the current buffer length is 0, lag will occur soon. |
NET_STATUS_SERVER_IP | Connected server IP |
mVodPlayer.setVodListener(new ITXVodPlayListener() {@Overridepublic void onPlayEvent(TXVodPlayer player, int event, Bundle param) {}@Overridepublic void onNetStatus(TXVodPlayer player, Bundle bundle) {// Get the current CPU utilizationCharSequence cpuUsage = bundle.getCharSequence(TXLiveConstants.NET_STATUS_CPU_USAGE);// Get the video widthint videoWidth = bundle.getInt(TXLiveConstants.NET_STATUS_VIDEO_WIDTH);// Get the video heightint videoHeight = bundle.getInt(TXLiveConstants.NET_STATUS_VIDEO_HEIGHT);// Get the real-time rate in Kbpsint speed = bundle.getInt(TXLiveConstants.NET_STATUS_NET_SPEED);// Get the current video frame rate of streaming mediaint fps = bundle.getInt(TXLiveConstants.NET_STATUS_VIDEO_FPS);// Get the current video bitrate in bps of streaming mediaint videoBitRate = bundle.getInt(TXLiveConstants.NET_STATUS_VIDEO_BITRATE);// Get the current audio bitrate in bps of streaming mediaint audioBitRate = bundle.getInt(TXLiveConstants.NET_STATUS_AUDIO_BITRATE);// Get the buffer (`jitterbuffer`) size. If the current buffer length is 0, lag will occur soon.int jitterbuffer = bundle.getInt(TXLiveConstants.NET_STATUS_VIDEO_CACHE);// Get the connected server IPString ip = bundle.getString(TXLiveConstants.NET_STATUS_SERVER_IP);}});
TXVodPlayConfig config = new TXVodPlayConfig();config.setMediaType(TXVodConstants.MEDIA_TYPE_HLS_LIVE); // Specify the HLS live media typemVodPlayer.setConfig(config);mVodPlayer.startVodPlay(${YOUR_HSL_LIVE_URL});
この記事はお役に立ちましたか?