简体   繁体   中英

How to extract and save audio from a .mp4 file

I am having a bit of trouble saving an audio file of a .mp4 file. The following code does not seem to be working.

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *audioPath = [documentsDirectory stringByAppendingPathComponent:@"soundOneNew.m4a"];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:full_url options:nil];
AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetPassthrough];
exportSession.outputURL = [NSURL fileURLWithPath:audioPath];
exportSession.outputFileType = AVFileTypeAppleM4A;
CMTime vocalStartMarker = kCMTimeZero;
CMTime vocalEndMarker = exportSession.asset.duration;
CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(vocalStartMarker, vocalEndMarker);

//supported file types
NSArray *supportedTypeArray = exportSession.supportedFileTypes;

for (NSString *str in supportedTypeArray){
    NSLog(@"Supported file types  : %@",str);
}

exportSession.timeRange = exportTimeRange;
if ([[NSFileManager defaultManager] fileExistsAtPath:audioPath]) {
    [[NSFileManager defaultManager] removeItemAtPath:audioPath error:nil];
}
NSLog(@"Audio Path %@", audioPath);
[exportSession exportAsynchronouslyWithCompletionHandler:^{
    if (exportSession.status == AVAssetExportSessionStatusFailed) {
        NSLog(@"Audio export failed");
    }
    else {
        NSLog(@"AudioLocation : %@",audioPath);
    }
}];

At the end of the execution I won't be getting an audio file in the specified directory.

You're trying to write a video file to an audio file. Either read the audio track from the source video file and write it out using AVAssetReader + AVAssetWriter , or instead create an AVMutableComposition with the audio track from the source video inserted into an AVMutableCompositionTrack and then use the export session as you have it set up there, but with the composition as the asset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM