电影完成后关闭AVPlayer

Ror*_*ryM 6 avfoundation ios swift avkit

当按下按钮时,我正在制作一个简单的iPad应用程序来播放电影.电影播放,电影结束时我想关闭AVPlayerView,然后返回主屏幕.目前,当视频完成时,它将保留在最后一帧.我的ViewController.Swift此刻.

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)
}
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我认为actionAtItemEnd中可能存在某些内容,但我不确定如何实现它.谢谢.

Dee*_*pak 17

这是swift 3.0中的工作代码,尝试这个让我知道...... :)

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)
           }
}
Run Code Online (Sandbox Code Playgroud)


Ahm*_*adi 6

斯威夫特 4

let playerController = AVPlayerViewController()

private func playVideo() {
    guard let path = Bundle.main.path(forResource: "p810", ofType:"mp4") else {
        debugPrint("video.m4v not found")
        return
    }
    let player = AVPlayer(url: URL(fileURLWithPath: path))
    playerController.player = player
    NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerController.player?.currentItem)

    present(playerController, animated: true) {
        player.play()
    }
}

@objc func playerDidFinishPlaying(note: NSNotification) {
    playerController.dismiss(animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)