您能控制AVURLAsset
加载所需数据的方式吗?我需要添加一个自定义HTTP标头(ICY-MetaData=1
),似乎无法弄清楚如何。
答案 0 :(得分:11)
显然,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.
}
}
答案 1 :(得分:4)
Nicolas Young的回答是正确的,它只需要一些小的改动就可以使用Swift 3.现在有一些红色感叹号,所以我现在理解键值观察得更好我终于想出了如何解决这个问题
import UIKit
import MediaPlayer
//from the original
//https://stackoverflow.com/a/28057734/1839484
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.
}
}