AVPlayer 的定时元数据

Timed Metadata with AVPlayer

你能控制AVURLAsset如何加载它需要的数据吗?我需要添加自定义 HTTP header (ICY-MetaData=1),但似乎不知道如何添加。

显然,AVPlayer 会自动从 Icecast 请求元数据。下面的代码完美运行。

class ViewController: UIViewController {
    var Player: AVPlayer!
    var PlayerItem: AVPlayerItem!

    override func viewDidLoad() {
        super.viewDidLoad()

        PlayerItem = AVPlayerItem(URL: NSURL(string: "http://live.machine.fm/aac"))
        PlayerItem.addObserver(self, forKeyPath: "timedMetadata", options: nil, context: nil)
        Player = AVPlayer(playerItem: PlayerItem)
        Player.play()
    }

    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) -> Void {

        if keyPath != "timedMetadata" { return }

        var data: AVPlayerItem = object as AVPlayerItem

        for item in data.timedMetadata as [AVMetadataItem] {
            println(item.value)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Nicolas Young 的回答是正确的,只需要做一些小改动即可使用 Swift 3. 有一些红色感叹号,所以现在我对键值观察有了更好的理解,我终于想出了如何解决这个

import UIKit
import MediaPlayer

//from the original
//

class ViewController: UIViewController {
var Player: AVPlayer!
var PlayerItem: AVPlayerItem!

override func viewDidLoad() {
    super.viewDidLoad()
    let playBackURL = URL(string: "http://ca2.rcast.net:8044/")
    PlayerItem = AVPlayerItem(url: playBackURL!)
    PlayerItem.addObserver(self, forKeyPath: "timedMetadata", options: NSKeyValueObservingOptions(), context: nil)
    Player = AVPlayer(playerItem: PlayerItem)
    Player.play()
}


override func observeValue(forKeyPath: String?, of: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if forKeyPath != "timedMetadata" { return }

    let data: AVPlayerItem = of as! AVPlayerItem

    for item in data.timedMetadata! {
        print(item.value!)
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}