如何检测AVPlayer视频何时结束播放?

Nik*_*Nik 56 iphone ios avplayer swift

我正在使用AVPlayer在Swift中播放本地视频文件(mp4).有没有人知道如何检测视频完成播放?谢谢

jst*_*stn 68

要获得AVPlayerItemDidPlayToEndTimeNotification你的对象需要成为一个AVPlayerItem.

要这样做,只需使用.currentItem您的财产AVPlayer

现在,一旦视频结束,您将收到通知!

看我的例子:

let videoPlayer = AVPlayer(URL: url)       

NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:",
        name: AVPlayerItemDidPlayToEndTimeNotification, object: videoPlayer.currentItem)

func playerDidFinishPlaying(note: NSNotification) {
    print("Video Finished")
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

let videoPlayer = AVPlayer(URL: url)       

NotificationCenter.default.addObserver(self, selector: Selector(("playerDidFinishPlaying:")), 
       name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: videoPlayer.currentItem)

func playerDidFinishPlaying(note: NSNotification) {
    print("Video Finished")
}
Run Code Online (Sandbox Code Playgroud)

不要忘记删除你的观察者 deinit

  • 来自https://developer.apple.com/library/archive/releasenotes/Foundation/RN-FoundationOlderNotes/index.html#10_11NotificationCenter在OS X 10.11和iOS 9.0中,NSNotificationCenter和NSDistributedNotificationCenter将不再向可能释放的注册观察者发送通知。 (3认同)
  • 如何删除它请 (2认同)
  • 有两点是错误的(1)你实际上不需要将任何东西作为对象传递(2)多年来,不需要取消通知 (2认同)

Cha*_*nel 34

Swift 3.0

let videoPlayer = AVPlayer(URL: url)

NotificationCenter.default.addObserver(self, selector:#selector(self.playerDidFinishPlaying(note:)),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)

@objc func playerDidFinishPlaying(note: NSNotification){
        print("Video Finished")
    }
Run Code Online (Sandbox Code Playgroud)


dch*_*rov 10

如果您喜欢使用组合:

private var cancelBag: Set<AnyCancellable> = []

NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime)
.sink { _ in
    player.seek(to: CMTime.zero)
    player.play()
}
.store(in: &cancelBag)
Run Code Online (Sandbox Code Playgroud)


Nis*_*ish 9

Swift 4.2版本:

var player: AVPlayer!
  //
  //
// Configure Player
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let filepath: String? = Bundle.main.path(forResource: "selectedFileName", ofType: "mp4")
    if let filepath = filepath {
        let fileURL = URL.init(fileURLWithPath: filepath)
        player = AVPlayer(url: fileURL)
        let playerLayer = AVPlayerLayer(player: player)
        // Register for notification
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(playerItemDidReachEnd),
                                                         name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                                         object: nil) // Add observer

        playerLayer.frame = self.view.bounds
        self.view.layer.addSublayer(playerLayer)
        player.play()
    }
}
// Notification Handling
@objc func playerItemDidReachEnd(notification: NSNotification) {
    player.seek(to: CMTime.zero)
    player.play()
}
// Remove Observer
deinit {
    NotificationCenter.default.removeObserver(self)
}
Run Code Online (Sandbox Code Playgroud)


man*_*dra 8

对于SWIFT 3.0 这很好用

class PlayVideoViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayVideoViewController.finishVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTimeNotification, object: nil)
    }

    func finishVideo()
    {
        print("Video Finished")
    }
}
Run Code Online (Sandbox Code Playgroud)


Ara*_* HF 7

Swift 4.0

这个对我有用.感谢@Channel

    private func playVideo(fileURL: String) {

            // Create RUL object
            let url = URL(string: fileURL)

            // Create Player Item object
            let playerItem: AVPlayerItem = AVPlayerItem(url: url!)
            // Assign Item to Player
            let player = AVPlayer(playerItem: playerItem)

            // Prepare AVPlayerViewController
            let videoPlayer = AVPlayerViewController()
            // Assign Video to AVPlayerViewController
            videoPlayer.player = player

            NotificationCenter.default.addObserver(self, selector: #selector(myViewController.finishVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)

            // Present the AVPlayerViewController
            present(videoPlayer, animated: true, completion: {
                    // Play the Video
                    player.play()
            })

    }

    @objc func finishVideo()
    {
            print("Video Finished")
    }
Run Code Online (Sandbox Code Playgroud)


小智 7

SWIFT 5 更新

带有 @objc 函数的观察者方法不是本机的。最好在 swift 5 中使用事件发布器。非常简单。

在结构体中声明以下内容:

var pub = NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime)
Run Code Online (Sandbox Code Playgroud)

然后在任何视图上添加

.onReceive(pub) { (output) in
    print("Video Finished")
}
Run Code Online (Sandbox Code Playgroud)


Fat*_*tie 5

2019年

真的这么简单

NotificationCenter.default.addObserver(
    self,
    selector: #selector(fileComplete),
    name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
    object: nil
)
Run Code Online (Sandbox Code Playgroud)

(对象为零也可以。)

进而

@objc func fileComplete() {
    print("IT'S DONE!")
}
Run Code Online (Sandbox Code Playgroud)