开发者

What is the fastest way to get a random MPMediaItem [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 4 years ago.

Improve this question

guys :) Can you please share some ideas how to get one or more random MPMediaItems from user's iPod Library. Any call to [MPMediaQuery songsQuery].items is waaaaay too slow - for a library of just 800 songs it takes about 19 seconds on my iPod Touch 2G to execute the query. I don't want to cache the entire iPod library, because I don't think it's worth the effort. Any thoughts will be greatly appreciated. Thank you 开发者_如何学编程:)


You could use [MPMediaQuery albumsQuery] to get a random album, then try getting a random song from that album.


I wrote this method to retrieve a random track from the music collection for my iPad Jukebox application called My Jukebox, hopefully you can use it too. Its fast, even on big music collections and if you retain the MediaQuery object (store it as a property of the class) then the second call is almost instant. I hope it helps.

-(MPMediaItem*) getRandomTrack
{
    // Check if we can re-use an MPMediaQuery
    if (self.mediaQuery == nil)
    {
        MPMediaQuery *everything = [[MPMediaQuery alloc] init];
        [self setMediaQuery:everything];
        [everything release];
    }
    // Get all Media Items into an Array (Fast)
    NSArray *allTracks = [mediaQuery items];
    // Check we have enough Tracks for a Random Choice
    if ([allTracks count] < 20)
    {
        return nil;
    }
    // Pick Random Track
    int trackNumber = arc4random() % [allTracks count];
    MPMediaItem *item = [allTracks objectAtIndex:trackNumber];
    // Display and Return
    return item;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜