Swift xcode play sound files from player list
I'm looking for a quick encoding that plays audio from the player list, not sounds added as a resource for your project. Basically I found using NSURL (fileURLWithPath: NSBundle.mainBundle (). PathForResource ("sound_name", ofType: "wav")) Println (alertSound) but for that you need to have a sound file in your bundle. But I couldn't find any example of selecting audio files purchased through itunes and playing them.
Any ideas how to do this? Can I access music layer playlist files and use them in my application?
Thanks for any lines of code. RPW
source to share
These music files are represented by MPMediaItem instances. To get them, you can use MPMediaQuery as shown below:
let mediaItems = MPMediaQuery.songsQuery().items
At this point, you have all the songs included in the Music App Library, so you can play them using MPMusicPlayerController after setting the playlist queue:
let mediaCollection = MPMediaItemCollection(items: mediaItems) let player = MPMusicPlayerController.iPodMusicPlayer() player.setQueueWithItemCollection(mediaCollection) player.play()
You may need to filter songs by genre, artist, album, etc. In this case, before extracting the media items, you should apply the predicate to the query:
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()
source to share