如何知道AVPlayer何时可以播放并向控制器发送信息

时间:2016-12-17 00:36:14

标签: swift streaming

我正在迅速建立一个无线电流媒体应用程序。目前一切正常,但我想改善一点用户体验。

我有一个RadioPlayer.swift类来处理我的无线电操作。

 import Foundation
 import AVFoundation

 class RadioPlayer {
 static let sharedInstance = RadioPlayer()
 private var player = AVPlayer(URL: NSURL(string:"http://rfcmedia.streamguys1.com/classicrock.mp3")!)

private var isPlaying = false


func play() {
    player = AVPlayer(URL: NSURL(string: "http://rfcmedia.streamguys1.com/classicrock.mp3")!)
    player.play()
    isPlaying = true

    player.currentItem?.status

}

func pause() {
    player.pause()
    isPlaying = false
    player.replaceCurrentItemWithPlayerItem(nil)
}

func toggle() {
    if isPlaying == true {
        pause()
    } else {
        play()
    }
}

func currentlyPlaying() -> Bool {
    return isPlaying
}

然后我有一个实现该类的View Controller。我的目标是当播放器加载时,发送一条消息,说明正在准备流媒体,因此用户知道必须等待(也禁用播放按钮)。

所以我的问题是如何实现这一点,在android我使用广播来发送消息,但我没有在swift中找到一个等价物。

1 个答案:

答案 0 :(得分:1)

您可以为AVPlayer属性添加观察者,例如在Swift 3:

player.addObserver(self, forKeyPath: "reasonForWaitingToPlay", options: .new, context: &observerContext)

或者在Swift 2中,使用.New

player.addObserver(self, forKeyPath: "reasonForWaitingToPlay", options: .New, context: &observerContext)

注意,这是使用私有属性来标识上下文:

private var observerContext = 0

然后你可以添加观察者方法。在Swift 3中:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    guard context == &observerContext else {
        super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        return
    }

    // look at `change![.newKey]` to see what the status is, e.g.

    if keyPath == "reasonForWaitingToPlay" {
        NSLog("\(keyPath): \(change![.newKey])")
    }
}

或者在Swift 2中:

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    guard context == &observerContext else {
        super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        return
    }

    // look at `change![NSKeyValueChangeNewKey]` to see what the status is, e.g.

    if keyPath == "reasonForWaitingToPlay" {
        NSLog("\(keyPath): \(change![NSKeyValueChangeNewKey])")
    }

}