在 iOS 上錄製或匯入的影片多半是 MOV 格式,但若要上傳、分享或嵌入網頁,MP4 往往更通用。AVFoundation 提供的 AVAssetExportSession 就是處理這件事最直接的工具:你只要給它一個 AVURLAsset、指定輸出路徑與檔案型別,剩下的編碼工作它會在背景執行。
實作上要先檢查裝置是否支援該 preset,再把 exportSession 的 outputURL 與 outputFileType 設為 MP4,最後非同步匯出並在 completion handler 中處理三種狀態(成功、失敗、取消)。輸出路徑這裡寫在 App 的 tmp 目錄下,實務上請依需求替換。
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:path]
options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality]) {
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
initWithAsset:avAsset
presetName:AVAssetExportPresetPassthrough];
NSString *exportPath = [NSString stringWithFormat:@"%@/%@.mp4",
[NSHomeDirectory() stringByAppendingString:@"/tmp"], @"1"];
exportSession.outputURL = [NSURL fileURLWithPath:exportPath];
NSLog(@"%@", exportPath);
exportSession.outputFileType = AVFileTypeMPEG4;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed:
NSLog(@"Export failed: %@",
[[exportSession error] localizedDescription]);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(@"Export canceled");
break;
case AVAssetExportSessionStatusCompleted:
NSLog(@"轉換成功");
break;
default:
break;
}
}];
}
幾個實務上的提醒:exportAsynchronouslyWithCompletionHandler 是非同步的,回呼可能在背景執行緒觸發,若要更新 UI 記得切回主執行緒;presetName 若改成 AVAssetExportPresetPassthrough 以外的選項(例如 MediumQuality),輸出畫質與檔案大小會隨之改變;另外輸出檔名若固定不動,記得在寫檔前處理同名檔案的覆蓋或清理問題。