1箩张、視頻加水印,并保存到沙盒當(dāng)中
//原視頻sureasset较锡,有外界傳進來
AVURLAsset *asset = (AVURLAsset *)[self addPhotoTitleWithAsset:sureasset][0];
? ? AVMutableVideoComposition *mainCompositionInst = [self addPhotoTitleWithAsset:sureasset][1];
? ? sureasset = asset;
? ? AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset: sureasset presetName:AVAssetExportPresetMediumQuality];
? ? NSString *failPath = [self getVideosPath:@"localVideo"];//獲取路徑
? ? NSURL *filUrl = [NSURL fileURLWithPath:failPath];
? ? session.outputURL = filUrl;//視頻輸出地址
? ? session.outputFileType = AVFileTypeMPEG4;//AVFileTypeQuickTimeMovie;//AVFileTypeMPEG4;
? ? // 這個一般設(shè)置為yes(指示輸出文件應(yīng)針對網(wǎng)絡(luò)使用進行優(yōu)化业稼,例如QuickTime電影文件應(yīng)支持“快速啟動”)
? ? session.shouldOptimizeForNetworkUse = YES;
? ? // 文件的最大多大的設(shè)置
? ? session.fileLengthLimit = 30 * 1024 * 1024;
? ? session.shouldOptimizeForNetworkUse = YES;
? ? session.videoComposition = mainCompositionInst;
? ? [session exportAsynchronouslyWithCompletionHandler:^(void){
? ? ? ? dispatch_async(dispatch_get_main_queue(), ^{
? ? ? ? ? ? //視頻導(dǎo)入成功
? ? ? ? ? ? //failPath為本地視頻地址
? ? ? ? ? ? completeBlock(failPath,YES);
? ? ? ? });
? ? }];
//獲取路徑
- (NSString *)getVideosPath:(NSString *)videoName{
? ? NSString *documents = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
? ? documents = [documents stringByAppendingPathComponent:@"CCTV5"];
? ? documents = [self action_addFiles:documents];//判斷文件是否存在
? ? NSString *failPath = [documents stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",videoName]];
? ? return failPath;
}
#pragma mark- 視頻加水印
//添加水印
-(NSArray *)addPhotoTitleWithAsset:(AVAsset *)videoAsset
{
? ? //1 創(chuàng)建AVAsset實例
? ? //AVURLAsset*videoAsset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:path]];
? ? AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
? ? //3 視頻通道
? ? AVMutableCompositionTrack *videoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? preferredTrackID:kCMPersistentTrackID_Invalid];
? ? [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
? ? ? ? ? ? ? ? ? ? ? ? ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] firstObject]
? ? ? ? ? ? ? ? ? ? ? ? atTime:kCMTimeZero error:nil];
? ? //2 音頻通道
? ? AVMutableCompositionTrack *audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? preferredTrackID:kCMPersistentTrackID_Invalid];
? ? [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
? ? ? ? ? ? ? ? ? ? ? ? ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeAudio] firstObject]
? ? ? ? ? ? ? ? ? ? ? ? atTime:kCMTimeZero error:nil];
? ? //3.1 AVMutableVideoCompositionInstruction 視頻軌道中的一個視頻,可以縮放蚂蕴、旋轉(zhuǎn)等
? ? AVMutableVideoCompositionInstruction *mainInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
? ? mainInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, videoAsset.duration);
? ? // 3.2 AVMutableVideoCompositionLayerInstruction 一個視頻軌道低散,包含了這個軌道上的所有視頻素材
? ? AVMutableVideoCompositionLayerInstruction *videolayerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
? ? [videolayerInstruction setOpacity:0.0 atTime:videoAsset.duration];
? ? // 3.3 - Add instructions
? ? mainInstruction.layerInstructions = [NSArray arrayWithObjects:videolayerInstruction,nil];
? ? //AVMutableVideoComposition:管理所有視頻軌道,水印添加就在這上面
? ? AVMutableVideoComposition *mainCompositionInst = [AVMutableVideoComposition videoComposition];
? ? AVAssetTrack *videoAssetTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] firstObject];
? ? CGSize naturalSize = videoAssetTrack.naturalSize;
? ? //防崩潰處理骡楼,這個width可能為空熔号,按比例給他值
? ? if (naturalSize.width == 0) {
? ? ? ? CGFloat a = (1280.f / 720);
? ? ? ? naturalSize.width =? a * naturalSize.height;
? ? }
? ? float renderWidth, renderHeight;
? ? renderWidth = naturalSize.width;
? ? renderHeight = naturalSize.height;
? ? mainCompositionInst.renderSize = CGSizeMake(renderWidth, renderHeight);
? ? mainCompositionInst.instructions = [NSArray arrayWithObject:mainInstruction];
? ? mainCompositionInst.frameDuration = CMTimeMake(1, 30);
? ? [self applyVideoEffectsToComposition:mainCompositionInst size:naturalSize];
? ? NSArray *arrar = [NSArray arrayWithObjects:mixComposition,mainCompositionInst, nil];
? ? return arrar;;
}
/**
設(shè)置水印及其對應(yīng)視頻的位置
@param composition 視頻的結(jié)構(gòu)
@param size 視頻的尺寸
*/
- (void)applyVideoEffectsToComposition:(AVMutableVideoComposition *)composition size:(CGSize)size
{
? ? // 文字
? ? CATextLayer *subtitle1Text = [[CATextLayer alloc] init];
? ? //? ? [subtitle1Text setFont:@"Helvetica-Bold"];
? ? [subtitle1Text setFontSize:36];
? ? [subtitle1Text setFrame:CGRectMake(10, size.height-10-230, size.width, 100)];
? ? [subtitle1Text setString:@"央視體育5 水印"];
? ? //? ? [subtitle1Text setAlignmentMode:kCAAlignmentCenter];
? ? [subtitle1Text setForegroundColor:[[UIColor whiteColor] CGColor]];
? ? //圖片
? ? CALayer*picLayer = [CALayer layer];
? ? //picLayer.contents = (id)[UIImage imageNamed:@"CTVITTRIMSource.bundle/QQ"].CGImage; //本地圖片
? ? picLayer.contents = (id)self.videoWaterMarkImage.CGImage; //本地圖片2
? ? //NSString *imageUrl = @"http://p1.img.cctvpic.com/photoAlbum/templet/special/PAGEQ1KSin2j2U5FERGWHp1h160415/ELMTnGlKHUJZi7lz19PEnqhM160415_1460715755.png";
? ? //picLayer.contents = (id)[self getImageFromURL:imageUrl].CGImage; //遠程圖片
? ? CGFloat width = 63;
? ? CGFloat leftMargin = 16 * [self scaleSizeWithHeight:size.height];
? ? CGFloat topMargin = 20 * [self scaleSizeWithHeight:size.height];
? ? if (self.videoWaterMarkPlace == WaterMarkTopLeft) {
? ? ? ? picLayer.frame = CGRectMake(leftMargin, size.height-topMargin-[self scaleSizeWithHeight:size.height]*50, [self scaleSizeWithHeight:size.height]*width, [self scaleSizeWithHeight:size.height]*width);
? ? }
? ? if (self.videoWaterMarkPlace == WaterMarkBottomLeft) {
? ? ? ? picLayer.frame = CGRectMake(leftMargin, 20, [self scaleSizeWithHeight:size.height]*50, [self scaleSizeWithHeight:size.height]*50);
? ? }
? ? if (self.videoWaterMarkPlace == WaterMarkTopRight) {
? ? ? ? picLayer.frame = CGRectMake(size.width - 20 - [self scaleSizeWithHeight:size.height]*50, size.height-20-[self scaleSizeWithHeight:size.height]*50, [self scaleSizeWithHeight:size.height]*50, [self scaleSizeWithHeight:size.height]*50);
? ? }
? ? if (self.videoWaterMarkPlace == WaterMarkBottomRight) {
? ? ? ? picLayer.frame = CGRectMake(size.width - 20 - [self scaleSizeWithHeight:size.height]*50, 20, [self scaleSizeWithHeight:size.height]*50, [self scaleSizeWithHeight:size.height]*50);
? ? }
? ? // 2 - The usual overlay
? ? CALayer *overlayLayer = [CALayer layer];
? ? [overlayLayer addSublayer:picLayer];
? ? //? ? [overlayLayer addSublayer:subtitle1Text];
? ? overlayLayer.frame = CGRectMake(0, 0, size.width, size.height);
? ? [overlayLayer setMasksToBounds:YES];
? ? CALayer *parentLayer = [CALayer layer];
? ? CALayer *videoLayer = [CALayer layer];
? ? parentLayer.frame = CGRectMake(0, 0, size.width, size.height);
? ? videoLayer.frame = CGRectMake(0, 0, size.width, size.height);
? ? [parentLayer addSublayer:videoLayer];
? ? [parentLayer addSublayer:overlayLayer];
? ? composition.animationTool = [AVVideoCompositionCoreAnimationTool
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];
}
//ios 從網(wǎng)絡(luò)上獲取圖片
-(UIImage *) getImageFromURL:(NSString *)fileURL {
? ? //https://vod.cctv.cn/cctvsports/cctv5/img/advertisingImage.jpg
? ? NSLog(@"執(zhí)行圖片下載函數(shù)");
? ? UIImage * result;
? ? NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
? ? result = [UIImage imageWithData:data];
? ? return result;
}
2、另一種實現(xiàn)方式
? ? //? ? [self applyVideoEffectsToComposition:mainCompositionInst size:naturalSize];
? ? CIFilter *watermarkFilter = [CIFilter filterWithName:@"CISourceOverCompositing"];
? ? mainCompositionInst = [AVMutableVideoComposition videoCompositionWithAsset:videoAsset applyingCIFiltersWithHandler:^(AVAsynchronousCIImageFilteringRequest * _Nonnull request) {
? ? ? ? CIImage *watermarkImage? =? [[CIImage alloc] initWithCGImage:self.videoWaterMarkImage.CGImage];
? ? ? ? CIImage *source = request.sourceImage;
? ? ? ? [watermarkFilter setValue:source forKey:kCIInputBackgroundImageKey];
? ? ? ? [watermarkFilter setValue:[watermarkImage imageByApplyingTransform:CGAffineTransformMakeScale(0.5, 0.5)] forKey:kCIInputImageKey];
? ? ? ? [watermarkFilter setValue:[watermarkImage imageByApplyingTransform:CGAffineTransformMakeTranslation(14, source.extent.size.height - 14 - watermarkImage.extent.size.height)] forKey:kCIInputImageKey];
? ? ? ? [request finishWithImage:watermarkFilter.outputImage context:nil];
? ? }];
? ? //? ? ? //? ? // 4 - 輸出路徑