播放视频结束后如何返回tvOS中的Main.storyboard?

时间:2015-12-31 09:43:26

标签: xcode swift avplayer tvos avkit

我有一个玩家继续玩,并且已经被告知如何设置itemDidFinishPlaying :( AVPlayerItemDidPlayToEndTimeNotification)的通知,但是,出于某种原因,该通知功能不是在视频结束时调用。

 import UIKit
 import AVKit

 class ViewController: UIViewController {

 let playerLayer = AVPlayerLayer()

func playMe(inputfile: String, inputtype: String) {


    let path = NSBundle.mainBundle().pathForResource(inputfile, ofType:inputtype)!
    let videoURL = NSURL(fileURLWithPath: path)
    let playerItem = AVPlayerItem(URL: videoURL)
    let player = AVPlayer(playerItem: playerItem)
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.bounds
    self.view.layer.addSublayer(playerLayer)
    player.play()
    print ("Play has started")

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "itemDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)
    print ("Item Did Finish Playing -notification added")

}

func itemDidFinishPlaying(notification: NSNotification) {
    playerLayer.removeFromSuperlayer()
    print ("Notification sent with removeFromSuperlayer done")

}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
我错过了什么?我已尝试在viewDidLoad()处填写通知条目,我已尝试删除:itemDidFinishPlaying的结尾,我已尝试设置通知在播放开始之前,我object: nil中有object:playerItemNSNotificationCenter ..

对于如何继续,我真的很无能为力。

这些类型的东西只有在有AVPlayerViewController的情况下才可用 - 或者是按下按钮时产生的辅助视图控制器?

1 个答案:

答案 0 :(得分:0)

如果您没有对AVPlayer实例的引用,这似乎就会发生。试试这个:

import UIKit
import AVFoundation

class ViewController: UIViewController {
    var player: AVPlayer?
    var playerLayer: AVPlayerLayer?

    func playMe(inputfile: String, inputtype: String) {
        guard let path = NSBundle.mainBundle().pathForResource(inputfile, ofType: inputtype) else {
            print("couldn't find \(inputfile).\(inputtype)")

            return
        }

        player = AVPlayer()
        playerLayer = AVPlayerLayer(player: player)

        let playerItem = AVPlayerItem(URL: NSURL(fileURLWithPath: path))

        player?.replaceCurrentItemWithPlayerItem(playerItem)

        playerLayer.frame = view.bounds

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.itemDidFinishPlaying(_:)), name: AVPlayerItemDidPlayToEndTimeNotification, object: player?.currentItem)

        view.layer.insertSublayer(playerLayer!, atIndex: 0)

        player?.play()
    }

    func itemDidFinishPlaying(notification: NSNotification) {
        playerLayer?.removeFromSuperlayer()
        print ("Notification sent with removeFromSuperlayer done")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
}

这应该可以解决问题。

不要忘记删除观察员

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}