iOS 在線視頻生成GIF圖功能

在一些視頻APP中,都可以看到一個將在線視頻轉(zhuǎn)成GIF圖的功能。下面就來說說思路以及實現(xiàn)尊搬。我們知道本地視頻可以生成GIF,那么將在線視頻截取成本地視頻不就可以了嗎?經(jīng)過比較土涝,騰訊視頻App也是這么做的佛寿。話不多說,下面開始上代碼:
第一步:截取視頻

#pragma mark -截取視頻
/**
  @param videoUrl 視頻的URL
 @param outPath 輸出路徑
 @param outputFileType 輸出視頻格式
 @param videoRange 截取視頻的范圍
 @param completeBlock 視頻截取的回調(diào)
 */
- (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];
   
    //創(chuàng)建AVMutableComposition對象來添加視頻音頻資源的AVMutableCompositionTrack
    AVMutableComposition* mixComposition = [AVMutableComposition composition];
    
    //CMTimeRangeMake(start, duration),start起始時間,duration時長茵肃,都是CMTime類型
    //CMTimeMake(int64_t value, int32_t timescale)腔长,返回CMTime,value視頻的一個總幀數(shù)验残,timescale是指每秒視頻播放的幀數(shù)捞附,視頻播放速率,(value / timescale)才是視頻實際的秒數(shù)時長您没,timescale一般情況下不改變鸟召,截取視頻長度通過改變value的值
    //CMTimeMakeWithSeconds(Float64 seconds, int32_t preferredTimeScale),返回CMTime氨鹏,seconds截取時長(單位秒)欧募,preferredTimeScale每秒幀數(shù)
    
    //開始位置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];
    
    // 避免數(shù)組越界 tracksWithMediaType 找不到對應(yīng)的文件時候返回空數(shù)組
    //TimeRange截取的范圍長度
    //ofTrack來源
    //atTime插放在視頻的時間位置
    [compositionVideoTrack insertTimeRange:videoTimeRange ofTrack:([videoAsset tracksWithMediaType:AVMediaTypeVideo].count>0) ? [videoAsset tracksWithMediaType:AVMediaTypeVideo].firstObject : nil atTime:kCMTimeZero error:nil];
    
    
    //視頻聲音采集(也可不執(zhí)行這段代碼不采集視頻音軌,合并后的視頻文件將沒有視頻原來的聲音)
    
    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用于合并文件仆抵,導(dǎo)出合并后文件跟继,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];
    }
    
    //輸出視頻格式 outputFileType:mov或mp4及其它視頻格式
    assetExportSession.outputFileType = outputFileType;
    assetExportSession.outputURL = outPutURL;
    //輸出文件是否網(wǎng)絡(luò)優(yōu)化
    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圖

 #pragma mark--制作GIF
/** 
@param videoURL 視頻的路徑URL
 @param loopCount 播放次數(shù) 0即無限循環(huán) 
 @param time 每幀的時間間隔 默認(rèn)0.25s
 @param imagePath 存放GIF圖片的文件路徑
 @param completeBlock 完成的回調(diào)
*/
- (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);
    }

}

經(jīng)過上面兩步,就可以生成本地的視頻和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 - Helpers

CGImageRef 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加載即可金吗。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子摇庙,更是在濱河造成了極大的恐慌旱物,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件跟匆,死亡現(xiàn)場離奇詭異异袄,居然都是意外死亡,警方通過查閱死者的電腦和手機玛臂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門烤蜕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人迹冤,你說我怎么就攤上這事讽营。” “怎么了泡徙?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵橱鹏,是天一觀的道長。 經(jīng)常有香客問我堪藐,道長莉兰,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任礁竞,我火速辦了婚禮糖荒,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘模捂。我一直安慰自己捶朵,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布狂男。 她就那樣靜靜地躺著综看,像睡著了一般。 火紅的嫁衣襯著肌膚如雪岖食。 梳的紋絲不亂的頭發(fā)上红碑,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天,我揣著相機與錄音泡垃,去河邊找鬼析珊。 笑死,一個胖子當(dāng)著我的面吹牛兔毙,可吹牛的內(nèi)容都是我干的唾琼。 我是一名探鬼主播兄春,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼澎剥,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起哑姚,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤祭饭,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后叙量,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體倡蝙,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年绞佩,在試婚紗的時候發(fā)現(xiàn)自己被綠了寺鸥。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡品山,死狀恐怖胆建,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情肘交,我是刑警寧澤笆载,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站涯呻,受9級特大地震影響凉驻,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜复罐,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一涝登、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧市栗,春花似錦缀拭、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至篡腌,卻和暖如春褐荷,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背嘹悼。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工叛甫, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人杨伙。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓其监,卻偏偏與公主長得像,于是被迫代替她去往敵國和親限匣。 傳聞我的和親對象是個殘疾皇子抖苦,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,724評論 2 354