前一段時間剛剛做了一個短視頻功能,然后今天給小伙伴們分享視頻裁剪這一塊的代碼,今天時間比較緊,我就直接把工具類的代碼分享給小伙伴們吧,哪里不理解的可以在下面留言給我
視頻裁剪
- SHMediaManager.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface SHMediaManager : NSObject
+ (void)cropWithVideoUrlStr:(NSURL *)videoUrl start:(CGFloat)startTime end:(CGFloat)endTime completion:(void (^)(NSURL *outputURL, Float64 videoDuration, BOOL isSuccess))completionHandle;
@end
注:這里videoUrl參數(shù)是本地視頻文件的路徑
- SHMediaManager.m
#import "SHMediaManager.h"
#import <AVFoundation/AVFoundation.h>
@implementation SHMediaManager
+ (void)cropWithVideoUrlStr:(NSURL *)videoUrl start:(CGFloat)startTime end:(CGFloat)endTime completion:(void (^)(NSURL *outputURL, Float64 videoDuration, BOOL isSuccess))completionHandle
{
AVURLAsset *asset =[[AVURLAsset alloc] initWithURL:videoUrl options:nil];
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString *outputFilePath = [NSString stringWithFormat:@"%@/%@.mp4", docDirPath , [self getCurrentTime]];
NSURL *outputFileUrl = [NSURL fileURLWithPath:outputFilePath];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:asset];
if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality])
{
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
initWithAsset:asset presetName:AVAssetExportPresetPassthrough];
NSURL *outputURL = outputFileUrl;
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.shouldOptimizeForNetworkUse = YES;
CMTime start = CMTimeMakeWithSeconds(startTime, asset.duration.timescale);
CMTime duration = CMTimeMakeWithSeconds(endTime,asset.duration.timescale);
CMTimeRange range = CMTimeRangeMake(start, duration);
exportSession.timeRange = range;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed:
{
NSLog(@"合成失?。?@", [[exportSession error] description]);
completionHandle(outputURL, endTime, NO);
}
break;
case AVAssetExportSessionStatusCancelled:
{
completionHandle(outputURL, endTime, NO);
}
break;
case AVAssetExportSessionStatusCompleted:
{
completionHandle(outputURL, endTime, YES);
}
break;
default:
{
completionHandle(outputURL, endTime, NO);
} break;
}
}];
}
}
//獲取當前時間
+ (NSString *)getCurrentTime {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateTime = [formatter stringFromDate:[NSDate date]];
return dateTime;
}
@end
注:以上block回調(diào)的方式比較簡單,小伙伴們可以按照自己的需求進行更改,例如添加一個裁剪失敗報錯的block回調(diào)等