亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 系統 > iOS > 正文

iOS 在線視頻生成GIF圖功能的方法

2019-10-21 18:41:43
字體:
來源:轉載
供稿:網友

在一些視頻APP中,都可以看到一個將在線視頻轉成GIF圖的功能。下面就來說說思路以及實現。我們知道本地視頻可以生成GIF,那么將在線視頻截取成本地視頻不就可以了嗎?經過比較,騰訊視頻App也是這么做的。話不多說,下面開始上代碼:

第一步:截取視頻

#pragma mark -截取視頻- (void)interceptVideoAndVideoUrl:(NSURL *)videoUrl withOutPath:(NSString *)outPath outputFileType:(NSString *)outputFileType range:(NSRange)videoRange intercept:(InterceptBlock)interceptBlock {  _interceptBlock =interceptBlock;  //不添加背景音樂 NSURL *audioUrl =nil; //AVURLAsset此類主要用于獲取媒體信息,包括視頻、聲音等 AVURLAsset* audioAsset = [[AVURLAsset alloc] initWithURL:audioUrl options:nil]; AVURLAsset* videoAsset = [[AVURLAsset alloc] initWithURL:videoUrl options:nil];  //創建AVMutableComposition對象來添加視頻音頻資源的AVMutableCompositionTrack AVMutableComposition* mixComposition = [AVMutableComposition composition];  //CMTimeRangeMake(start, duration),start起始時間,duration時長,都是CMTime類型 //CMTimeMake(int64_t value, int32_t timescale),返回CMTime,value視頻的一個總幀數,timescale是指每秒視頻播放的幀數,視頻播放速率,(value / timescale)才是視頻實際的秒數時長,timescale一般情況下不改變,截取視頻長度通過改變value的值 //CMTimeMakeWithSeconds(Float64 seconds, int32_t preferredTimeScale),返回CMTime,seconds截取時長(單位秒),preferredTimeScale每秒幀數  //開始位置startTime CMTime startTime = CMTimeMakeWithSeconds(videoRange.location, videoAsset.duration.timescale); //截取長度videoDuration CMTime videoDuration = CMTimeMakeWithSeconds(videoRange.length, videoAsset.duration.timescale);  CMTimeRange videoTimeRange = CMTimeRangeMake(startTime, videoDuration);  //視頻采集compositionVideoTrack AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];  // 避免數組越界 tracksWithMediaType 找不到對應的文件時候返回空數組 //TimeRange截取的范圍長度 //ofTrack來源 //atTime插放在視頻的時間位置 [compositionVideoTrack insertTimeRange:videoTimeRange ofTrack:([videoAsset tracksWithMediaType:AVMediaTypeVideo].count>0) ? [videoAsset tracksWithMediaType:AVMediaTypeVideo].firstObject : nil atTime:kCMTimeZero error:nil];   //視頻聲音采集(也可不執行這段代碼不采集視頻音軌,合并后的視頻文件將沒有視頻原來的聲音)  AVMutableCompositionTrack *compositionVoiceTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];  [compositionVoiceTrack insertTimeRange:videoTimeRange ofTrack:([videoAsset tracksWithMediaType:AVMediaTypeAudio].count>0)?[videoAsset tracksWithMediaType:AVMediaTypeAudio].firstObject:nil atTime:kCMTimeZero error:nil];  //聲音長度截取范圍==視頻長度 CMTimeRange audioTimeRange = CMTimeRangeMake(kCMTimeZero, videoDuration);  //音頻采集compositionCommentaryTrack AVMutableCompositionTrack *compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];  [compositionAudioTrack insertTimeRange:audioTimeRange ofTrack:([audioAsset tracksWithMediaType:AVMediaTypeAudio].count > 0) ? [audioAsset tracksWithMediaType:AVMediaTypeAudio].firstObject : nil atTime:kCMTimeZero error:nil];  //AVAssetExportSession用于合并文件,導出合并后文件,presetName文件的輸出類型 AVAssetExportSession *assetExportSession = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetPassthrough];   //混合后的視頻輸出路徑 NSURL *outPutURL = [NSURL fileURLWithPath:outPath];  if ([[NSFileManager defaultManager] fileExistsAtPath:outPath]) {  [[NSFileManager defaultManager] removeItemAtPath:outPath error:nil]; }  //輸出視頻格式 assetExportSession.outputFileType = outputFileType; assetExportSession.outputURL = outPutURL; //輸出文件是否網絡優化 assetExportSession.shouldOptimizeForNetworkUse = YES; [assetExportSession exportAsynchronouslyWithCompletionHandler:^{    dispatch_async(dispatch_get_main_queue(), ^{      switch (assetExportSession.status) {    case AVAssetExportSessionStatusFailed:          if (_interceptBlock) {            _interceptBlock(assetExportSession.error,outPutURL);     }               break;         case AVAssetExportSessionStatusCancelled:{          logdebug(@"Export Status: Cancell");          break;    }    case AVAssetExportSessionStatusCompleted: {          if (_interceptBlock) {            _interceptBlock(nil,outPutURL);     }          break;    }    case AVAssetExportSessionStatusUnknown: {          logdebug(@"Export Status: Unknown");    }    case AVAssetExportSessionStatusExporting : {          logdebug(@"Export Status: Exporting");    }    case AVAssetExportSessionStatusWaiting: {          logdebug(@"Export Status: Wating");    }             }        });     }];}

第二步:本地視頻生成GIF圖

/** 生成GIF圖片 @param videoURL 視頻的路徑URL @param loopCount 播放次數 @param time 每幀的時間間隔 默認0.25s @param imagePath 存放GIF圖片的文件路徑 @param completeBlock 完成的回調 */ #pragma mark--制作GIF- (void)createGIFfromURL:(NSURL*)videoURL loopCount:(int)loopCount delayTime:(CGFloat )time gifImagePath:(NSString *)imagePath complete:(CompleteBlock)completeBlock {   _completeBlock =completeBlock;  float delayTime = time?:0.25;  // Create properties dictionaries NSDictionary *fileProperties = [self filePropertiesWithLoopCount:loopCount]; NSDictionary *frameProperties = [self framePropertiesWithDelayTime:delayTime];  AVURLAsset *asset = [AVURLAsset assetWithURL:videoURL];  float videoWidth = [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize].width; float videoHeight = [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize].height;  GIFSize optimalSize = GIFSizeMedium; if (videoWidth >= 1200 || videoHeight >= 1200)  optimalSize = GIFSizeVeryLow; else if (videoWidth >= 800 || videoHeight >= 800)  optimalSize = GIFSizeLow; else if (videoWidth >= 400 || videoHeight >= 400)  optimalSize = GIFSizeMedium; else if (videoWidth < 400|| videoHeight < 400)  optimalSize = GIFSizeHigh;  // Get the length of the video in seconds float videoLength = (float)asset.duration.value/asset.duration.timescale; int framesPerSecond = 4; int frameCount = videoLength*framesPerSecond;  // How far along the video track we want to move, in seconds. float increment = (float)videoLength/frameCount;  // Add frames to the buffer NSMutableArray *timePoints = [NSMutableArray array]; for (int currentFrame = 0; currentFrame<frameCount; ++currentFrame) {  float seconds = (float)increment * currentFrame;  CMTime time = CMTimeMakeWithSeconds(seconds, [timeInterval intValue]);  [timePoints addObject:[NSValue valueWithCMTime:time]]; }   //completion block NSURL *gifURL = [self createGIFforTimePoints:timePoints fromURL:videoURL fileProperties:fileProperties frameProperties:frameProperties gifImagePath:imagePath frameCount:frameCount gifSize:_gifSize?:GIFSizeMedium];  if (_completeBlock) {    // Return GIF URL  _completeBlock(_error,gifURL); }}

經過上面兩步,就可以生成本地的視頻和GIF圖了,存儲在沙盒即可。貼上兩步所用到的方法:

#pragma mark - Base methods- (NSURL *)createGIFforTimePoints:(NSArray *)timePoints fromURL:(NSURL *)url fileProperties:(NSDictionary *)fileProperties frameProperties:(NSDictionary *)frameProperties gifImagePath:(NSString *)imagePath frameCount:(int)frameCount gifSize:(GIFSize)gifSize{  NSURL *fileURL = [NSURL fileURLWithPath:imagePath]; if (fileURL == nil)  return nil; CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypeGIF , frameCount, NULL); CGImageDestinationSetProperties(destination, (CFDictionaryRef)fileProperties); AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil]; AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset]; generator.appliesPreferredTrackTransform = YES;  CMTime tol = CMTimeMakeWithSeconds([tolerance floatValue], [timeInterval intValue]); generator.requestedTimeToleranceBefore = tol; generator.requestedTimeToleranceAfter = tol;  NSError *error = nil; CGImageRef previousImageRefCopy = nil; for (NSValue *time in timePoints) {  CGImageRef imageRef;    #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR   imageRef = (float)gifSize/10 != 1 ? createImageWithScale([generator copyCGImageAtTime:[time CMTimeValue] actualTime:nil error:&error], (float)gifSize/10) : [generator copyCGImageAtTime:[time CMTimeValue] actualTime:nil error:&error];  #elif TARGET_OS_MAC   imageRef = [generator copyCGImageAtTime:[time CMTimeValue] actualTime:nil error:&error];  #endif    if (error) {      _error =error;   logdebug(@"Error copying image: %@", error);   return nil;     }  if (imageRef) {   CGImageRelease(previousImageRefCopy);   previousImageRefCopy = CGImageCreateCopy(imageRef);  } else if (previousImageRefCopy) {   imageRef = CGImageCreateCopy(previousImageRefCopy);  } else {      _error =[NSError errorWithDomain:NSStringFromClass([self class]) code:0 userInfo:@{NSLocalizedDescriptionKey:@"Error copying image and no previous frames to duplicate"}];   logdebug(@"Error copying image and no previous frames to duplicate");   return nil;  }  CGImageDestinationAddImage(destination, imageRef, (CFDictionaryRef)frameProperties);  CGImageRelease(imageRef); } CGImageRelease(previousImageRefCopy);  // Finalize the GIF if (!CGImageDestinationFinalize(destination)) {    _error =error;    logdebug(@"Failed to finalize GIF destination: %@", error);  if (destination != nil) {   CFRelease(destination);  }  return nil; } CFRelease(destination);  return fileURL;}#pragma mark - HelpersCGImageRef createImageWithScale(CGImageRef imageRef, float scale) {  #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR CGSize newSize = CGSizeMake(CGImageGetWidth(imageRef)*scale, CGImageGetHeight(imageRef)*scale); CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));  UIGraphicsBeginImageContextWithOptions(newSize, NO, 0); CGContextRef context = UIGraphicsGetCurrentContext(); if (!context) {  return nil; }  // Set the quality level to use when rescaling CGContextSetInterpolationQuality(context, kCGInterpolationHigh); CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);  CGContextConcatCTM(context, flipVertical); // Draw into the context; this scales the image CGContextDrawImage(context, newRect, imageRef);  //Release old image CFRelease(imageRef); // Get the resized image from the context and a UIImage imageRef = CGBitmapContextCreateImage(context);  UIGraphicsEndImageContext(); #endif  return imageRef;}#pragma mark - Properties- (NSDictionary *)filePropertiesWithLoopCount:(int)loopCount { return @{(NSString *)kCGImagePropertyGIFDictionary:    @{(NSString *)kCGImagePropertyGIFLoopCount: @(loopCount)}    };}- (NSDictionary *)framePropertiesWithDelayTime:(float)delayTime { return @{(NSString *)kCGImagePropertyGIFDictionary:    @{(NSString *)kCGImagePropertyGIFDelayTime: @(delayTime)},    (NSString *)kCGImagePropertyColorModel:(NSString *)kCGImagePropertyColorModelRGB   };}

最后,截取的本地視頻可用AVPlayer播放,生成的GIF圖則用UIWebView或者WKWebView又或者 YYImage 加載即可。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到IOS開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
亚洲天堂视频在线观看| 国内精品400部情侣激情| 亚洲乱码一区av黑人高潮| 国内精品400部情侣激情| 国产精品视频免费观看www| 日韩高清av一区二区三区| 国产精品草莓在线免费观看| 国产精品第一第二| 日韩av日韩在线观看| 国产成人精品国内自产拍免费看| 中文字幕国产日韩| 亚洲精品日产aⅴ| 亚洲男人天堂手机在线| 国产精品麻豆va在线播放| 国产精品美女免费看| 日韩动漫免费观看电视剧高清| 欧美成人激情视频| 亚洲肉体裸体xxxx137| 亚洲一区二区自拍| 不卡av电影院| 久久久国产一区| 国产精品av网站| 日韩免费av一区二区| 清纯唯美亚洲激情| 91精品国产成人| 欧美日韩一区二区三区在线免费观看| 国产精品色视频| 精品成人国产在线观看男人呻吟| 91精品国产777在线观看| 欧美日韩免费在线观看| 亚洲一区制服诱惑| 日韩在线观看av| 久久97精品久久久久久久不卡| 91在线中文字幕| 亚洲人成电影网站色xx| 欧美日韩免费观看中文| 91av福利视频| 久久国产精品久久久久久久久久| 国产成人欧美在线观看| 国产精品露脸自拍| 国产91精品最新在线播放| 日韩精品中文字幕在线观看| 亚洲欧美国产va在线影院| 黄色精品一区二区| 91国产一区在线| 久久在线观看视频| 高清日韩电视剧大全免费播放在线观看| 精品久久久久人成| 欧美大片在线影院| 欧美大秀在线观看| 亚洲福利视频网| 久久精品小视频| 亚洲在线视频观看| 欧美极品欧美精品欧美视频| 亚洲国产精品中文| 国产精品一区二区三区成人| 国产精品三级久久久久久电影| 成人在线免费观看视视频| 国产中文日韩欧美| 日韩中文字幕在线播放| 欧美成年人在线观看| 91美女福利视频高清| 97精品一区二区三区| 92看片淫黄大片欧美看国产片| 日本久久精品视频| 九九九热精品免费视频观看网站| 欧美日韩成人在线播放| 国产精品日韩在线一区| 国产日韩中文字幕| 亚洲欧美制服丝袜| 欧美黄色片视频| 欧美肥老太性生活视频| 欧美日韩亚洲一区二区| 国产精品久久久久久超碰| 精品女厕一区二区三区| 亚洲欧洲国产精品| 国产精品自拍偷拍视频| 午夜精品理论片| 午夜精品www| 久久精品国产免费观看| 精品色蜜蜜精品视频在线观看| 欧美日韩在线免费| 国产精品一区二区久久久久| 一区二区三区美女xx视频| 国产成人一区二区三区小说| 久久九九全国免费精品观看| 亚洲精品色婷婷福利天堂| 日韩美女av在线免费观看| 正在播放欧美视频| 国产区亚洲区欧美区| 精品国产一区二区在线| 日本人成精品视频在线| 国产亚洲欧美aaaa| 久国内精品在线| 久久视频这里只有精品| 好吊成人免视频| 粗暴蹂躏中文一区二区三区| 欧美成人免费一级人片100| 国产91精品高潮白浆喷水| 琪琪亚洲精品午夜在线| 成人精品福利视频| 狠狠躁夜夜躁人人爽天天天天97| 亚洲奶大毛多的老太婆| 欧美在线播放视频| 久久影院资源站| 日韩成人在线视频| 69久久夜色精品国产69| 91成人国产在线观看| 国产精品美女免费视频| 曰本色欧美视频在线| 久久久久久久国产| 亚洲综合在线播放| 国产精品视频成人| 欧美老少做受xxxx高潮| 亚洲另类xxxx| 国产91在线高潮白浆在线观看| 久久精品国亚洲| 国产精品久久久久久久久久新婚| 国产成人精品网站| 欧美成人中文字幕在线| 国产精品福利在线| 91精品国产免费久久久久久| 日本道色综合久久影院| 国产欧美精品一区二区三区介绍| 欧美一区二区三区精品电影| 亚洲国产成人精品一区二区| 91精品国产色综合久久不卡98| 91国产美女视频| 欧美午夜精品久久久久久浪潮| 欧美激情在线一区| 欧美激情图片区| 丝袜一区二区三区| 亚洲性无码av在线| 狠狠综合久久av一区二区小说| 国产午夜精品美女视频明星a级| 精品在线欧美视频| 精品久久久香蕉免费精品视频| 国产精品久久久久久久av大片| 日韩av在线直播| 久久99久久亚洲国产| 日韩免费在线播放| 久久亚洲精品中文字幕冲田杏梨| 中文字幕日韩免费视频| 国模精品视频一区二区三区| 欧美精品激情在线| 日韩资源在线观看| 日韩欧美综合在线视频| 亚洲欧美色图片| 欧美日韩黄色大片| 欧洲精品在线视频| 国产精品91在线| 久久免费精品视频| 亚洲精品美女免费| 日韩女在线观看| 国产午夜精品全部视频播放| 亚洲精品456在线播放狼人| 亚洲精品动漫100p| 欧美精品亚州精品| 日韩欧美在线第一页| 亚洲欧洲成视频免费观看| 中文字幕亚洲欧美| 成人免费视频xnxx.com| 精品久久久久久久大神国产| 亚洲欧美制服第一页|