tencent cloud


VOD Scenario

Last updated: 2024-06-07 17:07:54


    1. Activate VOD. If you don’t have an account yet, sign up for one first.
    2. Download and install Xcode from App Store.
    3. Download and install CocoaPods as instructed at the CocoaPods website.

    This Document Describes

    How to integrate the Tencent Cloud Player SDK for iOS.
    How to use the Player SDK for VOD playback.
    How to use the underlying capabilities of the Player SDK to implement more features.

    SDK Integration

    Step 1. Integrate the SDK ZIP file

    Download and integrate the SDK ZIP file as instructed in Integration Guide.

    Step 2. Configure the license

    If you have obtained a license, you can view the license URL and key in the VOD console.
    If you don't have the required license yet, you can get it as instructed in Adding and Renewing a License.
    After obtaining the License information, you need to initialize and configure the License before calling the relevant interfaces of the SDK. For detailed tutorials, please see Configuring View License.

    Step 3. Create a player object

    The TXVodPlayer module of the Player SDK is used to implement the VOD feature.
    TXVodPlayer *_txVodPlayer = [[TXVodPlayer alloc] init];
    [_txVodPlayer setupVideoWidget:_myView insertIndex:0]

    Step 4. Create a rendering view

    In iOS, a view is used as the basic UI rendering unit. Therefore, you need to configure a view, whose size and position you can adjust, for the player to display video images on.
    [_txVodPlayer setupVideoWidget:_myView insertIndex:0]
    Technically, the player does not render video images directly on the view (_myView in the sample code) you provide. Instead, it creates a subview for OpenGL rendering over the view.
    You can adjust the size of video images by changing the size and position of the view. The SDK will make changes to the video images accordingly.
    How to make an animation You are allowed great flexibility in view animation, but note that you need to modify the transform rather than frame attribute of the view.
    [UIView animateWithDuration:0.5 animations:^{
    _myView.transform = CGAffineTransformMakeScale(0.3, 0.3); // Shrink by 1/3

    Step 5. Start playback

    TXVodPlayer supports two playback modes for you to choose as needed:
    Through URL
    Through `fileId`
    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 URL
    NSString* 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` path
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    // Get the local video path
    NSString *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];
    You can go to Media Assets and find it. After clicking it, you can view its 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.

    Step 6. Stop playback

    Remember to use removeVideoWidget to terminate the view control before exiting the current UI when stopping playback. This can prevent memory leak and screen flashing issues.
    // Stop playback
    [_txVodPlayer stopPlay];
    [_txVodPlayer removeVideoWidget]; // Remember to terminate the view control

    Basic Feature Usage

    1. Playback control

    Starting playback

    // Start playback
    [_txVodPlayer startVodPlay:url];

    Pausing playback

    // Pause the video
    [_txVodPlayer pause];

    Resuming playback

    // Resume the video
    [_txVodPlayer resume];

    Stopping playback

    // Stop the video
    [_txVodPlayer stopPlay];

    Seek to the specified Program Date Time (PDT) point in the video stream

    To seek to the specified Program Date Time (PDT) point in the video stream, which enables functions such as fast-forward, rewind, and progress bar jumping, currently only HLS video format is supported.
    Note: Starting from version 11.6 of the player's advanced edition, this function is supported.
    long long pdtTimeMs = 600; // Unit is milliseconds
    [_txVodPlayer seekToPdtTime:time];

    Adjusting playback progress (seek)

    When the user drags the progress bar, 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];

    Precise and Imprecise Seek

    Starting from version 11.8 of the player SDK, it is supported to specify precise or imprecise seek when calling the seek interface.
    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

    Specifying playback start time

    You can specify the playback start time before calling startVodPlay for the first time.
    float startTimeInSecond = 60; // Unit: Second
    [_txVodPlayer setStartTime:startTimeInSecond]; // Set the playback start time
    [_txVodPlayer startVodPlay:url];

    2. Image adjustment

    view: size and position You can modify the size and position of the view by adjusting the size and position of the parameter view of setupVideoWidget. The SDK will automatically adjust the size and position of the view based on your configuration.
    setRenderMode: Aspect fill or aspect fit
    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.
    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.
    setRenderRotation: Image rotation
    The Home button is on the right of the video image
    The Home button is below the video image
    The Home button is on the left of the video image
    The Home button is above the video image

    3. Adjustable-Speed playback

    The VOD player supports adjustable-speed playback. You can use the 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];

    4. Playback loop

    // Set playback loop
    [_txVodPlayer setLoop:true];
    // Get the current playback loop status
    [_txVodPlayer loop];

    5. Muting/Unmuting

    // Mute or unmute the player. true: Mute; false: Unmute
    [_txVodPlayer setMute:true];

    6. Screencapturing

    Call snapshot to take a screenshot of the current video frame. This method captures only the video frame. To capture the UI, use the corresponding API of the iOS system.

    7. Roll image ad

    The Player SDK allows you to add roll images on the UI for advertising as follows:
    If autoPlay is set to NO, the player will load the video normally but will not immediately start playing it back.
    Users can see the roll image ad on the player UI after the player is loaded and before the video playback starts.
    When the ad display stop conditions are met, the resume API will be called to start video playback.

    8. HTTP-REF

    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];

    9. Hardware acceleration

    It is extremely difficult to play back videos of the Blu-ray (1080p) or higher image quality smoothly if only software decoding is used. Therefore, if your main scenario is game live streaming, we recommend you use hardware acceleration.
    Before switching between software and hardware decoding, you need to call stopPlay first. After the switch, you need to call startVodPlay; otherwise, severe blurs will occur.
    [_txVodPlayer stopPlay];
    _txVodPlayer.enableHWAcceleration = YES;
    [_txVodPlayer startVodPlay:_flvUrl type:_type];

    10. Definition settings

    The SDK supports the multi-bitrate format of HLS, so users can switch between streams at different bitrates. You can get the array of multiple bitrates as follows:
    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 bitrate
    TXBitrateItem *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 enabled 
    int index = [_txVodPlayer bitrateIndex];
    During playback, you can call -[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.
    If you know the resolution information of the video stream in advance, you can specify the resolution of the video to be played before starting the broadcast, so as to avoid switching the stream after playback. For detailed methods, refer to Player configuration#Specify resolution before starting broadcast.

    11. Adaptive bitrate streaming

    The SDK supports adaptive bitrate streaming of HLS. After this capability is enabled, the player can dynamically select the most appropriate bitrate for playback based on the current bandwidth. You can enable adaptive bitrate streaming as follows:
    [_txVodPlayer setBitrateIndex:-1]; // Pass in `-1` for the `index` parameter
    During playback, you can call -[TXVodPlayer setBitrateIndex:] at any time to switch to another bitrate. After the switch, adaptive bitrate streaming will be disabled.

    12. Enabling smooth bitrate switch

    Before starting playback, you can enable smooth bitrate switch to seamlessly switch between different definitions (bitrates) during playback. If smooth bitrate switch is enabled, the transition between different bitrates will be smoother but will be more time-consuming. Therefore, this feature can be configured as needed.
    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];

    13. Playback progress listening

    There are two metrics for the VOD progress: loading progress and playback progress. Currently, the SDK notifies the two progress metrics in real time through event notifications. For more information on the event notification content, see Event Listening.
    -(void) onPlayEvent:(TXVodPlayer *)player event:(int)EvtID withParam:(NSDictionary*)param {
    // 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];

    14. Playback network speed listening

    You can display the current network speed when the video is lagging by listening on events.
    You can use the NET_SPEED of onNetStatus to get the current network speed. For detailed directions, see Playback status feedback (onNetStatus).
    After the PLAY_EVT_PLAY_LOADING event is detected, the current network speed will be displayed.
    After the PLAY_EVT_VOD_LOADING_END event is received, the view showing the current network speed will be hidden.

    15. Video resolution acquisition

    The Player SDK plays back a video through a URL string. The URL doesn't contain the video information, and you need to access the cloud server to load such information. Therefore, the SDK can only send the video information to your application as event notifications. For more information, see Event Listening.
    Resolution information
    Method 1
    Method 2
    Use the VIDEO_WIDTH and VIDEO_HEIGHT of onNetStatus to get the video width and height. For detailed directions, see Status feedback (onNetStatus).
    Directly call -[TXVodPlayer width] and -[TXVodPlayer height] to get the current video width and height.

    16. Player buffer size

    During normal video playback, you can control the maximum size of the data buffered from the network in advance. If the maximum buffer size is not configured, the player will use the default buffer policy to guarantee a smooth playback experience.
    TXVodPlayConfig *_config = [[TXVodPlayConfig alloc]init];
    [_config setMaxBufferSize:10]; // Maximum buffer size during playback in MB
    [_txVodPlayer setConfig:_config]; // Pass in `config` to `_txVodPlayer`

    17. Local video cache

    In short video playback scenarios, the local video file cache is required, so that general users don't need to consume traffic again to reload an already watched video.
    Supported format: The SDK supports caching videos in two common VOD formats: HLS (M3U8) and MP4.
    Enablement time: The SDK doesn't enable the caching feature by default. We recommend you do not enable it for scenarios in which most videos are watched only once.
    Enablement method: To enable it, you need to configure two parameters: local cache directory and cache size.
    // Set the global cache directory of the playback engine
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *preloadDataPath = [documentsDirectory stringByAppendingPathComponent:@"/preload"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:preloadDataPath]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:preloadDataPath
    [TXPlayerGlobalSetting setCacheFolderPath:preloadDataPath];
    // Set the playback engine cache size
    [TXPlayerGlobalSetting setMaxCacheSize:200];
    // Start playback
    [_txVodPlayer startVodPlay:url];
    The TXVodPlayConfig#setMaxCacheItems API used for configuration on earlier versions has been deprecated and is not recommended.

    18.Screen control (screen on and off)

    Due to the frequent personalized settings in mobile phones, the screen lock time is often set, which may cause the screen to turn off (or be locked) during video playback, greatly affecting the user experience. Therefore, to solve this problem, the following code needs to be added at relevant times during the playback process to keep the screen always on.
    (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];
    Please pay attention to calling the above interfaces in the main thread.

    19.DRM encrypted video playback

    This feature requires the premium version of the player to be supported.
    The advanced version of the player SDK supports playback of commercial-grade DRM-encrypted videos, and currently supports two DRM schemes, WideVine and Fairplay. For more commercial-grade DRM information, please refer to the product introduction.
    DRM-encrypted videos can be played in the following 2 ways:
    Play by FiledId
    Custom configuration play
    TXPlayerAuthParams *p = [TXPlayerAuthParams new];
    p.appId = ${appId}; // appId of the Tencent Cloud account
    p.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];
    Playing via FileId is suitable for accessing the cloud on-demand background. This method is no different from playing ordinary FileId files. You need to configure the resource as a DRM type in Cloud VOD, and the SDK will recognize and process it internally.
    // 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 played
    TXPlayerDrmBuilder *builder = [[TXPlayerDrmBuilder alloc] initWithDeviceCertificateUrl:@"${certificateUrl}"licenseUrl:@"${licenseUrl}" videoUrl:@"${videoUrl}"];
    [_txVodPlayer startPlayDrm:builder];

    20.External subtitles

    This feature requires the premium version of the player to be supported.
    The advanced version of the player SDK supports adding and switching external subtitles, and now supports subtitles in two formats: SRT and VTT.
    Best practice: It is recommended to add subtitles and configure subtitle styles before calling startVodPlay. After receiving the PLAY_EVT_VOD_PLAY_PREPARED event, call selectTrack to choose the subtitle. Adding subtitles does not automatically load them. After calling selectTrack, the subtitles will be loaded. The successful selection of subtitles will trigger the VOD_PLAY_EVT_SELECT_TRACK_COMPLETE event callback.
    The usage is as follows:

    Step 1: Add external subtitles

    // 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];

    Step 2: Switch subtitles after playback.

    // 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 {
    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);

    Step 3: Configure subtitle style.

    The subtitle style supports configuration before or during playback.
    // For detailed parameter configuration, please refer to the API documentation
    TXPlayerSubtitleRenderModel *model = [[TXPlayerSubtitleRenderModel alloc] init];
    model.canvasWidth = 1920;  // The width of the subtitle rendering canvas
    model.canvasHeight = 1080;  // The height of the subtitle rendering canvas
    model.isBondFontStyle = NO;  // Set whether the subtitle font is bold
    model.fontColor = 0xFF000000; // Set the subtitle font color, the default is white and opaque
    [_txVodPlayer setSubtitleStyle:model];

    21.Switching between multiple audio tracks

    The advanced version of the player SDK supports switching between multiple audio tracks built into the video. The usage is as follows:
    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];

    Using Advanced Features

    1. Video preloading

    Step 1. Use video preloading

    In UGSV playback scenarios, the preloading feature contributes to a smoother viewing experience: While watching a video, you can load the URL of the next video to be played back on the backend. When the next video is switched to, it will be preloaded and can be played back immediately.
    Video preloading can deliver an instant playback effect but has certain performance overheads. If your business needs to preload many videos, we recommend you use this feature together with video predownloading.
    This is how seamless switch works in video playback. You can use 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 called
    NSString* 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];
    After video A ends and video B is automatically or manually switched to, you can call the resume function to immediately play back video B.
    After 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 switch
    if (EvtID == PLAY_EVT_PLAY_END) {
    [_player_A stopPlay];
    [_player_B setupVideoWidget:mVideoContainer insertIndex:0];
    [_player_B resume];

    Step 2. Configure the video preloading buffer

    You can set a large buffer to play back videos more smoothly under unstable network conditions.
    You can set a smaller buffer to reduce the traffic consumption.
    Preloading buffer size
    This API is used to control the maximum buffer size before the playback starts in preloading scenarios (that is, 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`
    Playback buffer size
    During normal video playback, you can control the maximum size of the data buffered from the network in advance. If the maximum buffer size is not configured, the player will use the default buffer policy to guarantee a smooth playback experience.
    TXVodPlayConfig *_config = [[TXVodPlayConfig alloc]init];
    [_config setMaxBufferSize:10]; // Maximum buffer size during playback in MB
    [_txVodPlayer setConfig:_config]; // Pass in `config` to `_txVodPlayer`

    2. Video predownloading

    You can download part of the video content in advance without creating a player instance, so as to start playing back the video faster when using the player. This helps deliver a better playback experience.
    Before using the playback service, make sure that video cache has been set.
    TXPlayerGlobalSetting is the global cache setting API, and the original TXVodConfig API has been deprecated.
    The global cache directory and size settings have a higher priority than those configured in TXVodConfig of the player.
    Pre-download by media URL
    Pre-download by media filedId
    An example code for pre-downloading a video via a media asset URL is as follows:
    // Set the global cache directory of the playback engine
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *preloadDataPath = [documentsDirectory stringByAppendingPathComponent:@"/preload"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:preloadDataPath]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:preloadDataPath 
    error:&error]; //Create folder
    [TXPlayerGlobalSetting setCacheFolderPath:preloadDataPath];
    // Set the playback engine cache size
    [TXPlayerGlobalSetting setMaxCacheSize:200];
    NSString *m3u8url = "http://****";
    int taskID = [[TXVodPreloadManager sharedManager] startPreload:m3u8url 
    // Cancel predownloading
    [[TXVodPreloadManager sharedManager] stopPreload:taskID];
    Pre-download by fileId is supported since version 11.3.
    Pre-downloading by fileId is a time-consuming operation, please do not call it in the main thread, otherwise an illegal call exception will be thrown. The preferredResolution passed in during startPreload must be consistent with the preferred resolution set when starting the broadcast, otherwise the expected effect will not be achieved. An example of use is as follows:
    //Set the global cache directory of the playback engine
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *preloadDataPath = [documentsDirectory stringByAppendingPathComponent:@"/preload"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:preloadDataPath]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:preloadDataPath
    error:&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:params
    delegate:self]; // TXVodPreloadManagerDelegate
    // Set the playback engine cache size
    [[TXVodPreloadManager sharedManager] stopPreload:taskID];

    3. Video download

    Video download allows users to download online videos and watch them offline. If the video is encrypted, the downloaded video through the player SDK will be kept in an encrypted state locally and can only be decrypted and played through Tencent Cloud Player SDK. This can effectively prevent illegal dissemination of downloaded videos and protect video security.
    As HLS streaming media cannot be directly saved locally, you cannot download them and play back them as local files. You can use the video download scheme based on TXVodDownloadManager to implement offline HLS playback.
    Currently, TXVodDownloadManager can cache only HLS files but not MP4 and FLV files.
    The Player SDK already supports playing back local MP4 and FLV files.

    Step 1. Make preparations

    When the SDK is initialized, set the global storage path for functions such as video download, preload, and cache. The usage is as follows:
    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];

    Step 2. Start the download

    You can start the download through the fileid or URL.
    Through fileid
    Through URL
    You need to pass in 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];
    You only need to pass in the download URL. Only the non-nested HLS, i.e., single-bitstream HLS, is supported. Use fileid in case of private encryption.
    [downloader startDownloadUrl:@"http://1253131631.vod2.myqcloud.com/26f327f9vodgzp1253131631/f4bdff799031868222924043041/playlist.m3u8"]

    Step 3. Receive the task information

    Before receiving the task information, you need to set the callback delegate first.
    downloader.delegate = self;
    You may receive the following task callbacks:
    Callback Message
    -[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.
    Download error code
    error code
    Download successful
    Failed to request video information from the cloud on-demand console, it is recommended to check whether the fileId and psign parameters are correct
    No file for this resolution
    The download file format is not supported
    The network is disconnected, it is recommended to check whether the network is normal
    Failed to get HLS decryption key
    Download directory access failed, it is recommended to check whether you have permission to access the download directory
    As the downloader can download multiple files at a time, the callback API carries the 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.

    Step 4. Stop the download

    You can call the -[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.

    Step 5. Manage downloads

    1. You can get the download lists of all accounts or the specified account.
    // s a time-consuming function. Please do not call it in the main thread
    NSArray<TXVodDownloadMediaInfo *> *array = [[[TXVodDownloadManager shareInstance] getDownloadMediaInfoList] mutableCopy];
    // Get the download list of the `default` user
    for (TXVodDownloadMediaInfo *info in array) {
    if ([info.userName isEqualToString:@"default"]) {
    // Save the download list of the `default` user
    2. Get the download information of a FileId or URL:
    2.1 To get the download information of a 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 downloaded
    downlaodMediaInfo.duration; // Get the total duration
    downlaodMediaInfo.playableDuration; // Get the playable duration of the downloaded video
    downlaodMediaInfo.progress; // Get the download progress
    downlaodMediaInfo.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.
    2.2 To get the download information of a URL, you simply need to pass in the URL information.
    // Get the download information of a `fileId`
    TXVodDownloadMediaInfo *sourceMediaInfo = [[TXVodDownloadMediaInfo alloc] init];
    mediaInfo.url = @"videoURL";
    TXVodDownloadMediaInfo *downlaodMediaInfo = [[TXVodDownloadManager shareInstance] getDownloadMediaInfo:sourceMediaInfo];
    3. Delete the download information and relevant file:
    If you don't need to resume the download, call the -[TXVodDownloadManager deleteDownloadFile:] method to delete the file to release the storage space.

    Step 6: Play offline after downloading

    The downloaded video can be played without internet connection, no internet connection is required. Once the download is complete, it can be played.
    NSArray<TXVodDownloadMediaInfo *> *mediaInfoList = [[TXVodDownloadManager shareInstance]getDownloadMediaInfoList];
    TXVodDownloadMediaInfo *mediaInfo = [mediaInfoList firstObject]; // Find the current media object according to the situation
    if (mediaInfo.downloadState == TXVodDownloadMediaInfoStateFinish) { // Determine whether the download is complete
    [self.player startVodPlay:mediaInfo.playPath];
    When downloading and playing offline, be sure to get the download list and play it through the PlayPath of the download list video object TXVodDownloadMediaInfo, do not save the PlayPath object directly.

    4. Encrypted playback

    The video encryption solution is used in scenarios where the video copyright needs to be protected, such as online education. To encrypt your video resources, you need to alter the player and encrypt and transcode video sources. For more information, see Media Encryption and Copyright Protection Overview.
    After you get the 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 account
    p.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];

    5. Player configuration

    Before calling 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`
    Specifying resolution when playback starts
    When playing back an HLS multi-bitrate video source, if you know the video stream resolution information in advance, you can specify the preferred resolution before playback starts, and the player will select and play back the stream at or below the preferred resolution. In this way, after playback starts, you don't need to call 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`
    Specifying media type before playback
    When the media type to be played is known in advance, the playback type detection within the player SDK can be reduced and the startup speed can be improved by configuring TXVodPlayConfig#setMediaType.
    TXVodPlayConfig#setMediaType is supported since version 11.2.
    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];
    Setting playback progress callback interval
    TXVodPlayConfig *_config = [[TXVodPlayConfig alloc]init];
    [_config setProgressInterval:200]; // Set the progress callback interval in ms
    [_txVodPlayer setConfig:_config]; // Pass in `config` to `_txVodPlayer`

    6、HttpDNS resolution service

    HTTPDNS is a domain name resolution service that sends domain name resolution requests to DNS servers based on the HTTP protocol, replacing the traditional method of sending resolution requests to the operator's local DNS based on the DNS protocol. This method can avoid domain name hijacking and cross-network access issues caused by local DNS, and solve the problem of video playback failure caused by abnormal domain name resolution in mobile internet services.
    HttpDNS resolution service is supported from version 10.9 onwards.
    1. To enable HTTPDNS resolution service
    you can choose Tencent Cloud or other cloud providers and open the service. Make sure to integrate the service into the playback SDK after successful activation.
    2. Accessing HTTPDNS Resolution Service in the Playback SDK
    Taking Tencent Cloud HTTPDNS as an example, the following steps demonstrate how to access the service in the player SDK:
    // 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;

    7. HEVC Adaptive Downgrade Play

    The player supports playing links that contain both HEVC and other video encoding formats, such as H.264. When the player device does not support the HEVC format, it will automatically downgrade to playing videos in the configured alternative encoding format (such as H.264).
    Note: Supported from player version 11.7 of the premium version.
    #import <CoreMedia/CoreMedia.h> //Import header file
    NSDictionary *dic = @{
    VOD_KEY_VIDEO_CODEC_TYPE:@(kCMVideoCodecType_HEVC), // Specify the original HEVC video encoding type
    VOD_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}"];

    8. Volume Normalization

    The player supports automatically adjusting the volume when playing audio to ensure that the volume of all audio is consistent. This can avoid problems with some audio being too loud or too quiet, providing a better auditory experience. Use 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)
    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

    Player Event Listening

    You can bind a TXVodPlayListener listener to the TXVodPlayer object to use onPlayEvent (event notification) and onNetStatus (status feedback) to sync information to your application.

    Event notification (onPlayEvent)

    Playback events

    Event ID
    Video playback started.
    Video playback progress. The current playback progress, loading progress, and total video duration will be notified of.
    The video is being loaded. The LOADING_END event will be reported if video playback resumes.
    Video loading ended, and video playback resumed.
    Seeking was completed. The seeking feature is supported by v10.3 or later.
    A round of loop was completed. The loop feature is supported by v10.8 or later.
    Cache hit event at startup (supported since version 11.2).
    Received SEI frame event (supported from player version 11.6 of the premium version).
    SEI frame
    SEI (Supplemental Enhancement Information) frames are a type of frame used to transmit additional information. The premium version of the player will parse the SEI frames in the video stream and provide callbacks through the `VOD_PLAY_EVT_VIDEO_SEI` event.
    Note: Supported from player version 11.6 of the premium version.
    -(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 } }

    Warning events

    You can ignore the following events, which are only used to notify you of some internal events of the SDK.
    Event ID
    Failed to decode the current video frame.
    Failed to decode the current audio frame.
    The network was disconnected, and automatic reconnection was performed (the PLAY_ERR_NET_DISCONNECT event will be thrown after three failed attempts).
    Failed to start the hardware decoder, and the software decoder was used instead.

    Connection events

    The following server connection events are mainly used to measure and collect the server connection time:
    Event ID
    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.
    The network received the first renderable video data packet (IDR).

    Image quality events

    The following events are used to get image change information:
    Event ID
    The video resolution changed.
    The MP4 video was rotated.

    Video information events

    Event ID
    Obtained the information of the file played back successfully.
    If you play back a video through 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
    Video thumbnail URL
    Video playback URL
    Video duration
    Ghost watermark text content (supported from version 11.6).
    -(void) onPlayEvent:(TXVodPlayer *)player event:(int)EvtID withParam:(NSDictionary*)param
    // 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

    Ghost watermark

    The content of the ghost watermark is filled in the player signature and is ultimately displayed on the playback end through collaboration between the cloud and the player, ensuring the security of the watermark throughout the transmission process. Follow the tutorial to configure the ghost watermark in the player signature. The content of the ghost watermark can be obtained through `[param objectForKey:@"EVT_KEY_WATER_MARK_TEXT"]` after receiving the `VOD_PLAY_EVT_GET_PLAYINFO_SUCC` event from the player. For detailed usage tutorial, please refer to SuperPlayer Component > Ghost Watermark.
    Note: Supported from player version 11.6.

    Playback error event

    [-6004 , -6010] Error events are supported since version 11.0.
    Event ID
    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.
    HLS decryption key retrieval failure.
    System player playback error.
    Video decoding error or unsupported video format.
    Audio decoding error or unsupported audio format.
    Subtitle decoding error.
    Video rendering error.
    Video post-processing error.
    Failed to obtain the on-demand file information. It is recommended to check whether the AppId, FileId or Psign is filled in correctly.

    Status feedback (onNetStatus)

    The status feedback is triggered once every 0.5 seconds to provide real-time feedback on the current status of the pusher. It can act as a dashboard to inform you of what is happening inside the SDK so you can better understand the current video playback status.
    Current instantaneous CPU utilization
    Video resolution - width
    Video resolution - height
    Current network data reception speed in KBps
    Current video frame rate of streaming media
    Current video bitrate in bps of streaming media
    Current audio bitrate in bps of streaming media
    Buffer (`jitterbuffer`) size. If the current buffer length is 0, lag will occur soon.
    Connected server IP
    Below is the sample code of using `onNetStatus` to get the video playback information:
    - (void)onNetStatus:(TXVodPlayer *)player withParam:(NSDictionary *)param {
    // Get the current CPU utilization
    float cpuUsage = [[param objectForKey:@"CPU_USAGE"] floatValue];
    // Get the video width
    int videoWidth = [[param objectForKey:@"VIDEO_WIDTH"] intValue];
    // Get the video height
    int videoHeight = [[param objectForKey:@"VIDEO_HEIGHT"] intValue];
    // Get the real-time speed
    int speed = [[param objectForKey:@"NET_SPEED"] intValue];
    // Get the current video frame rate of streaming media
    int fps = [[param objectForKey:@"VIDEO_FPS"] intValue];
    // Get the current video bitrate in Kbps of streaming media
    int videoBitRate = [[param objectForKey:@"VIDEO_BITRATE"] intValue];
    // Get the current audio bitrate in Kbps of streaming media
    int 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 IP
    NSString *ip = [param objectForKey:@"SERVER_IP"];

    Other functions

    HLS live video source playback

    The premium version of the player supports playing HLS live video sources. Starting from version 11.8, it supports live video sources with HLS EVENT. Usage is as follows:
    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}];

    Scenario-Specific Features

    1. Dynamically Setting AudioSession

    Sometimes it is necessary to dynamically set the audio output mode based on the scene, especially for iPhones, which natively support multiple audio playback and background modes. Therefore, we support the following three main modes based on the user's scenario:
    AVAudioSessionCategoryPlayback: Exclusive playback in the background.
    AVAudioSessionCategoryPlayAndRecord: Exclusive playback in the background.
    AVAudioSessionCategoryAmbient: Mixed playback.
    You can use the above modes to set the Category and Option of AudioSession according to the current scenario to achieve your purpose. The following are two examples of settings for different scenarios (the settings below can be dynamically adjusted and set according to your own scenario):
    Scenario 1: Playlist scenario (video playback needs to support silent playback in the playlist and does not interrupt external audio playback).
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers error:nil];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    Scenario 2: Playback details scenario (the video details have sound, and temporarily interrupt external audio. After the video playback is complete, the external audio will be resumed).
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
    [[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];

    2. SDK-based demo component

    Based on the Player SDK, Tencent Cloud has developed a player component. It integrates quality monitoring, video encryption, Top Speed Codec, definition selection, and small window playback and is suitable for all VOD and live playback scenarios. It encapsulates complete features and provides upper-layer UIs to help you quickly create a playback program comparable to popular video apps.

    3. Open-source GitHub projects

    Based on the Player SDK, Tencent Cloud has developed immersive video player, video feed stream, and multi-layer reuse components and will provide more user scenario-based components on future versions. You can download the Player for iOS to try out the components.
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support