如何从.mp4文件中提取和保存音频

时间:2014-10-13 08:05:21

标签: ios avfoundation avassetexportsession

我在保存.mp4文件的音频文件时遇到了一些麻烦。以下代码似乎不起作用。

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

在执行结束时,我将不会在指定目录中获取音频文件。

1 个答案:

答案 0 :(得分:0)

您正在尝试将视频文件写入音频文件。从源视频文件中读取音轨并使用AVAssetReader + AVAssetWriter将其写出,或者创建一个AVMutableComposition,其中源视频中的音轨插入{{1}然后使用导出会话,因为它在那里设置,但组成为资产。