首页 热点资讯 义务教育 高等教育 出国留学 考研考公
您的当前位置:首页正文

获取本地音乐文件并保存到沙盒

2024-12-20 来源:华佗小知识

获取本地音乐

MPMediaQuery *allMusic = [[MPMediaQuery alloc] init];
    MPMediaPropertyPredicate *albumNamePredicate = [MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithInt:MPMediaTypeMusic ] forProperty: MPMediaItemPropertyMediaType];
    [allMusic addFilterPredicate:albumNamePredicate];
    NSArray *itemsFromGenericQuery = [allMusic items];

获取音乐的信息

for (MPMediaItem *song in itemsFromGenericQuery) {
            SingleMusicModel *model = [SingleMusicModel new];
            model.title = [song valueForProperty: MPMediaItemPropertyTitle];
            model.singer = [song valueForProperty:MPMediaItemPropertyArtist];
            model.songURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
            …………
        }

由于iPhone 自带的音乐软件Music的推出.从iPod取出来的音乐MPMediaItemPropertyAssetURL属性可能为空. 这是因为iPhone自带软件Music对音乐版权的保护,对于所有进行过 DRM Protection(数字版权加密保护)的音乐都不能被第三方APP获取并播放.即使这些音乐已经下载到本地.但是还是可以播放本地未进行过数字版权加密的音乐.也就是您自己手动导入的音乐.

写入沙盒


-(void)configVideo:(NSURL *)url
             title:(NSString *)title
           success:(void (^)(NSData *data))success
           failure:(void (^)())failure {
    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [dirs objectAtIndex:0];
    AVAssetExportSession *exporter = [[AVAssetExportSession alloc]
                                      initWithAsset: songAsset
                                      presetName: AVAssetExportPresetAppleM4A];
    exporter.outputFileType = @"com.apple.m4a-audio";
    // 建立本地音乐文件
    NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"locationMusic"];
    if (![fileManager fileExistsAtPath:filePath]) {
        // 创建文件夹
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *exportFile = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.m4a",title]];
    NSError *error1;
    if([fileManager fileExistsAtPath:exportFile]) {
        [fileManager removeItemAtPath:exportFile error:&error1];
    }
    NSURL* exportURL = [NSURL fileURLWithPath:exportFile];
    exporter.outputURL = exportURL;
    [exporter exportAsynchronouslyWithCompletionHandler:^ {
        NSData *data = [NSData dataWithContentsOfFile:exportFile];
        int exportStatus = exporter.status;
        if (exportStatus == AVAssetExportSessionStatusCompleted) {
            NSLog(@"AVAssetExportSessionStatusCompleted");
            if (success) {
                success(data);
            }
        } else {
            NSLog(@"AVAssetExportSessionStatusFail");
            if (failure) {
                failure();
            }
        }
    }];
    
}
显示全文