I am making a Music Player app. MPMediaQuery returns duplicates. For example, when I get the list of songs from a certain album (10 songs are on the actually CD), 1 song shows up twice. I don't know why. Maybe I had sampled my old CD for the 1 song and then at some point later, I sampled the whole CD. I don't know. Anyway, my app and Apple's music app lists the song twice, so when I go to play the album, I hear that song twice. I'd like to eliminate this. By the way, as you might expect, there are 11 different PersistentIDs (one is out of sequence).
I've spend a bunch of time changing the code and searching stack overflow.
// Filter the Albums by the Artist (PASSED in from the previous View Controller)
let predicateByArtist = MPMediaPropertyPredicate(value: selectedArtist, forProperty: MPMediaItemPropertyArtist)
// Filter the Songs by the AlbumTitle (PASSED in from the previous View Controller)
let predicateByAlbumTitle = MPMediaPropertyPredicate(value: selectedAlbumTitle, forProperty: MPMediaItemPropertyAlbumTitle)
// Query the songs
qrySongs = MPMediaQuery.songs()
qrySongs.addFilterPredicate(predicateByArtist)
qrySongs.addFilterPredicate(predicateByAlbumTitle)
//********** June 19, 2019 additional effort...
// At this point, qrySongs has 11 songs (note: the album City to City really only has 10 songs
// In an effort to learn Xcode/Swift, I thought would if I made a new array of MPMediaItems that only had the list of unique song titles (I'm trying to skip the one duplicate). Then I could use this list: qrySongsUnique when I assign titles to the TableView. The theory being that the MPMusicPlayerController.systemMusicPlayer is really just playing a PersistentID.
// Maybe this idea will not work, maybe it will (but should only be used with small arrays like albums) ... but I'm confused as to why I'm getting a fatal error...
let count = qrySongs.items?.count
print(count!) // Optional(11)
var i: Int = 0
var lastRowItemTitle: String = ""
var qrySongsUnique: [MPMediaItem] = [MPMediaItem]()
if count ?? 0 > 0 {
while i < count ?? 0 {
print(i) // 0
let currentRowItemTitle = qrySongs.items![i].title
print(currentRowItemTitle!) // Optional("The Ark")
if currentRowItemTitle != lastRowItemTitle {
print(qrySongs.items![i]) // <MPConcreteMediaItem: 0x280f4da10> 6027817404062467305
qrySongsUnique[i] = qrySongs.items![i] // Thread 1: Fatal error: Index out of range
lastRowItemTitle = currentRowItemTitle ?? "skipped"
}
i = i + 1
}
}
//**********
A list of unique song titles