之前有个要选取本地音乐混音的功能,要读取本地库的音乐,发现取到的路径是系统处理过的路径,不能直接用, 在网上找了一些资料,有些是将item写成nsdata到沙盒,不过没找到能用的,最后发现其实用AVAssetExportSessionexport直接导出就行,真魔性
- (void) convertToMp3: (MPMediaItem*)song
{
NSURL*url = [songvalueForProperty:MPMediaItemPropertyAssetURL];
AVURLAsset*songAsset = [AVURLAssetURLAssetWithURL:urloptions:nil];
NSFileManager*fileManager = [NSFileManagerdefaultManager];
NSArray*dirs =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*documentsDirectoryPath = [dirsobjectAtIndex:0];
NSLog(@"compatible presets for songAsset: %@",[AVAssetExportSessionexportPresetsCompatibleWithAsset:songAsset]);
NSArray*ar = [AVAssetExportSessionexportPresetsCompatibleWithAsset: songAsset];
NSLog(@"%@", ar);
AVAssetExportSession*exporter = [[AVAssetExportSessionalloc]
initWithAsset: songAsset
presetName:AVAssetExportPresetAppleM4A];
NSLog(@"created exporter. supportedFileTypes: %@", exporter.supportedFileTypes);
exporter.outputFileType=@"com.apple.m4a-audio";
NSString*exportFile = [documentsDirectoryPathstringByAppendingPathComponent:[NSStringstringWithFormat:@"%@.m4a",[songvalueForProperty:MPMediaItemPropertyTitle]]];
NSError*error1;
if([fileManagerfileExistsAtPath:exportFile])
{
[fileManagerremoveItemAtPath:exportFileerror:&error1];
}
urlPath= [NSURLfileURLWithPath:exportFile];
exporter.outputURL=urlPath;
NSLog(@"---------%@",urlPath);
// do the export
[exporterexportAsynchronouslyWithCompletionHandler:^
{
NSData*data1 = [NSDatadataWithContentsOfFile:exportFile];
NSLog(@"==================data1:%@",data1);
intexportStatus = exporter.status;
switch(exportStatus) {
caseAVAssetExportSessionStatusFailed: {
// log error to text view
NSError*exportError = exporter.error;
NSLog(@"AVAssetExportSessionStatusFailed: %@", exportError);
break;
}
caseAVAssetExportSessionStatusCompleted: {
NSLog(@"AVAssetExportSessionStatusCompleted");
break;
}
caseAVAssetExportSessionStatusUnknown: {
NSLog(@"AVAssetExportSessionStatusUnknown");
break;
}
caseAVAssetExportSessionStatusExporting: {
NSLog(@"AVAssetExportSessionStatusExporting");
break;
}
caseAVAssetExportSessionStatusCancelled: {
NSLog(@"AVAssetExportSessionStatusCancelled");
break;
}
caseAVAssetExportSessionStatusWaiting: {
NSLog(@"AVAssetExportSessionStatusWaiting");
break;
}
default:
{NSLog(@"didn't get export status");
break;
}
}
}];
}
网友评论