2

我有一个播放器正在进行,并且已被指示如何设置通知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- 或在按钮按下时产生的辅助视图控制器时才可用?

4

1 回答 1

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)
}
于 2016-06-10T15:49:11.577 回答