1.申请媒体库使用权限
+ (BOOL)hasMediaLibraryAuth {
MPMediaLibraryAuthorizationStatus aStatus = [MPMediaLibrary authorizationStatus];
if (aStatus == MPMediaLibraryAuthorizationStatusNotDetermined) {
[MPMediaLibrary requestAuthorization:^(MPMediaLibraryAuthorizationStatus status) {
if (aStatus == MPMediaLibraryAuthorizationStatusAuthorized) {
[self fetchItunsMusics];
}
}];
return NO;
}
if (aStatus == MPMediaLibraryAuthorizationStatusAuthorized) {
returnYES;
}else{
returnNO;
}
}
2.获取本地媒体库的音乐列表
+ (NSArray *)fetchItunsMusics {
if (![self hasMediaLibraryAuth]) {
return@[];
}
MPMediaQuery *query = [[MPMediaQuery alloc] init];
MPMediaPropertyPredicate *albumNamePredicate = [MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithInt:MPMediaTypeMusic] forProperty:MPMediaItemPropertyMediaType];
[query addFilterPredicate:albumNamePredicate];
NSArray*a = [query items];
return a;
}
3.获取播放器实例
MPMusicPlayerApplicationController*musicPlayer = [MPMusicPlayerController applicationQueuePlayer];
4.将播放队列传给播放器
[musicPlayer setQueueWithQuery:query];
5.调用播放接口
[musicPlayer play];
6.切换歌曲
//记录下列表中的 MPMediaItem实例
MPMediaItem*mi = [self.musicItemsMap objectForKey:mid];
[musicPlayer setNowPlayingItem:mi];
[musicPlayer play];