我设法使用NSUrlConnection下载YouTube视频并将其保存到设备中。现在我想将此(我猜.mp4)文件转换为.mp3音频文件。有谁知道这个问题的解决方案?也许有办法只从视频中下载音频?这样可以节省很多时间。
答案 0 :(得分:5)
首先,你不想转换任何东西,这很慢。而是想要从mp4文件中提取音频流。您可以通过创建仅包含原始文件的音轨的AVMutableComposition
,然后使用AVAssetExportSession
导出合成来执行此操作。这是目前以m4a为中心的。如果要同时处理m4a和mp3输出,请检查音轨类型,确保设置正确的文件扩展名,并在导出会话中选择AVFileTypeMPEGLayer3
或AVFileTypeAppleM4A
。
NSURL* dstURL = [NSURL fileURLWithPath:dstPath];
[[NSFileManager defaultManager] removeItemAtURL:dstURL error:nil];
AVMutableComposition* newAudioAsset = [AVMutableComposition composition];
AVMutableCompositionTrack* dstCompositionTrack;
dstCompositionTrack = [newAudioAsset addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
AVAsset* srcAsset = [AVURLAsset URLAssetWithURL:srcURL options:nil];
AVAssetTrack* srcTrack = [[srcAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
CMTimeRange timeRange = srcTrack.timeRange;
NSError* error;
if(NO == [dstCompositionTrack insertTimeRange:timeRange ofTrack:srcTrack atTime:kCMTimeZero error:&error]) {
NSLog(@"track insert failed: %@\n", error);
return;
}
AVAssetExportSession* exportSesh = [[AVAssetExportSession alloc] initWithAsset:newAudioAsset presetName:AVAssetExportPresetPassthrough];
exportSesh.outputFileType = AVFileTypeAppleM4A;
exportSesh.outputURL = dstURL;
[exportSesh exportAsynchronouslyWithCompletionHandler:^{
AVAssetExportSessionStatus status = exportSesh.status;
NSLog(@"exportAsynchronouslyWithCompletionHandler: %i\n", status);
if(AVAssetExportSessionStatusFailed == status) {
NSLog(@"FAILURE: %@\n", exportSesh.error);
} else if(AVAssetExportSessionStatusCompleted == status) {
NSLog(@"SUCCESS!\n");
}
}];