Search code examples
iosobjective-ctagsm4a

Editing metatags of mp4 / m4a files


I want to edit the Title and the Author tag on a mp4 / m4a file with ObjC for iOS.

Is this possible?


Solution

  • There's probably more than one way, but AVAssetExportSession is simple and works.

    N.B. This creates a new file. AVFoundation doesn't really do in place modifications.

    #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
        }
    }];
    

    This example is for m4a files, you'll need to change the file extensions to mp4 and outputFileType to AVFileTypeMPEG4.