我正在开发一个iPhone 4应用程序,该应用程序可以通过不同的条件过滤本地媒体库。我已经能够按歌曲名称,艺术家和流派进行过滤。现在,我需要添加一个评级过滤器机制。我在思考“评级> = N星”(N:0..5)
我用来过滤的代码是:
allMedia = [MPMediaQuery songsQuery];
MPMediaPropertyPredicate *mpp1 = [MPMediaPropertyPredicate predicateWithValue:@"2" forProperty:MPMediaItemPropertyRating comparisonType:MPMediaPredicateComparisonEqualTo];
[allMedia addFilterPredicate:mpp1];
但是MPMediaPropertyPredicate不允许按MPMediaItemPropertyRating进行过滤(实际上,它可以与艺术家和歌曲标题一起使用)。
2011-05-12 11:37:39.060 Radio3[1525:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'MPMediaPropertyPredicate cannot filter using the rating property.'
我通过MPMediaItemPropertyRating在google上搜索,但看来我应该找到一种替代方法来按曲目评级进行过滤。
有人可以给我小费吗?
谢谢
更新:这是我的代码来解决这个问题:
allMedia = [MPMediaQuery songsQuery];
//MPMediaPropertyPredicate *mpp1 = [MPMediaPropertyPredicate predicateWithValue:@"2" forProperty:MPMediaItemPropertyRating comparisonType:MPMediaPredicateComparisonEqualTo];
//MPMediaPropertyPredicate *mpp2 = [MPMediaPropertyPredicate predicateWithValue:@"Pop" forProperty:MPMediaItemPropertyGenre comparisonType:MPMediaPredicateComparisonContains];
//[allMedia addFilterPredicate:mpp1];
//[allMedia addFilterPredicate:mpp2];
//[myPlayer setQueueWithQuery:allMedia];
NSArray *itemsFromGenericQuery = [allMedia items];
NSMutableArray *mArray = [[NSMutableArray alloc] init];
int i = 0;
int j=0;
NSLog(@"itemCount: %d",[itemsFromGenericQuery count]);
float playsQuery = sliderPlays.value;
if(playsQuery == 20){playsQuery = 10000;}
NSLog(@"sliderRating.value %f sliderPlays.value %.1f", [sliderRating value], playsQuery);
while(i++ < 1000){
int trackNumber = arc4random() % [itemsFromGenericQuery count];
MPMediaItem *song = [itemsFromGenericQuery objectAtIndex:trackNumber];
NSString *artistName = [song valueForProperty: MPMediaItemPropertyArtist];
NSString *title = [song valueForProperty: MPMediaItemPropertyTitle];
NSString *rating = [song valueForKey:MPMediaItemPropertyRating];
double lengh = [[song valueForProperty:MPMediaItemPropertyPlaybackDuration] doubleValue];
NSNumber *playCount = [song valueForKey:MPMediaItemPropertyPlayCount];
if ([rating intValue] >= sliderRating.value && [playCount intValue] <= playsQuery) {
if(j++ > 50){break;}
NSLog (@"tracknumber: %d j: %d artistName: %@ title: %@ lengh: %.1f rating: %@ playcount: %d",trackNumber, j, artistName, title, lengh, rating, [playCount intValue]);
[mArray addObject:song];
}
if(i++ > 1000)break;
}
MPMediaItemCollection *itemCol = [[MPMediaItemCollection alloc] initWithItems:mArray];
[myPlayer setQueueWithItemCollection:itemCol];
[myPlayer setShuffleMode: MPMusicShuffleModeSongs];
[myPlayer setRepeatMode: MPMusicRepeatModeNone];
最佳答案
MPMediaItemPropertyRating
是用户定义的属性,根据Apple docs:
用户定义的属性不能用于构建媒体属性谓词。
解决此问题的一种方法是首先遍历所有歌曲,将评分存储在数据库(或其他数据库)中,然后从那里对数据进行排序。