Val*_*lle 5 audio video nsurlconnection ios
我管理它使用NSUrlConnection下载YouTube视频并将其保存到设备.现在我想将此(我猜.mp4)文件转换为.mp3音频文件.有谁知道这个问题的解决方案?也许有办法只从视频中下载音频?这将节省大量时间.
首先,你不想转换任何东西,这很慢.而是想要从mp4文件中提取音频流.您可以通过创建AVMutableComposition仅包含原始文件的音轨,然后使用a导出合成来完成此操作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");
}
}];
Run Code Online (Sandbox Code Playgroud)