Swift AVPlayerItem 完成后关闭

Swift AVPlayerItem close when finished

我对 Swift 和 iOS 开发非常陌生,所以请原谅我的无知。

我正在尝试让 AVPlayer 在视频播放完毕后自动关闭。我想附加 "playerDidFinishPlaying" 侦听器来接收通知,但是一旦我有了它,我就找不到 method/event 来关闭控制器。我想模仿单击 "Done" 按钮的操作。

这是一小段代码。希望这是足够的信息。如果没有,我可以提供更多信息

let destination = segue.destinationViewController as! AVPlayerViewController
let url = NSURL(string: "video url")
destination.player = AVPlayer(URL: url!)
destination.player?.play()

我已经添加了以下通知,但同样,我不确定在收到通知后如何处理...

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

func playerDidFinishPlaying(note:NSNotification){
    print("finished")
    // close window/controller
}

最后,我知道我需要删除观察者,但我不确定何时何地这样做。非常感谢任何帮助。

为了"close"控制器,你应该调用dismissViewControllerAnimated(true, completion: nil)

因此代码将如下所示:

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

func playerDidFinishPlaying(note:NSNotification){
    print("finished")
    dismissViewControllerAnimated(true, completion: nil)
}

如果您的 viewControllerUINavigationController 堆栈中,您还可以:

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

func playerDidFinishPlaying(note:NSNotification){
    print("finished")
    navigationController?.popViewControllerAnimated(true)
}

而要移除观察者,您可以在 deinit{}:

内进行
deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

SWIFT3 的更新:

注意:viewController播放音频的地方需要:AVAudioPlayerDelegate

你也不需要观察者

class myViewController: UIViewController, AVAudioPlayerDelegate {

var audioplayer = AVAudioPlayer() 

override func viewDidAppear(_ animated: Bool) {

if soundsON{
        let myFilePathString = Bundle.main.path(forResource: "backgroundSound", ofType: "mp3")

        if let myFilePathString = myFilePathString
        {
            let myFilePathURL = URL(fileURLWithPath: myFilePathString)

            do{
                try audioplayer = AVAudioPlayer(contentsOf: myFilePathURL)
                audioplayer.delegate = self
                audioplayer.prepareToPlay()

                audioplayer.play()


            }catch{
                print("error playing coin sound")
            }
        }
   }    
}

在此示例中,声音将在 viewDidAppear 播放,播放完毕后将调用:audioPlayerDidFinishPlaying:

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    //Check if the sound that finishes comes from a certain AVAudioPlayer 
    if player == audioplayer{
        print("The sound from -audioplayer- has finished")
    // If you need to dismiss the VC:
        dismiss(animated: true, completion: nil)
    }
}

对于 #iOS 11 和 swift 4.2 关闭控制器不起作用所以只需在您的播放器设置代码中添加此键

if #available(iOS 11.0, *) {
     self.playerVC?.exitsFullScreenWhenPlaybackEnds = true
}

如果您也想允许 #iOS 10,请写下这一行。

if #available(iOS 11.0, *) {
      self.playerVC?.exitsFullScreenWhenPlaybackEnds = true
 }

NotificationCenter.default.addObserver(self, selector: #selector(self.playerItemDidReachEnd(notification:)), name: .AVPlayerItemDidPlayToEndTime, object:self.playerVC?.player!.currentItem)

func playerItemDidReachEnd(note:NSNotification){
     print("finished")
     dismissViewControllerAnimated(true, completion: nil)
 }