电影完成后关闭AVPlayer [英] Close AVPlayer when movie is complete

查看:117
本文介绍了电影完成后关闭AVPlayer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的iPad应用程序,可以在按下按钮时播放电影.电影播放后,当电影结束时,我想关闭AVPlayerView,使其返回主屏幕. 目前,视频播放完毕后会停留在最后一帧. 我的ViewController.此刻为Swift.

I am making a simple iPad app to play a movie when a button is pressed. The movie plays and when the movie is finished I want to close AVPlayerView so it goes back to the main screen. Currently when the video finishes it stays on the last frame. My ViewController.Swift at the moment.

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {
//MARK : Properties 

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
//MARK: Actions

@IBAction func playButton(_ sender: AnyObject) {

    let movieURL = Bundle.main.url(forResource: "ElephantSeals", withExtension: "mov")!
    let player = AVPlayer(url: movieURL as URL)

    let playerViewController = AVPlayerViewController()

    playerViewController.player = player

    self.present(playerViewController, animated: true) {
        playerViewController.player!.play()
        }
//    player.actionAtItemEnd = playerViewController.dismiss(animated: true)
}
}

如您所见,我认为actionAtItemEnd中可能有某些内容,但是我不确定如何实现它. 谢谢.

As you can see, I think there might be something in actionAtItemEnd, but I'm not sure how to implement it. Thank you.

推荐答案

这是swift 3.0中的有效代码,尝试一下并让我知道...:)

This is working code in swift 3.0, try this and let me know...:)

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    let playerViewController = AVPlayerViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func playButton(_ sender: AnyObject) {

        let movieURL = Bundle.main.url(forResource: "ElephantSeals", withExtension: "mov")!
        let player = AVPlayer(url: movieURL as URL)

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

        self.present(playerViewController, animated: true) {
            self.playerViewController.player!.play()
        }
    }


    func playerDidFinishPlaying(note: NSNotification) {
            self.playerViewController.dismiss(animated: true)
           }
}

这篇关于电影完成后关闭AVPlayer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆