从apple music“音乐”里面导出音乐列表
1.引入头文件
<MediaPlayer/MediaPlayer.h>
2.获取音乐列表
// 创建媒体选择队列
MPMediaQuery *query = [[MPMediaQuery alloc] init];
// 创建读取条件
MPMediaPropertyPredicate *albumNamePredicate = [MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithInt:MPMediaTypeMusic] forProperty:MPMediaItemPropertyMediaType];
// 给队列添加读取条件
[queryaddFilterPredicate:albumNamePredicate];
// 从队列中获取条件的数组集合
NSArray*itemsFromGenericQuery = [queryitems];
// 遍历解析数据
NSMutableArray *musicAry = [[NSMutableArray alloc] init];
for(MPMediaItem*musicinitemsFromGenericQuery) {
[selfresolverMediaItem:music];
}
3.通过music获取歌曲信息和下载在本地的歌曲地址
NSMutableDictionary *musicInfoJson = [NSMutableDictionary dictionary];
NSString *songID = [music valueForProperty:MPMediaItemPropertyPersistentID];//歌曲编号
NSString *songTitle = [music valueForProperty:MPMediaItemPropertyTitle];//歌曲名称
NSString *albumName = [music valueForProperty:MPMediaItemPropertyAlbumTitle];//专辑名称
NSString *artistName = [music valueForProperty:MPMediaItemPropertyArtist];//歌手名称
NSURL *fileUrl = [music valueForProperty:MPMediaItemPropertyAssetURL];//文件路径
NSNumber *duration = [music valueForProperty:MPMediaItemPropertyPlaybackDuration];//歌曲时长
MPMediaItemArtwork *artwork = [music valueForProperty:MPMediaItemPropertyArtwork];//封面图片
UIImage*artworkImg;
NSString*artworkImgStr =@"";
if(artwork){
artworkImg = [artworkimageWithSize:CGSizeMake(72,72)];
}
NSString*filePath = [fileUrlabsoluteString];//文件路径
3.导出music到沙盒路径
NSString * appDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
NSString*newPath = [appDirstringByAppendingFormat:@"/345.mov"];
NSURL*outputUrl = [NSURLfileURLWithPath:newPath];
AVAsset*asset = [AVAssetassetWithURL:music.assetURL];
AVAssetExportSession *session =[[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetPassthrough];
session.outputURL= [NSURLfileURLWithPath:newPath];
session.outputFileType = AVFileTypeCoreAudioFormat;
session.metadata= asset.metadata;
[sessionexportAsynchronouslyWithCompletionHandler:^{
//判断导出状态
switch(session.status) {
case AVAssetExportSessionStatusCompleted:{
//导出完成
NSLog(@"导出成功 %@",outputUrl.absoluteString);
NSString *newPath1 = [[newPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"543.mp3"];
NSError*renameError =nil;
[[NSFileManagerdefaultManager]moveItemAtPath:newPathtoPath:newPath1error:&renameError];
if(renameError) {
NSLog(@"renameError=%@",renameError.localizedDescription);
}else{
NSLog (@" No renameError(Success) :: newPath=%@",newPath1);
self.podFilePath= newPath1;
}
[[NSFileManager defaultManager] removeItemAtPath:newPath error:nil];
}
break;
case AVAssetExportSessionStatusFailed:{
//导出失败
NSLog(@"导出错误 %@",session.error);
}
break;
default:
break;
}
}];
需要注意导出的时候需要指定成mov类型的问题,不然会导出失败