您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

iOS 影片轉碼:將 mov 轉換為 MP4

編輯:iOS 程式設計技術

下面記錄一段將 mov 影片轉碼為 MP4 的實作,方便日後查閱,避免遺忘。

#import <AVFoundation/AVFoundation.h>

- (void)movToMP4:(NSString *)path completionHandler:(void(^)(NSURL * URL))finalUrl {

     // path 為檔案存放路徑

    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 %@", 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(@"轉換成功");

                    finalUrl(exportSession.outputURL);

                }

                break;

              default:

                break;

            }

        }];

    }

}

這段程式碼的核心思路是:先以 AVURLAsset 載入原始影片,接著用 AVAssetExportSession 建立轉碼工作階段,把輸出格式指定為 AVFileTypeMPEG4,最後透過非同步匯出並在完成回呼中依狀態處理成功、失敗與取消三種情況。隨手記下,以備不時之需。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved