Ega Setya Putra Ega Setya Putra - 1 year ago 154
Swift Question

iOS + Swift ,How to access all music file in directory

I'm making an app in iOS using swift.What I want to do is get all music file on the directory/iPhone storage,just like iTunes did on Mac/iPhone.
Since I'm really new with iOS programming,So I really don't know where to start.I'll really appreciate any suggestion and advice.

What I want to do is get all music file in my directory,so that I get music tittle,music album and music can played on my app.

Thanks in advance.

Answer Source

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.iPodMusicPlayer()

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

This probably won't work on simulator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download