iOS + Swift, How to access all music files [closed

2019-03-10 04:36发布

问题:

I'm making an app in iOS using swift. What I want to do is get all music file on the iPhone storage, just like iTunes does: I want to display titles, albums, as well as play tracks.

I'm new with iOS programming: what iOS framework should I learn and use in order to achieve my goal?

Thanks in advance.

回答1:

The question is a bit unclear (to me at least).

You are looking to create a kind of music player application ? You want to add your own music (A) or use the music that the user have in his Music App Library (B) ?

In the second case, you might be looking for something like this.

Music files are represented by MPMediaItem instances. You could use retrieve them through a MPMediaQuery, for example :

// All
let mediaItems = MPMediaQuery.songsQuery().items
// Or you can filter on various property
// Like the Genre for example here
var query = MPMediaQuery.songsQuery()
let predicateByGenre = MPMediaPropertyPredicate(value: "Rock", forProperty: MPMediaItemPropertyGenre)
query.filterPredicates = NSSet(object: predicateByGenre)

At this point, you have all (or some if you filter) songs included in Music App Library, so you can play them with a MPMusicPlayerController after setting a playlist queue :

let mediaCollection = MPMediaItemCollection(items: mediaItems)

let player = MPMusicPlayerController.systemMusicPlayer()
player.setQueueWithItemCollection(mediaCollection)

player.play()

There is probably the possibility to access somehow the metadata (title, genre, artist, ...) from the songs.

This probably won't work on simulator.



标签: ios swift music