tencent cloud

User Generated Short Video SDK

iOS

Download
포커스 모드
폰트 크기
마지막 업데이트 시간: 2026-05-15 16:33:30

Feature Overview

Video editing includes features such as video clipping, time-based special effects (slow motion, reverse, and loop), special effect filters (dynamic light-wave, darkness and phantom, soul out, and cracked screen), filter styles (aesthetic, rosy, blues, etc.), music mix, animated stickers, static stickers, and bubble subtitles.

Overview of Relevant Classes

Class Name
Feature
TXVideoInfoReader.h
Gets media information
TXVideoEditer.h
Edits video

Basic Video Editing Workflow

1. Set video preview parameters and video path.
2. Start preview.
3. Add effects.
4. Generate video to the specified file.
5. Monitor and handle generation events.

Sample

// Here, `Common/UGC/VideoPreview` in the demo is used as the preview view
#import "VideoPreview.h"

@implementation EditViewController
{
TXVideoEditer *editor;
VideoPreview *_videoPreview;
}

- (void)viewDidLoad {
[super viewDidLoad];
_videoPreview = [[VideoPreview alloc] initWithFrame:self.view.bounds];
[self.view addSubview:_videoPreview];
// Edit preview parameters
TXPreviewParam *param = [[TXPreviewParam alloc] init];
param.videoView = _videoPreview.renderView;
param.renderMode = PREVIEW_RENDER_MODE_FILL_EDGE;

// 1. Initialize the editor. If you do not need preview, you can pass in `nil` or directly call the `init` method
TXVideoEditer *editor = [[TXVideoEditer alloc] initWithPreview:param];

// Set the source video path
NSString *path = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"mp4"]
[editor setVideoPath: path];

// Configure the delegation
editor.generateDelegate = self; // Set the callback delegation object of the generation event, which can be used to get the generation progress and result

// 2. Process the video. Watermarking is used as an example here
[editor setWaterMark:[UIImage imageNamed:@"water_mark"]
normalizationFrame:CGRectMake(0,0,0.1,0)];
}

// 3. Generate the video. Response to a user click is used as an example here
- (IBAction)onGenerate:(id)sender {
NSString *output = [NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.mp4"];
[editor generateVideo:VIDEO_COMPRESSED_720P videoOutputPath:output];
}

// 4. Get the generation progress
-(void) onGenerateProgress:(float)progress
{
}

// Get the generation result
-(void) onGenerateComplete:(TXGenerateResult *)result
{
if (result.retCode == 0) {
// Generated successfully
} else {
// Generation failed. For the specific cause, please see `result.descMsg`.
}
}
@end

Getting Video Information

The getVideoInfo method of TXVideoInfoReader can get certain basic information of a specified video file. The relevant APIs are as detailed below:
// Get the video file information
+ (TXVideoInfo *)getVideoInfo:(NSString *)videoPath;

/** Get the video file information
* @param videoAsset Video file attributes
* @return Video information
*/
+ (TXVideoInfo *)getVideoInfoWithAsset:(AVAsset *)videoAsset;
The returned TXVideoInfo is defined as follows:
/// Video information
@interface TXVideoInfo : NSObject
/// Image of the first video frame
@property (nonatomic, strong) UIImage* coverImage;
/// Video duration in seconds
@property (nonatomic, assign) CGFloat duration;
/// Video size in bytes
@property (nonatomic, assign) unsigned long long fileSize;
/// Video frame rate in fps
@property (nonatomic, assign) float fps;
/// Video bitrate in Kbps
@property (nonatomic, assign) int bitrate;
/// Audio sample rate
@property (nonatomic, assign) int audioSampleRate;
/// Video width
@property (nonatomic, assign) int width;
/// Video height
@property (nonatomic, assign) int height;
/// Video image rotation angle
@property (nonatomic, assign) int angle;
@end

Getting Thumbnail

The thumbnail APIs are mainly used to generate the preview thumbnails displayed on the video editing page, get the video cover, and perform other relevant operations.

1. Get the thumbnails evenly distributed along the video duration by number

getSampleImages of TXVideoInfoReader can get the specified number of thumbnails at the same time intervals:
/** Get the list of thumbnails of the video
* @param count Number of the thumbnails to be obtained (at even sampling intervals)
* @param maxSize Maximum thumbnail dimensions. The dimensions of the generated thumbnails will not exceed the specified width and height.
* @param videoAsset Video file attributes
* @param sampleProcess Sampling progress
*/
+ (void)getSampleImages:(int)count
maxSize:(CGSize)maxSize
videoAsset:(AVAsset *)videoAsset
progress:(sampleProcess)sampleProcess;


+ (void)getSampleImages:(int)count
videoPath:(NSString *)videoPath
progress:(sampleProcess)sampleProcess;


+ (void)getSampleImages:(int)count
videoAsset:(AVAsset *)videoAsset
progress:(sampleProcess)sampleProcess;
VideoRangeSlider in the SDK uses getSampleImages to get 10 thumbnails so as to construct a progress bar consisting of video preview images.

2. Get thumbnails according to the list of points in time

/**
* Get the thumbnails according to the list of points in time
* @param asset Video file object
* @param times List of points in time for getting thumbnails
* @param maxSize Thumbnail dimensions
*/
+ (UIImage *)getSampleImagesFromAsset:(AVAsset *)asset
times:(NSArray<NSNumber*> *)times
maxSize:(CGSize)maxSize
progress:(sampleProcess)sampleProcess



/* Get a single frame image at the specified time.
* @param time The time to extract the frame.
* @param videoPath The video file path.
*/
+ (nullable UIImage *)getSampleImage:(float)time videoPath:(NSString *)videoPath;


+ (nullable UIImage *)getSampleImage:(float)time videoAsset:(AVAsset *)videoAsset;

Editing and Previewing

Video editing supports two effect preview modes: pinpoint preview (the video image is frozen at a specified point in time) and range preview (a video segment within a specified time range (A–B) is looped). To use a preview mode, you need to bind a UIView to the SDK in order to display the video image.

1. Set up the UIView for preview playback

The initWithPreview function of TXVideoEditer is used to bind a UIView to the SDK for rendering video frames. By configuring the renderMode property in TXPreviewParam, you can set two modes: ​adaptive (fit) or ​fill..
/**
* Default initialization method
* @param param Preview parameters for the editor's view
* @see TXPreviewParam
*/
- (instancetype)initWithPreview:(TXPreviewParam *)param;

@interface TXPreviewParam : NSObject
@property(nonatomic, strong) UIView* videoView; // Video preview view
@property(nonatomic, assign) TXPreviewRenderMode renderMode; // Fill mode
@end
PREVIEW_RENDER_MODE_FILL_SCREEN - Fill mode, where the video image will cover the entire screen with no black bars present, but the video image may be cropped.
PREVIEW_RENDER_MODE_FILL_EDGE - Fit mode, where the video image will be complete but black bars will exist if the aspect ratio of the video is different from that of the screen.

2. Use pinpoint preview

The previewAtTime function of TXVideoEditer is used to preview the video image at a specified point in time.
/** Render the video image at a specified point in time
* @param time Preview frame time in seconds
*/
- (void)previewAtTime:(CGFloat)time;

3. Use range preview

The startPlayFromTime function of TXVideoEditer is used to loop a video segment within the time range of A–B.
/** Play back a video segment within a time range
* @param startTime Playback start time in seconds
* @param endTime Playback end time in seconds
*/
- (void)startPlayFromTime:(CGFloat)startTime
toTime:(CGFloat)endTime;

4. Pause and resume preview

/// Pause the video
- (void)pausePlay;

/// Resume the video
- (void)resumePlay;

/// Stop the video
- (void)stopPlay;

Beauty Filter

You can apply filter effects to videos, such as whitening, romantic, fresh, etc. Additionally, you can set composite filters, which are typically used for transitioning between two filters.
// Among them, image is the filter mapping image. If image is set to nil, the filter effect will be cleared
- (void) setFilter:(UIImage *)image;


// Set the filter effect level from 0 to 1. The larger the value, the more obvious the filter effect. Default is 0.5
- (void)setSpecialRatio:(float)specialRatio;

/**
* Set two filter effects
* @param leftFilter Left filter image (nil represents no left filter)
* @param leftIntensity Left filter intensity
* @param rightFilter Right filter image (nil represents no right filter)
* @param rightIntensity Right filter intensity
* @param leftRatio Proportion of the left filter
*/

- (void)setFilter:(UIImage *)leftFilter
leftIntensity:(CGFloat)leftIntensity
rightFilter:(UIImage *)rightFilter
rightIntensity:(CGFloat)rightIntensity
leftRatio:(CGFloat)leftRatio;
Demo:
TXVideoEditer *_ugcEdit;
NSString * path = [[NSBundle mainBundle] pathForResource:@"FilterResource" ofType:@"bundle"];
path = [path stringByAppendingPathComponent:@"langman.png"];
UIImage* image = [UIImage imageWithContentsOfFile:path];
[_ugcEdit setFilter:image];
[_ugcEdit setSpecialRatio:0.5];

Watermark

1. Set a global watermark

You can set a watermark image for the video and specify the image position.
You can set a watermark as follows:
- (void) setWaterMark:(UIImage *)waterMark normalizationFrame:(CGRect)normalizationFrame;
Here, waterMark indicates the watermark image, and normalizationFrame is a normalized frame value relative to the video image. The values of x, y, width, and height in frame all range from 0 to 1.

Demo

UIImage *image = [UIImage imageNamed:@"watermark"];
[_ugcEdit setWaterMark:image normalizationFrame:CGRectMake(0, 0, 0.3 , 0.3 * image.size.height / image.size.width)];// The watermark width is 30% of the video width, and the height is proportionally scaled according to the width

2. Set a post-roll watermark

You can set a post-roll watermark for the video and specify the watermark position.
You can set a post-roll watermark as follows:
- (void) setTailWaterMark:(UIImage *)tailWaterMark normalizationFrame:(CGRect)normalizationFrame
duration:(CGFloat)duration;
Here, tailWaterMark indicates the post-roll watermark image, and normalizationFrame is a normalized frame relative to the video image. The values of x, y, width, and height in frame all range from 0 to 1. duration indicates the watermark duration in seconds.

Demo

set a post-roll watermark that can be displayed for 1 second in the middle of the video image
UIImage *tailWaterimage = [UIImage imageNamed:@"tcloud_logo"];
float w = 0.15;
float x = (1.0 - w) / 2.0;
float width = w * videoMsg.width;
float height = width * tailWaterimage.size.height / tailWaterimage.size.width;
float y = (videoMsg.height - height) / 2 / videoMsg.height;
[_ugcEdit setTailWaterMark:tailWaterimage normalizationFrame:CGRectMake(x,y,w,0) duration:1];


Adding BGM During Editing

// Initialize the editor
TXPreviewParam *param = [[TXPreviewParam alloc] init];
param.videoView = videoView;
param.renderMode = PREVIEW_RENDER_MODE_FILL_EDGE;
ugcEdit = [[TXVideoEditer alloc] initWithPreview:param];

// Set BGM asset path
[ugcEdit setBGMAsset:fileAsset result:^(int result) {
}];

// Set BGM start and end times (in seconds)
[ugcEdit setBGMStartTime:0 endTime:5];

// Enable/disable BGM looping
[ugcEdit setBGMLoop:YES];

// Set BGM start position in the video timeline (in seconds)
[ugcEdit setBGMAtVideoTime:0];

// Set video original audio volume (0.0 ~ 1.0)
[ugcEdit setVideoVolume:1.0];

// Set BGM volume (0.0 ~ 1.0)
[ugcEdit setBGMVolume:1.0];

Compressing and Clipping

1. Video Compression

To compress a video, use the following APIs:
/**
* Pros: Broad compatibility, supports all video editing operations, and the output video plays well across platforms.
* Cons: Slower processing speed.
* Monitor results via `TXVideoGenerateListener` callbacks.
* @param videoCompressed Video compression quality level
* @param videoOutputPath Output video file path
*/
- (void)generateVideo:(TXVideoCompressed)videoCompressed
videoOutputPath:(NSString *)videoOutputPath;

/**
* Pros: Faster processing speed.
* Cons:
* 1. Trimmed videos may have slightly worse cross-platform compatibility.
* 2. Only supports trimming and compression via system APIs; other operations fall back to the default `generateVideo` logic.
*/
- (void)quickGenerateVideo:(TXVideoCompressed)videoCompressed
videoOutputPath:(NSString *)videoOutputPath;

/**
* Two-pass encoding (not supported in the Lite version).
* Pros: Better compatibility and clarity at the same bitrate, maintains quality at lower bitrates, works for all editing operations.
* Cons: Slowest processing speed.
*/
- (void)generateVideoWithTwoPass:(TXVideoCompressed)videoCompressed
videoOutputPath:(NSString *)videoOutputPath;
TXVideoCompressed Constants:
typedef NS_ENUM(NSInteger, TXVideoCompressed) {
VIDEO_COMPRESSED_360P = 0, // Compress to 360p resolution
VIDEO_COMPRESSED_480P = 1, // Compress to 480p
VIDEO_COMPRESSED_540P = 2, // Compress to 540p
VIDEO_COMPRESSED_720P = 3, // Compress to 720p
VIDEO_COMPRESSED_1080P = 4, // Compress to 1080p
};
If the source video's resolution is ​lower than the selected constant, the original resolution is retained.
If the source video's resolution is ​higher, it is compressed to the target resolution.

2. Cropping Region Configuration

Specify a cropping region when calling generateVideo. If not set, the entire video is processed. Use setCutFromTime:
/**
* Set video cropping range.
* @param startTime Start time (in seconds)
* @param endTime End time (in seconds)
*/
- (void)setCutFromTime:(float)startTime toTime:(float)endTime;

3. Video Bitrate Configuration

Customize the video bitrate (recommended range: ​600–12000 kbps). Avoid extremely high or low values:
High bitrate → Large file size.
Low bitrate → Blurry video.
Note: If not set, the SDK automatically calculates the bitrate based on the compression level.
- (void) setVideoBitrate:(int)bitrate;

4. Video Frame Rate Configuration

Use setVideoFramerate to set the frame rate:
- (void)setVideoFramerate:(TXVideoFramerateLevel)framerate;

typedef NS_ENUM(NSInteger, TXVideoFramerateLevel) {
VIDEO_FRAMERATE_ORIGIN = 0, // Keep original frame rate
VIDEO_FRAMERATE_AUTO = -1, // Auto-select based on resolution and bitrate
VIDEO_FRAMERATE_15FPS = 15, // 15 fps
VIDEO_FRAMERATE_25FPS = 25, // 25 fps
VIDEO_FRAMERATE_30FPS = 30, // 30 fps
VIDEO_FRAMERATE_60FPS = 60, // 60 fps
};
VIDEO_FPS_ORIGIN - Utilizes the original video's frame rate. When the setVideoFrameRate interface is not called, the system defaults to using the video's original frame rate.
VIDEO_FPS_AUTO - Based on the user-generated video's resolution, bitrate, and the SDK's internal decisions, an appropriate frame rate will be determined.
VIDEO_FPS_15, VIDEO_FPS_25, VIDEO_FPS_30, VIDEO_FPS_60 - Specifies the frame rate as 15, 25, 30, or 60 fps.
Regardless of the parameters passed by the user, the final frame rate of the generated video will not exceed the original video's frame rate.
If the frame rate you set is too low, resulting in an excessively low frame rate for the generated video, it may cause the video to appear less smooth.

Advanced Features

도움말 및 지원

문제 해결에 도움이 되었나요?

피드백