Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timed Metadata with AVPlayer

Can you control how AVURLAsset loads the data it requires? I need to add a custom HTTP header (ICY-MetaData=1) and can't seem to figure out how.

like image 599
Nicholas Young Avatar asked Jan 15 '15 00:01

Nicholas Young


2 Answers

Apparently, AVPlayer automatically requests metadata from Icecast. The code below works perfectly.

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.
    }
}
like image 178
Nicholas Young Avatar answered Sep 22 '22 07:09

Nicholas Young


Nicolas Young's answer is correct it just needs some small changes to work with Swift 3. There were some red exclamation points so now that I understand key value observation a little better I finally figured out how to fix this

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.
}
}
like image 40
Ohiovr Avatar answered Sep 24 '22 07:09

Ohiovr