Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get MPMediaItem (song) listening times (dates)

I wanna get song's listening times in a certain period. Using MPMediaItemPropertyLastPlayedDate I only get the date of the last time a song was played, so if a I play a song multiple times a day, only the last time will count. Basically, what I wanna do is getting user's listening history in a certain period (the last 2 days for example.) Also with MPMediaItemPropertyPlayCount I get the total play count overall.

Any ideas?

Thanks.

like image 771
user3350794 Avatar asked Oct 20 '22 09:10

user3350794


2 Answers

I'm working with this right now. My (Swift code) is:

func getPlaysSince(since:NSDate, onSuccess: (tracks: [MediaItem])->(), onFail: (error: NSError?)->()) {

    var rValue = [MediaItem]()
    let timeInterval = since.timeIntervalSince1970
    let query = MPMediaQuery.songsQuery()
    let songs = query.items
    Logger.logMessage(domain: "Data", level: .Minor, "Checking \(songs.count) songs for those since \(since)")
    let then = NSDate()
    for song in songs {
        if let lastPlayedDate = song.lastPlayedDate {
            if lastPlayedDate != nil {
                if lastPlayedDate.timeIntervalSince1970 > timeInterval {
                    Logger.logMessage(domain: "Data", level: .Minor, "\(song.title) at \(lastPlayedDate)")
                    let item:MediaItem = MediaItem(mediaItem: song as! MPMediaItem)
                    rValue.append(item)
                }
            }
        }
    }
    let taken = NSDate().timeIntervalSinceDate(then)
    Logger.logMessage(domain: "Data", level: .Minor, "scanned in \(taken) seconds")

    onSuccess(tracks: rValue)

}

I've include my entire function, though the key lines are the assignments to query, songs and song, and then the check for lastPlayedDate. lastPlayedDate can be nil (never played this song before).

This code is doing a full check of my entire library 5K songs, and takes about 3 seconds. In my case I'm only interested in my play history since "since"

like image 100
Derek Knight Avatar answered Nov 01 '22 11:11

Derek Knight


Use this to get the duration of an MPMediaItem.

MPMediaItem *song;
NSNumber *duration= [song valueForProperty:MPMediaItemPropertyPlaybackDuration];
like image 41
Cody Robertson Avatar answered Nov 01 '22 10:11

Cody Robertson