本文用一個最小可用的 Demo 演示「錄製視頻 / 從相冊選視頻 / 保存到相冊 / 抽幀取封面 / 壓縮導出」這一整套流程,UI 提示部分用了 SVProgressHUD。
要特別提醒的是:從 iOS 10 開始,凡是要訪問設備能力的接口都必須先在 Info.plist 裡聲明用途說明,否則 App 一調用就會直接崩潰。這一步不做,後面所有代碼都白寫。
兩個按鈕,一個走相機錄製,一個走相冊挑選:
static NSString *const AssetCollectionName = @"錄制視頻";
- (void)createBtn {
UIButton *recordBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
[recordBtn setTitle:@"開始錄制" forState:UIControlStateNormal];
recordBtn.backgroundColor = [UIColor lightGrayColor];
[recordBtn addTarget:self action:@selector(videoFromCamera) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:recordBtn];
UIButton *selectBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 250, 100, 100)];
[selectBtn setTitle:@"選擇視頻" forState:UIControlStateNormal];
selectBtn.backgroundColor = [UIColor lightGrayColor];
[selectBtn addTarget:self action:@selector(videoFromPhotos) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:selectBtn];
}
- (void)videoFromCamera {
[self getVideoWithSourceType:UIImagePickerControllerSourceTypeCamera shouldAsync:YES];
}
- (void)videoFromPhotos {
[self getVideoWithSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum shouldAsync:NO];
}
UIImagePickerController 至今仍是「快速拉起相機錄一段視頻」最省事的方案。打開之前先確認授權狀態,被拒絕就引導用戶去系統設置裡打開:
- (void)getVideoWithSourceType:(UIImagePickerControllerSourceType)type
shouldAsync:(BOOL)shouldAsync {
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
[SVProgressHUD showInfoWithStatus:@"請到 [設置]-[隱私]-[相機] 中允許本 App 訪問"];
return;
}
if (![UIImagePickerController isSourceTypeAvailable:type]) {
[SVProgressHUD showInfoWithStatus:@"設備不支持該來源"];
return;
}
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = type;
picker.mediaTypes = @[(NSString *)kUTTypeMovie];
[self presentViewController:picker animated:YES completion:NULL];
self.shouldAsync = shouldAsync;
}
在動手保存之前,先理清 iOS 相冊相關的幾個概念,這也是很多老項目代碼混亂的根源:
UIImageWriteToSavedPhotosAlbum,也可以用 AssetsLibrary(iOS 9 起已廢棄),或者 Photos.framework(iOS 8 起可用,iOS 9 之後完全取代 AssetsLibrary)。Photos 框架裡兩個核心對象:PHAsset 代表一張圖片或一段視頻;PHAssetCollection 代表一本相冊。所有修改操作都必須包在 PHAssetChangeRequest 裡,並放進下面兩個方法的 block 中執行:
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:completionHandler:]; [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:error:];
iOS 9 之前用 ALAssetsLibrary,之後改用 PHPhotoLibrary。這裡保留兩套分支,方便理解老項目的遷移路徑。
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:videoUrl]) {
[library writeVideoAtPathToSavedPhotosAlbum:videoUrl completionBlock:^(NSURL *assetURL, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
[SVProgressHUD showInfoWithStatus:@"保存視頻失敗"];
} else {
[SVProgressHUD showInfoWithStatus:@"保存視頻成功"];
}
});
}];
}
});
思路是:先存進膠卷拿到 localIdentifier,再查找(或創建)名為「錄制視頻」的自定義相冊,最後把剛存進去的資源添加進去。
PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
dispatch_async(dispatch_get_main_queue(), ^{
NSError *error = nil;
__block NSString *assetId = nil;
__block NSString *assetCollectionId = nil;
// 1. 存入相機膠卷
[library performChangesAndWait:^{
assetId = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoUrl]
.placeholderForCreatedAsset.localIdentifier;
} error:&error];
// 2. 查找已有的自定義相冊
PHAssetCollection *createdAssetCollection = nil;
PHFetchResult *assetCollections = [PHAssetCollection
fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
subtype:PHAssetCollectionSubtypeAlbumRegular
options:nil];
for (PHAssetCollection *collection in assetCollections) {
if ([collection.localizedTitle isEqualToString:AssetCollectionName]) {
createdAssetCollection = collection;
break;
}
}
// 3. 沒找到就新建一本
if (createdAssetCollection == nil) {
[library performChangesAndWait:^{
assetCollectionId = [PHAssetCollectionChangeRequest
creationRequestForAssetCollectionWithTitle:AssetCollectionName]
.placeholderForCreatedAssetCollection.localIdentifier;
} error:&error];
createdAssetCollection = [PHAssetCollection
fetchAssetCollectionsWithLocalIdentifiers:@[assetCollectionId]
options:nil].firstObject;
}
// 4. 把視頻加入自定義相冊
[library performChangesAndWait:^{
PHAssetCollectionChangeRequest *request =
[PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdAssetCollection];
[request addAssets:[PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil]];
} error:&error];
if (error) {
[SVProgressHUD showErrorWithStatus:@"保存視頻失敗!"];
} else {
[SVProgressHUD showSuccessWithStatus:@"保存視頻成功!"];
}
});
[picker dismissViewControllerAnimated:YES completion:^{
// 修正 iOS 8 打開相機後 tabBar 坐標錯位的問題
self.tabBarController.view.frame = [[UIScreen mainScreen] bounds];
[self.tabBarController.view layoutIfNeeded];
}];
關鍵類是 AVAssetImageGenerator。這裡有個實務細節值得說明:蘋果文檔建議 timeScale 取 600,因為常見的 24fps(電影)、30fps(NTSC)、25fps(PAL)都能用它整除,可以精確表示任意幀。
另外 copyCGImageAtTime:actualTime:error: 返回的是 CFRetained 的 CGImageRef,必須自己調用 CGImageRelease 釋放,否則就是內存洩露。
- (UIImage *)frameImageFromVideoURL:(NSURL *)videoURL {
AVAsset *asset = [AVAsset assetWithURL:videoURL];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform = YES;
Float64 duration = CMTimeGetSeconds([asset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(duration / 2.0, 600);
NSError *error = nil;
CMTime actualTime;
CGImageRef centerFrameImage = [generator copyCGImageAtTime:midpoint
actualTime:&actualTime
error:&error];
if (centerFrameImage != NULL) {
UIImage *image = [[UIImage alloc] initWithCGImage:centerFrameImage];
CGImageRelease(centerFrameImage);
return image;
}
return nil;
}
異步版本的好處是可以一次請求多個時間點,逐幀回調,適合做視頻預覽條:
- (void)centerFrameImageWithVideoURL:(NSURL *)videoURL
completion:(void (^)(UIImage *image))completion {
AVAsset *asset = [AVAsset assetWithURL:videoURL];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform = YES;
Float64 duration = CMTimeGetSeconds([asset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(duration / 2.0, 600);
NSValue *midTime = [NSValue valueWithCMTime:midpoint];
[generator generateCGImagesAsynchronouslyForTimes:@[midTime]
completionHandler:^(CMTime requestedTime,
CGImageRef image,
CMTime actualTime,
AVAssetImageGeneratorResult result,
NSError *error) {
UIImage *frameImage = nil;
if (result == AVAssetImageGeneratorSucceeded && image != NULL) {
frameImage = [[UIImage alloc] initWithCGImage:image];
}
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) { completion(frameImage); }
});
}];
}
設備原生素質越來越高,一段十幾秒的視頻动辄幾十兆,上傳前壓縮基本是標配。AVAssetExportSession 會先查詢當前素材支持的預設檔位,再選一個合適的開始異步導出。
- (void)compressVideoWithVideoURL:(NSURL *)videoURL
savedName:(NSString *)savedName
completion:(void (^)(NSString *savedPath))completion {
AVURLAsset *videoAsset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
NSArray *presets = [AVAssetExportSession exportPresetsCompatibleWithAsset:videoAsset];
if (![presets containsObject:AVAssetExportPreset640x480]) { return; }
AVAssetExportSession *session = [[AVAssetExportSession alloc]
initWithAsset:videoAsset presetName:AVAssetExportPreset640x480];
// 沙盒路徑:Documents/錄制視頻
NSString *doc = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *folder = [doc stringByAppendingPathComponent:@"錄制視頻"];
BOOL isDir = NO;
BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:folder isDirectory:&isDir];
if (!isExist || (isExist && !isDir)) {
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:folder
withIntermediateDirectories:YES
attributes:nil
error:&error];
if (error) {
[SVProgressHUD showInfoWithStatus:@"目錄創建失敗"];
return;
}
}
session.outputURL = [NSURL fileURLWithPath:[folder stringByAppendingPathComponent:savedName]];
session.shouldOptimizeForNetworkUse = YES;
NSArray *supportedTypes = session.supportedFileTypes;
if ([supportedTypes containsObject:AVFileTypeMPEG4]) {
session.outputFileType = AVFileTypeMPEG4;
} else if (supportedTypes.count == 0) {
[SVProgressHUD showInfoWithStatus:@"沒有可用的輸出格式"];
return;
} else {
session.outputFileType = [supportedTypes objectAtIndex:0];
}
[session exportAsynchronouslyWithCompletionHandler:^{
NSString *path = (session.status == AVAssetExportSessionStatusCompleted)
? [session.outputURL path] : nil;
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) { completion(path); }
});
}];
}
didFinishPickingMediaWithInfo: 與 imagePickerControllerDidCancel:sourceType 決定來源,allowsEditing 決定是否允許編輯isSourceTypeAvailable:、isCameraDeviceAvailable:、isFlashAvailableForCameraDevice:info 字典裡最常用的是 UIImagePickerControllerMediaURL(媒體地址)與 UIImagePickerControllerReferenceURL(原圖地址)mediaTypes 決定能選什麼:kUTTypeImage 走圖片,kUTTypeMovie 走視頻,也可用 kUTTypeMPEG4、kUTTypeVideo 等更具體的類型整套流程串起來並不複雜,真正的坑集中在兩處:一是 iOS 10 之後必須補全 Info.plist 的用途說明,二是 CGImageRef 這類 Core Media 對象需要手動釋放。把這兩點照顧到,錄像功能就能穩定跑起來。