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: nilobject: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 に答える