web-dev-qa-db-ja.com

AVPlayerビデオの再生が終了したことを検出する方法は?

Swiftでローカルビデオファイル(mp4)を再生するためにAVPlayerを使用しています。ビデオの再生が終了したことを検出する方法を知っている人はいますか?ありがとう

54
Nik

AVPlayerItemDidPlayToEndTimeNotificationを取得するには、オブジェクトがAVPlayerItemである必要があります。

そのためには、AVPlayer.currentItemプロパティを使用するだけです

動画が終了すると通知が届きます!

私の例を参照してください:

let videoPlayer = AVPlayer(URL: url)       

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

func playerDidFinishPlaying(note: NSNotification) {
    print("Video Finished")
}

Swift

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")
}

deinitのObserverを削除することを忘れないでください

Swift 4、5

NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: nil)
68
jstn

Swift 3.

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")
    }
33
Channel

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)
}
9
Nish

For Swift 3.これは正常に動作しています

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")
    }
}
8
manvendra

Swift 4.

これは私のために動作します。 @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")
    }
6
Arash HF

Swift 3.0

let videoPlayer = AVPlayer(URL: url)
NotificationCenter.default.addObserver(self, selector:#selector(self.playerDidFinishPlaying(note:)),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)

func playerDidFinishPlaying(note: NSNotification){
    //Called when player finished playing
}
2
jaya raj

For Swift 3.

ここで、「fullUrl」はビデオのURLであり、URLにスペースがないことを確認してください。URLが機能するように、「スペース」を「%20」に置き換える必要があります。

  let videoURL = NSURL(string: fullUrl)
  let player = AVPlayer(url: videoURL! as URL)

  playerViewController.delegate = self
  playerViewController.player = player
  self.present(playerViewController, animated: false) {

    self.playerViewController.player!.play()

    NotificationCenter.default.addObserver(self, selector: #selector(yourViewControllerName.playerDidFinishPlaying), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
  }

View Controllerで指定されたメソッドを以下に追加します。

func playerDidFinishPlaying(){    
print("Video Finished playing in style")
}
2
Anil shukla

Swift 3およびRxSwift 3.5で必要なことは次のとおりです。

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.rx.notification(Notification.Name.AVPlayerItemDidPlayToEndTime)
        .asObservable().subscribe(onNext: { [weak self] notification in

            //Your action

        }).addDisposableTo(disposeBag)
}
2
mkkrolik

私はここに受け入れられた答えがたくさんあることを知っています...

しかし、別の方法は、境界時間オブザーバーをAVPlayerに追加することです。ビデオの長さをplayer.currentItemから取得して、必要な時間境界として追加する必要があります。

fileprivate var videoEndObserver: Any?

func addVideoEndObserver() {
    guard let player = YOUR_VIDEO_PLAYER else { return }

    // This is just in case you are loading a video from a URL.
    guard let duration = player.currentItem?.duration, duration.value != 0 else {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { [weak self] in
            self?.addVideoEndObserver()
        })

        return
    }

    let endTime = NSValue(time: duration - CMTimeMakeWithSeconds(0.1, duration.timescale))
    videoEndObserver = player.addBoundaryTimeObserver(forTimes: [endTime], queue: .main, using: {
        self.removeVideoEndObserver()

        // DO YOUR STUFF HERE...
    })
}

func removeVideoEndObserver() {
    guard let observer = videoEndObserver else { return }

    videoPlayer.player?.removeTimeObserver(observer)
    videoEndObserver = nil
}
0
Designerd