2016-01-03 94 views

回答

3

可能有不止一種方式,但AVAssetExportSession很簡單,有效。

N.B.這會創建一個新文件。 AVFoundation並不是真的就地修改。

#import <AVFoundation/AVFoundation.h> 
#import <CoreMedia/CoreMedia.h> 

// ... 

NSURL *outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/output.m4a", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]]]; 
[[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil]; 

NSURL *inputURL = [[NSBundle mainBundle] URLForResource:@"foo" withExtension:@"m4a"]; 
AVAsset *asset = [AVAsset assetWithURL:inputURL]; 

AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetPassthrough]; 
session.outputURL = outputURL; 
session.outputFileType = AVFileTypeAppleM4A; 

AVMutableMetadataItem *metaTitle = [[AVMutableMetadataItem alloc] init]; 

metaTitle.identifier = AVMetadataCommonIdentifierTitle;      // more in AVMetadataIdentifiers.h 
metaTitle.dataType = (__bridge NSString *)kCMMetadataBaseDataType_UTF8;  // more in CoreMedia/CMMetadata.h 
metaTitle.value = @"Choon!"; 

AVMutableMetadataItem *metaArtist = [[AVMutableMetadataItem alloc] init]; 
metaArtist.identifier = AVMetadataCommonIdentifierArtist; 
metaArtist.dataType = (__bridge NSString *)kCMMetadataBaseDataType_UTF8; 
metaArtist.value = @"Me, of course"; 

session.metadata = @[metaTitle, metaArtist]; 

[session exportAsynchronouslyWithCompletionHandler:^{ 
    if (session.status == AVAssetExportSessionStatusCompleted) { 
     // hurray 
    } 
}]; 

這個例子是m4a文件,你需要改變文件擴展名mp4outputFileTypeAVFileTypeMPEG4