swiftavplayermpmediaitemcollection

Play items from MPMediaItemCollection in AVPlayer [Swift]


Here is the thing, I have a MPMediaItemCollection with user choosen items(from the library). I used the mediaPicker to do that. Now, I need to get the URL from these items so I can play them on a AVPlayer. This is the best I can find, but when I "translate" to swift it gets messed up. If someone can help me I would appreciate a lot.


Solution

  • Here is your swift code:

    func mediaPicker(mediaPicker: MPMediaPickerController!, didPickMediaItems mediaItemCollection: MPMediaItemCollection!) {
    
        for thisItem in mediaItemCollection.items as! [MPMediaItem] {
            let itemUrl = thisItem.valueForProperty(MPMediaItemPropertyAssetURL) as? NSURL
            self.dismissViewControllerAnimated(true, completion: nil)
    
            // Play the item using MPMusicPlayer
            var appMusicPlayer = MPMusicPlayerController.applicationMusicPlayer()
            appMusicPlayer.play()
    
            // Play the item using AVPlayer
            let playerItem = AVPlayerItem(URL: itemUrl)
            let player = AVPlayer(playerItem: playerItem)
            player.play()
        }
    }