我设法使用NSUrlConnection下载youtube视频并将其保存到设备中。现在,我想将此文件(我想是.mp4)转换为.mp3音频文件。有人知道这个问题的解决方案吗?也许有一种方法只能从视频中下载音频?这样可以节省大量时间。
首先,您不想转换任何东西,那很慢。相反,您想从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");
}
}];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句