Ios – swift xcode play sound files from player list

audiofileiosswiftxcode

I am looking for a swift coding playing sound out of the player list and not sounds added as resource to your project.
I mainly found the usage of
NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound_name", ofType: "wav"))
println(alertSound)
but for this you need to have the sound file in your bundle. But I couldn't find any example
selecting audio files bought thru itunes and play them.

Any idea how to do this? Can I access my music layer playlist files and using them in my app?

Thanks for any code lines.
rpw

Best Answer

These music files are represented by MPMediaItem instances. To fetch them, you could use an MPMediaQuery, as follows:

let mediaItems = MPMediaQuery.songsQuery().items

At this point, you have all 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()
player.setQueueWithItemCollection(mediaCollection)

player.play()

You might need to filter songs by genre, artist, album and so on. In that case, you should apply a predicate to the query before fetching the media items:

var query = MPMediaQuery.songsQuery()
let predicateByGenre = MPMediaPropertyPredicate(value: "Rock", forProperty: MPMediaItemPropertyGenre)
query.filterPredicates = NSSet(object: predicateByGenre)

let mediaCollection = MPMediaItemCollection(items: query.items)

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

player.play()

Cheers!

Related Topic