检索的方法通过在iOS的最后一个上场时间排序歌曲列表(Retrieve list of songs

2019-07-19 03:02发布

I need to obtain a list of the N most recently played songs from an iOS device, in order.

The only way I can imagine doing it, at the moment, is by getting all the songs through an MPMediaQuery and manually sort them by lastPlayedDate.

This is a potentially expensive operation and I was wondering if there was a better approach.


Edit: After some tests, this is a very expensive operation. On a test library of 2500 songs, it took around 20 seconds to:

  1. Get all the songs.
  2. Assign a date to all songs that had never played (January 1 1970).
  3. Order them by date.
  4. Fetch the first N entries.

Any suggestion of improvements would be appreciated.


Edit 2: Solved now, but just for the record here's what I was doing.

I was sorting using a block as described here: https://stackoverflow.com/a/805589/112702. Simply changing the sorting method to what's in Bryan's answer improved my speed by nearly 20 times on an iPod Touch 3.

Answer 1:

一种方法是利用数组MPMediaItem是你从一开始MPMediaQuery通过和排序它MPMediaItemPropertyLastPlayedDate使用NSSortDescriptor

NSTimeInterval start  = [[NSDate date] timeIntervalSince1970];

MPMediaQuery *songsQuery = [MPMediaQuery songsQuery];
NSArray *songsArray = [songsQuery items];

NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:MPMediaItemPropertyLastPlayedDate
                                                         ascending:NO];
NSArray *sortedSongsArray = [songsArray sortedArrayUsingDescriptors:@[sorter]];

NSTimeInterval finish = [[NSDate date] timeIntervalSince1970];
NSLog(@"Execution took %f seconds.", finish - start);

这个排序由最近新数组第一个出场。 我用2000首歌曲测试这对iPhone 4S,并花了0.98秒。



Answer 2:

我认为MPMediaQuery是让最近在这个时候播放的歌曲从iOS设备的唯一途径。

您可以使用属性MPMediaItemPropertyLastPlayedDate这将返回用户在其上播放媒体项目最近的日历日期和时间。 值是一个NSDate对象。

http://developer.apple.com/library/IOs/#documentation/MediaPlayer/Reference/MPMediaItem_ClassReference/Reference/Reference.html#//apple_ref/doc/constant_group/General_Media_Item_Property_Keys



文章来源: Retrieve list of songs ordered by last play time in iOS