如何从 mediaPickerController 获取 mediaItemCollection 以在 AVPlayer 上播放?

How do I get a mediaItemCollection from the mediaPickerController to play on an AVPlayer?

为了回答这个问题,我在一本书中看到了这个。

"MPMediaItem, however, has an MPMediaItemPropertyAssetURL key (or assetURL property) whose value is a URL. That gives you a reference to the music file on disk,...having obtained an MPMediaItem’s asset URL, you could use that URL to initialize an AVAudioPlayer, an AVPlayer, or an AVAsset."

所以我尝试像这样使用 mediaPickerController 来获取资产 url。

    func mediaPicker(mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {

    guard let mediaItem = mediaItemCollection.items.first else {
        NSLog("No item selected.")
        return
    }
    var songURL = mediaItem.valueForProperty(MPMediaItemPropertyAssetURL) as! NSURL
    print(songURL)
    self.dismissViewControllerAnimated(true, completion: nil)
}

书中给出了这个例子:

let arr = // array of MPMediaItem
let items = arr.map {
    let url = [=11=].assetURL!
    let asset = AVAsset(URL:url)
    return AVPlayerItem(asset: asset)
}
self.qp = AVQueuePlayer(items:items)
self.qp.play()

我不确定如何将 mediaItemCollection 获取到 arr 变量。 songURL 和 MediaItemCollection 的使用在 picker mediaPicker 函数内部。我无法在其功能之外访问它。我如何让它工作?

好的。我想通了。

解决办法是先在函数外声明变量,但在class下。我是这样创建的:

class ViewController: UIViewController, MPMediaPickerControllerDelegate {

var songUrl: NSURL = NSURL()
var player = AVPlayer()


func mediaPicker(mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {

    guard let mediaItem = mediaItemCollection.items.first else {
        NSLog("No item selected.")
        return
    }
    songUrl = mediaItem.valueForProperty(MPMediaItemPropertyAssetURL) as! NSURL
    print(songUrl)

    self.dismissViewControllerAnimated(true, completion: nil)
}

现在我可以在函数外访问 songUrl。