TXVodPlayer
module of the Player SDK is used to implement the VOD feature.TXVodPlayer *_txVodPlayer = [[TXVodPlayer alloc] init];[_txVodPlayer setupVideoWidget:_myView insertIndex:0]
[_txVodPlayer setupVideoWidget:_myView insertIndex:0]
_myView
in the sample code) you provide. Instead, it creates a subview for OpenGL rendering over the view.transform
rather than frame
attribute of the view.[UIView animateWithDuration:0.5 animations:^{_myView.transform = CGAffineTransformMakeScale(0.3, 0.3); // Shrink by 1/3}];
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 startPlay
function.// Play back a video resource at a URLNSString* url = @"http://1252463788.vod2.myqcloud.com/xxxxx/v.f20.mp4";[_txVodPlayer startVodPlay:url];// Play back a local video resource in the sandbox// Get the `Documents` pathNSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];// Get the local video pathNSString *videoPath = [NSString stringWithFormat:@"%@/video1.m3u8",documentPath];[_txVodPlayer startVodPlay:videoPath];
TXPlayerAuthParams *p = [TXPlayerAuthParams new];p.appId = 1252463788;p.fileId = @"4564972819220421305";// `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).p.sign = @"psignxxxxx"; // The player signature[_txVodPlayer startVodPlayWithParams:p];
fileId
in the video details on the right.
Play back the video through the 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 PLAY_ERR_GET_PLAYINFO_FAIL
event will be received; otherwise, PLAY_EVT_GET_PLAYINFO_SUCC
will be received, indicating that the request succeeded.// Stop playback[_txVodPlayer stopPlay];[_txVodPlayer removeVideoWidget]; // Remember to terminate the view control
// Start playback[_txVodPlayer startVodPlay:url];
// Pause the video[_txVodPlayer pause];
// Resume the video[_txVodPlayer resume];
// Stop the video[_txVodPlayer stopPlay];
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// Adjust the playback progress[_txVodPlayer seek:time];
float time = 600; // float type, unit is seconds// Adjust progress[_txVodPlayer seek:time accurateSeek:YES]; // Accurate seek[_txVodPlayer seek:time accurateSeek:NO]; // Non-accurate seek
long long pdtTimeMs = 600; // Unit is milliseconds[_txVodPlayer seekToPdtTime:time];
startVodPlay
for the first time.float startTimeInSecond = 60; // Unit: Second[_txVodPlayer setStartTime:startTimeInSecond]; // Set the playback start time[_txVodPlayer startVodPlay:url];
view
of setupVideoWidget. The SDK will automatically adjust the size and position of the view based on your configuration.Value | Description |
RENDER_MODE_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 in whole. |
RENDER_MODE_FILL_EDGE | Images are scaled as large as the longer side can go. Neither side exceeds the screen after scaling. Images are centered, and there may be black bars. |
Value | Description |
HOME_ORIENTATION_RIGHT | The Home button is on the right of the video image |
HOME_ORIENTATION_DOWN | The Home button is below the video image |
HOME_ORIENTATION_LEFT | The Home button is on the left of the video image |
HOME_ORIENTATION_UP | The Home button is above the video image |
setRate
API to set the VOD playback speed, such as 0.5x, 1.0x, 1.2x, and 2x speed.// Set playback at 1.2X rate[_txVodPlayer setRate:1.2];// Start playback[_txVodPlayer startVodPlay:url];
// Set playback loop[_txVodPlayer setLoop:true];// Get the current playback loop status[_txVodPlayer loop];
// Mute or unmute the player. true: Mute; false: Unmute[_txVodPlayer setMute:true];
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.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 authentication.NSMutableDictionary<NSString *, NSString *> *httpHeader = [[NSMutableDictionary alloc] init];[httpHeader setObject:@"${Referer Content}" forKey:@"Referer"];[_config setHeaders:httpHeader];[_txVodPlayer setConfig:_config];
[_txVodPlayer stopPlay];_txVodPlayer.enableHWAcceleration = YES;[_txVodPlayer startVodPlay:_flvUrl type:_type];
NSArray *bitrates = [_txVodPlayer supportedBitrates]; // Get the array of multiple bitrates// TXBitrateItem class field meaning: index-bitrate subscript; width-video width; height-video height; birate-video bitrateTXBitrateItem *item = [bitrates objectAtIndex:i];[_txVodPlayer setBitrateIndex:item.index]; // Switch bit rate to desired definition// Get the bit rate subscript of the current playback, the return value -1000 is the default value, indicating that no bit rate subscript has been set; the return value -1 means that the adaptive bit stream is enabledint index = [_txVodPlayer bitrateIndex];
-[TXVodPlayer setBitrateIndex:]
at any time to switch the bitrate. During switch, the data of another stream will be pulled. The SDK is optimized for Tencent Cloud multi-bitrate files to implement smooth switch.[_txVodPlayer setBitrateIndex:-1]; // Pass in `-1` for the `index` parameter
-[TXVodPlayer setBitrateIndex:]
at any time to switch to another bitrate. After the switch, adaptive bitrate streaming will be disabled.TXVodPlayConfig *_config = [[TXVodPlayConfig alloc]init];// If it is set to `YES`, the bitrate can be switched smoothly when IDR frames are aligned. If it is set to `NO` (default), multi-bitrate URLs are opened faster.[_config setSmoothSwitchBitrate:YES];[_txVodPlayer setConfig:_config];
-(void) onPlayEvent:(TXVodPlayer *)player event:(int)EvtID withParam:(NSDictionary*)param {if (EvtID == PLAY_EVT_PLAY_PROGRESS) {// Loading progress in seconds. The decimal part is in ms.float playable = [param[EVT_PLAYABLE_DURATION] floatValue];[_loadProgressBar setValue:playable];// Playback progress in seconds. The decimal part is in ms.float progress = [param[EVT_PLAY_PROGRESS] floatValue];[_seekProgressBar setValue:progress];// Total video duration in seconds. The decimal part is in ms.float duration = [param[EVT_PLAY_DURATION] floatValue];// 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 long pdt_time_ms = [param[VOD_PLAY_EVENT_PLAY_PDT_TIME_MS] longLongValue];}}
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.VIDEO_WIDTH
and VIDEO_HEIGHT
of onNetStatus
to get the video width and height. For detailed directions, see Status feedback (onNetStatus).-[TXVodPlayer width]
and -[TXVodPlayer height]
to get the current video width and height.TXVodPlayConfig *_config = [[TXVodPlayConfig alloc]init];[_config setMaxBufferSize:10]; // Maximum buffer size during playback in MB[_txVodPlayer setConfig:_config]; // Pass in `config` to `_txVodPlayer`
// Set the global cache directory of the playback engineNSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectory = [paths objectAtIndex:0];NSString *preloadDataPath = [documentsDirectory stringByAppendingPathComponent:@"/preload"];if (![[NSFileManager defaultManager] fileExistsAtPath:preloadDataPath]) {[[NSFileManager defaultManager] createDirectoryAtPath:preloadDataPathwithIntermediateDirectories:NOattributes:nilerror:&error];[TXPlayerGlobalSetting setCacheFolderPath:preloadDataPath];// Set the playback engine cache size[TXPlayerGlobalSetting setMaxCacheSize:200];// Start playback[_txVodPlayer startVodPlay:url];
TXVodPlayConfig#setMaxCacheItems
API used for configuration on earlier versions has been deprecated and is not recommended.(1)Bright screen (no screen off)// start playing(startVodPlay / startPlayDrm / startVodPlayWithParams)// resume playback(resume)[[UIApplication sharedApplication] setIdleTimerDisabled:YES];(2)Off screen (restore off screen)// stop(stopPlay)// pause(pause)[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
TXPlayerAuthParams *p = [TXPlayerAuthParams new];p.appId = ${appId}; // appId of the Tencent Cloud accountp.fileId = @"${fieId}"; // fileId of DRM encrypted video// psign is the signature of the player. Please refer to the link for signature introduction and generation method:https://www.tencentcloud.com/document/product/266/38099?lang=en&pg=p.sign = @"${psgin}"; // Player signature for encrypted video[_txVodPlayer startVodPlayWithParams:p];
// Play through the TXVodPlayer#startPlayDrm interface// @param certificateUrl certificate provider url// @param licenseUrl decrypted key url// @param videoUrl Url address of the video to be playedTXPlayerDrmBuilder *builder = [[TXPlayerDrmBuilder alloc] initWithDeviceCertificateUrl:@"${certificateUrl}"licenseUrl:@"${licenseUrl}" videoUrl:@"${videoUrl}"];[_txVodPlayer startPlayDrm:builder];
// Pass in subtitle url, subtitle name, subtitle type. It is recommended to add subtitles before starting the playback.[_txVodPlayer addSubtitleSource:@"https://mediacloud-76607.gzc.vod.tencent-cloud.com/DemoResource/subtitleVTT.vtt" name:@"subtitleName"mimeType:TX_VOD_PLAYER_MIMETYPE_TEXT_VTT];
// After starting to play the video, select the added external subtitles. Please call it after receiving the VOD_PLAY_EVT_SELECT_TRACK_COMPLETE event.NSArray<TXTrackInfo *> *subtitlesArray = [_txVodPlayer getSubtitleTrackInfo];for (int i = 0; i < subtitlesArray.count; i++) {TXTrackInfo *info = subtitlesArray[i];if (info.trackIndex == 0) {[_txVodPlayer selectTrack:info.trackIndex]; // check subtitles} else {// If other subtitles are not needed, perform deselectTrack[_txVodPlayer deselectTrack:info.trackIndex];}}// Listen for track switch messages- (void)onPlayEvent:(TXVodPlayer *)player event:(int)EvtID withParam:(NSDictionary *)param {if (EvtID == VOD_PLAY_EVT_SELECT_TRACK_COMPLETE) {int trackIndex = [(NSNumber *)[param valueForKey:EVT_KEY_SELECT_TRACK_INDEX] intValue];int errorCode = [(NSNumber *)[param valueForKey:EVT_KEY_SELECT_TRACK_ERROR_CODE] intValue];NSLog(@"receive VOD_PLAY_EVT_SELECT_TRACK_COMPLETE, trackIndex=%d , errorCode=%d", trackIndex,errorCode);}}
// For detailed parameter configuration, please refer to the API documentationTXPlayerSubtitleRenderModel *model = [[TXPlayerSubtitleRenderModel alloc] init];model.canvasWidth = 1920; // The width of the subtitle rendering canvasmodel.canvasHeight = 1080; // The height of the subtitle rendering canvasmodel.isBondFontStyle = NO; // Set whether the subtitle font is boldmodel.fontColor = 0xFF000000; // Set the subtitle font color, the default is white and opaque[_txVodPlayer setSubtitleStyle:model];
NSArray<TXTrackInfo *> *soundTrackArray = [_txVodPlayer getAudioTrackInfo];for (int i = 0; i < soundTrackArray.count; i++) {TXTrackInfo *info = soundTrackArray[i];if (info.trackIndex == 0) {// Switch to the desired audio track by determining the trackIndex or name.[_txVodPlayer selectTrack:info.trackIndex];} else {// If other subtitles are not required, proceed with deselectTrack.[_txVodPlayer deselectTrack:info.trackIndex];}}
isAutoPlay
in TXVodPlayer
to implement the feature as follows:
// Play back video A: If `isAutoPlay` is set to `YES`, the video will be immediately loaded and played back when `startVodPlay` is calledNSString* url_A = @"http://1252463788.vod2.myqcloud.com/xxxxx/v.f10.mp4";_player_A.isAutoPlay = YES;[_player_A startVodPlay:url_A];// To preload video B when playing back video A, set `isAutoPlay` to `NO`NSString* url_B = @"http://1252463788.vod2.myqcloud.com/xxxxx/v.f20.mp4";_player_B.isAutoPlay = NO;[_player_B startVodPlay:url_B];
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.-(void) onPlayEvent:(TXVodPlayer *)player event:(int)EvtID withParam:(NSDictionary*)param{// When video A ends, directly start playing back video B for seamless switchif (EvtID == PLAY_EVT_PLAY_END) {[_player_A stopPlay];[_player_B setupVideoWidget:mVideoContainer insertIndex:0];[_player_B resume];}}
AutoPlay
of the player is set to false
before video playback starts).TXVodPlayConfig *_config = [[TXVodPlayConfig alloc]init];[_config setMaxPreloadSize:(2)];; // Maximum preloading buffer size in MB. Set it based on your business conditions to reduce the traffic consumption[_txVodPlayer setConfig:_config]; // Pass in `config` to `_txVodPlayer`
TXVodPlayConfig *_config = [[TXVodPlayConfig alloc]init];[_config setMaxBufferSize:10]; // Maximum buffer size during playback in MB[_txVodPlayer setConfig:_config]; // Pass in `config` to `_txVodPlayer`
TXPlayerGlobalSetting
is the global cache setting API, and the original TXVodConfig
API has been deprecated.TXVodConfig
of the player.// Set the global cache directory of the playback engineNSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectory = [paths objectAtIndex:0];NSString *preloadDataPath = [documentsDirectory stringByAppendingPathComponent:@"/preload"];if (![[NSFileManager defaultManager] fileExistsAtPath:preloadDataPath]) {[[NSFileManager defaultManager] createDirectoryAtPath:preloadDataPathwithIntermediateDirectories:NOattributes:nilerror:&error]; //Create folder}[TXPlayerGlobalSetting setCacheFolderPath:preloadDataPath];// Set the playback engine cache size[TXPlayerGlobalSetting setMaxCacheSize:200];NSString *m3u8url = "http://****";int taskID = [[TXVodPreloadManager sharedManager] startPreload:m3u8urlpreloadSize:10preferredResolution:1920*1080delegate:self];// Cancel predownloading[[TXVodPreloadManager sharedManager] stopPreload:taskID];
//Set the global cache directory of the playback engineNSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectory = [paths objectAtIndex:0];NSString *preloadDataPath = [documentsDirectory stringByAppendingPathComponent:@"/preload"];if (![[NSFileManager defaultManager] fileExistsAtPath:preloadDataPath]) {[[NSFileManager defaultManager] createDirectoryAtPath:preloadDataPathwithIntermediateDirectories:NOattributes:nilerror:&error]; //Create folder}[TXPlayerGlobalSetting setCacheFolderPath:preloadDataPath];//Set playback engine cache size[TXPlayerGlobalSetting setMaxCacheSize:200];TXPlayerAuthParams *params = [[TXPlayerAuthParams alloc] init];params.appId = ${appId};params.fileId = @"${fileId}";params.sign = @"${psign}";// Note: Time-consuming operation, please do not call it in the main thread! Calling on the main thread will throw an illegal call exception.int taskID = [[TXVodPreloadManager sharedManager] startPreload:paramspreloadSize:10preferredResolution:1920*1080delegate:self]; // TXVodPreloadManagerDelegate// Set the playback engine cache size[[TXVodPreloadManager sharedManager] stopPreload:taskID];
TXVodDownloadManager
to implement offline HLS playback.TXVodDownloadManager
can cache only HLS files but not MP4 and FLV files.NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];NSString downloadPath = [NSString stringWithFormat:@"%@/txdownload",cachesDir];[TXPlayerGlobalSetting setCacheFolderPath:downloadPath];
TXVodDownloadManager
is designed as a singleton; therefore, you cannot create multiple download objects. It is used as follows:TXVodDownloadManager *downloader = [TXVodDownloadManager shareInstance];
fileid
or URL.appId
and fileId
at least for download through fileid
. If you don't specify a value for userName
, default
will be used by default. Note: You can download encrypted videos only through Fileid
and must enter the psign
parameter.TXVodDownloadDataSource *source = [[TXVodDownloadDataSource alloc] init];source.appId = 1252463788;source.fileId = @"4564972819220421305";// // `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).source.pSign = @"xxxxxxxxxx";// Specify the download definition// Valid values: `TXVodQualityOD` (original), `TXVodQualityFLU` (LD), `TXVodQualitySD` (SD), `TXVodQualityHD` (HD), `TXVodQualityFHD` (FHD), `TXVodQuality2K` (2K), `TXVodQuality4K` (4K).source.quality = TXVodQualityHD; // HD// **Note that if you use the legacy v2 protocol for download, set the `appId` and `fileId` parameters through the `auth` attribute in `TXVodDownloadDataSource`.**// source.auth = auth; **There is no need to set it by default.**[downloader startDownload:dataSource];
fileid
in case of private encryption.[downloader startDownloadUrl:@"http://1253131631.vod2.myqcloud.com/26f327f9vodgzp1253131631/f4bdff799031868222924043041/playlist.m3u8"]
downloader.delegate = self;
Callback Message | Description |
-[TXVodDownloadDelegate onDownloadStart:] | The task started, that is, the SDK started the download. |
-[TXVodDownloadDelegate onDownloadProgress:] | Task progress. During download, the SDK will frequently call back this API. You can update the displayed progress here. |
-[TXVodDownloadDelegate onDownloadStop:] | The task stopped. When you call stopDownload to stop the download, if this message is received, the download is stopped successfully. |
-[TXVodDownloadDelegate onDownloadFinish:] | Download was completed. If this callback is received, the entire file has been downloaded, and the downloaded file can be played back by `TXVodPlayer`. |
-[TXVodDownloadDelegate onDownloadError:errorMsg:] | A download error occurred. If the network is disconnected during download, this API will be called back and the download task will stop. For all error codes, see TXDownloadError. |
error code | value | Meaning |
TXDownloadSuccess | 0 | Download successful |
TXDownloadAuthFaild | -5001 | Failed to request video information from the cloud on-demand console, it is recommended to check whether the fileId and psign parameters are correct |
TXDownloadNoFile | -5003 | No file for this resolution |
TXDownloadFormatError | -5004 | The download file format is not supported |
TXDownloadDisconnet | -5005 | The network is disconnected, it is recommended to check whether the network is normal |
TXDownloadHlsKeyError | -5006 | Failed to get HLS decryption key |
TXDownloadPathError | -5007 | Download directory access failed, it is recommended to check whether you have permission to access the download directory |
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.-[TXVodDownloadManager stopDownload:]
method to stop the download. The parameter is the object returned by -[TXVodDownloadManager sartDownloadUrl:]
. 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.// s a time-consuming function. Please do not call it in the main threadNSArray<TXVodDownloadMediaInfo *> *array = [[[TXVodDownloadManager shareInstance] getDownloadMediaInfoList] mutableCopy];// Get the download list of the `default` userfor (TXVodDownloadMediaInfo *info in array) {if ([info.userName isEqualToString:@"default"]) {// Save the download list of the `default` user}}
FileId
or URL:Fileid
through the -[TXVodDownloadManager getDownloadMediaInfo:]
API, 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 *sourceMediaInfo = [[TXVodDownloadMediaInfo alloc] init];TXVodDownloadDataSource *dataSource = [[TXVodDownloadDataSource alloc] init];dataSource.appId = 1252463788;dataSource.fileId = @"4564972819220421305";dataSource.pSign = @"psignxxxx";dataSource.quality = TXVodQualityHD;sourceMediaInfo.dataSource = dataSource;TXVodDownloadMediaInfo *downlaodMediaInfo = [[TXVodDownloadManager shareInstance] getDownloadMediaInfo:sourceMediaInfo];// 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.downlaodMediaInfo.size; // Get the total size of the file being downloadeddownlaodMediaInfo.duration; // Get the total durationdownlaodMediaInfo.playableDuration; // Get the playable duration of the downloaded videodownlaodMediaInfo.progress; // Get the download progressdownlaodMediaInfo.playPath; // Get the offline playback path, which can be passed in to the player to start offline playback.downlaodMediaInfo.downloadState; // Get the download status. For more information, see the `STATE_xxx` constant.[downlaodMediaInfo isDownloadFinished]; // If `YES` is returned, the download is completed.
// Get the download information of a `fileId`TXVodDownloadMediaInfo *sourceMediaInfo = [[TXVodDownloadMediaInfo alloc] init];mediaInfo.url = @"videoURL";TXVodDownloadMediaInfo *downlaodMediaInfo = [[TXVodDownloadManager shareInstance] getDownloadMediaInfo:sourceMediaInfo];
-[TXVodDownloadManager deleteDownloadFile:]
method to delete the file to release the storage space.NSArray<TXVodDownloadMediaInfo *> *mediaInfoList = [[TXVodDownloadManager shareInstance]getDownloadMediaInfoList];TXVodDownloadMediaInfo *mediaInfo = [mediaInfoList firstObject]; // Find the current media object according to the situationif (mediaInfo.downloadState == TXVodDownloadMediaInfoStateFinish) { // Determine whether the download is complete[self.player startVodPlay:mediaInfo.playPath];}
appId
as well as the encrypted video's fileId
and psign
in the Tencent Cloud console, you can play back the video as follows:TXPlayerAuthParams *p = [TXPlayerAuthParams new];p.appId = 1252463788; // The `appId` of the Tencent Cloud accountp.fileId = @"4564972819220421305"; // The video's `fileId`// `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).p.sign = @"psignxxxxx"; // The player signature[_txVodPlayer startVodPlayWithParams:p];
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 TXVodPlayConfig. Below is the configuration sample code:TXVodPlayConfig *_config = [[TXVodPlayConfig alloc]init];[_config setEnableAccurateSeek:true]; // Set whether to enable accurate seek. Default value: true[_config setMaxCacheItems:5]; // Set the maximum number of cached files to 5[_config setProgressInterval:200]; // Set the progress callback interval in ms[_config setMaxBufferSize:50]; // Set the maximum preloading buffer size in MB[_txVodPlayer setConfig:_config]; // Pass in `config` to `_txVodPlayer`
setBitrateIndex
to switch to the required bitstream.TXVodPlayConfig *_config = [[TXVodPlayConfig alloc]init];// The parameter passed in is the product of the video width and height. You can pass in a custom value.[_config setPreferredResolution:720*1280];[_txVodPlayer setConfig:_config]; // Pass in `config` to `_txVodPlayer`
TXVodPlayConfig *_config = [[TXVodPlayConfig alloc]init];[_config setMediaType:MEDIA_TYPE_FILE_VOD]; // Used to increase the speed of MP4 playback// [_config setMediaType:MEDIA_TYPE_HLS_VOD]; // Used to increase the speed of HLS playback[_txVodPlayer setConfig:_config];
TXVodPlayConfig *_config = [[TXVodPlayConfig alloc]init];[_config setProgressInterval:200]; // Set the progress callback interval in ms[_txVodPlayer setConfig:_config]; // Pass in `config` to `_txVodPlayer`
// Step 1: Turn on the HttpDNS resolution switch.[TXLiveBase enableCustomHttpDNS:YES];// Step 2: Implement HttpDNS resolution proxy: TXLiveBaseDelegate#onCustomHttpDNS.- (void)onCustomHttpDNS:(NSString *)hostName ipList:(NSMutableArray<NSString *> *)list {// After resolving the hostName to an IP address, save it to the iPList and return it to the internal SDK. Note: do not perform time-consuming asynchronous operations here.// MSDKDnsResolver is the HTTPDNS SDK resolution interface provided by Tencent Cloud.NSArray *result = [[MSDKDns sharedInstance] WGGetHostByName:hostName];NSString *ip = nil;if (result && result.count > 1) {if (![result[1] isEqualToString:@"0"]) {ip = result[1];} else {ip = result[0];}}[list addObject:ip];}// Step 3: Set the HttpDNS resolution proxy.[TXLiveBase sharedInstance].delegate = self;
#import <CoreMedia/CoreMedia.h> //Import header fileNSDictionary *dic = @{VOD_KEY_VIDEO_CODEC_TYPE:@(kCMVideoCodecType_HEVC), // Specify the original HEVC video encoding typeVOD_KEY_BACKUP_URL:@"${backupPlayUrl}"}; // Set the backup playback link address for formats such as H.264[_txVodPlayer setExtentOptionInfo:dic];// Set the original HEVC playback link[_txVodPlayer 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*/[_txVodPlayer setAudioNormalization:AUDIO_NORMALIZATION_STANDARD]; // Enable volume normalization[_txVodPlayer setAudioNormalization: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 | Video playback progress. The current playback progress, loading progress, and total video duration will be notified of. |
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. |
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. |
VOD_PLAY_EVT_HIT_CACHE | 2002 | Cache hit event at startup (supported since version 11.2). |
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_VOD_PLAY_FIRST_VIDEO_PACKET | 2017 | The player receives the first frame data packet event (supported by version 12.0). |
-(void) onPlayEvent:(TXVodPlayer *)player event:(int)EvtID withParam:(NSDictionary*)param { if (EvtID == VOD_PLAY_EVT_VIDEO_SEI) { int seiType = [param objectForKey:EVT_KEY_SEI_TYPE]; // the type of video SEI int seiSize = [param objectForKey:EVT_KEY_SEI_SIZE]; // the data size of video SEI NSData *seiData = [param objectForKey:EVT_KEY_SEI_DATA]; // the byte array data of video SEI } }
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_ROATION | 2011 | The MP4 video was rotated. |
Event ID | Code | Description |
PLAY_EVT_GET_PLAYINFO_SUCC | 2010 | Obtained the information of the file played back successfully. |
fileId
and the playback request succeeds, the SDK will notify the upper layer of some request information, and you can parse param
to get the video information after receiving the PLAY_EVT_GET_PLAYINFO_SUCC
event.Video Information | Description |
EVT_PLAY_COVER_URL | Video thumbnail URL |
EVT_PLAY_URL | Video playback URL |
EVT_PLAY_DURATION | Video duration |
EVT_KEY_WATER_MARK_TEXT | Ghost watermark text content (supported from version 11.6). |
-(void) onPlayEvent:(TXVodPlayer *)player event:(int)EvtID withParam:(NSDictionary*)param{if (EvtID == 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 (EvtID == PLAY_EVT_PLAY_BEGIN) {// The playback start event is received} else if (EvtID == PLAY_EVT_PLAY_END) {// The playback end event is received}}
Event ID | Value | Meaning |
PLAY_ERR_NET_DISCONNECT | -2301 | Video data errors that cannot be recovered by retrying the playback. For example, network anomalies or download data errors that cause demuxing timeouts or failures. |
PLAY_ERR_HLS_KEY | -2305 | HLS decryption key retrieval failure. |
VOD_PLAY_ERR_SYSTEM_PLAY_FAIL | -6004 | System player playback error. |
VOD_PLAY_ERR_DECODE_VIDEO_FAIL | -6006 | Video decoding error or unsupported video format. |
VOD_PLAY_ERR_DECODE_AUDIO_FAIL | -6007 | Audio decoding error or unsupported audio format. |
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 |
CPU_USAGE | Current instantaneous CPU utilization |
VIDEO_WIDTH | Video resolution - width |
VIDEO_HEIGHT | Video resolution - height |
NET_SPEED | Current network data reception speed in KBps |
VIDEO_FPS | Current video frame rate of streaming media |
VIDEO_BITRATE | Current video bitrate in bps of streaming media |
AUDIO_BITRATE | Current audio bitrate in bps of streaming media |
V_SUM_CACHE_SIZE | Buffer (`jitterbuffer`) size. If the current buffer length is 0, lag will occur soon. |
SERVER_IP | Connected server IP |
- (void)onNetStatus:(TXVodPlayer *)player withParam:(NSDictionary *)param {// Get the current CPU utilizationfloat cpuUsage = [[param objectForKey:@"CPU_USAGE"] floatValue];// Get the video widthint videoWidth = [[param objectForKey:@"VIDEO_WIDTH"] intValue];// Get the video heightint videoHeight = [[param objectForKey:@"VIDEO_HEIGHT"] intValue];// Get the real-time speedint speed = [[param objectForKey:@"NET_SPEED"] intValue];// Get the current video frame rate of streaming mediaint fps = [[param objectForKey:@"VIDEO_FPS"] intValue];// Get the current video bitrate in Kbps of streaming mediaint videoBitRate = [[param objectForKey:@"VIDEO_BITRATE"] intValue];// Get the current audio bitrate in Kbps of streaming mediaint audioBitRate = [[param objectForKey:@"AUDIO_BITRATE"] intValue];// Get the buffer (`jitterbuffer`) size. If the current buffer length is 0, lag will occur soon.int jitterbuffer = [[param objectForKey:@"V_SUM_CACHE_SIZE"] intValue];// Get the connected server IPNSString *ip = [param objectForKey:@"SERVER_IP"];}
TXVodPlayConfig *_config = [[TXVodPlayConfig alloc]init];[_config setMediaType:MEDIA_TYPE_HLS_LIVE]; // Specify the HLS live media type[_txVodPlayer setConfig:_config];[_txVodPlayer startVodPlay:${YOUR_HSL_LIVE_URL}];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers error:nil];[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];[[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
Was this page helpful?