按下后停止AV播放器

时间:2016-06-24 18:43:50

标签: ios xcode swift

我将本地视频加载到新的视图控制器中,但在完成后它会消失并立即再次弹回。我不知道是否有办法跟踪通知或什么。

这是我的代码:

import UIKit
import AVKit
import AVFoundation

class VideoController1: UIViewController {

    var playerViewController = AVPlayerViewController()
    var playerView = AVPlayer()

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

    override func viewDidAppear(_ animated: Bool) {
        let fileURL = NSURL(fileURLWithPath: "/Users/jamesjarrett/Desktop/NIMS/NIMS/NIMS/Vid2.mp4")
        playerView = AVPlayer(url: fileURL as URL)
        playerViewController.player = playerView
        self.present(playerViewController, animated: true){
            self.playerViewController.player?.play()
        }
    }

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

1 个答案:

答案 0 :(得分:0)

你把你的代码

let fileURL = NSURL(fileURLWithPath: "/Users/jamesjarrett/Desktop/NIMS/NIMS/NIMS/Vid2.mp4")
    playerView = AVPlayer(url: fileURL as URL)
    playerViewController.player = playerView
    self.present(playerViewController, animated: true){
        self.playerViewController.player?.play()
    }

在ViewController的ViewDidAppear中。

当您的视图再次出现在屏幕上时,会出现ViewDidAppear()。这意味着,当AVPlayer关闭时,它会返回到该视图,AVPlayer将再次显示。

您有两个选择:

为该按钮制作UIButton和Action

var button = UIButton(frame: CGRect(0, self.view.frame.height*0.9, self.view.frame.width, self.view.frame.height*0.1))
button.addTarget(self, #selector(VideoController1.playController), nil)
self.view.addSubview(button)    

let fileURL = NSURL(fileURLWithPath: "/Users/jamesjarrett/Desktop/NIMS/NIMS/NIMS/Vid2.mp4")

func playController() {
    playerView = AVPlayer(url: fileURL as URL)
    playerViewController.player = playerView
    self.present(playerViewController, animated: true){
        self.playerViewController.player?.play()
    }
}

- 或 -

如果您希望控制器仅在用户第一次看到视图时播放,那就是它,那么您可以

var played = false

func viewDidAppear() {
    if(!played) {
        let fileURL = NSURL(fileURLWithPath: "/Users/jamesjarrett/Desktop/NIMS/NIMS/NIMS/Vid2.mp4")
        playerView = AVPlayer(url: fileURL as URL)
        playerViewController.player = playerView
        self.present(playerViewController, animated: true){
            played = true
            self.playerViewController.player?.play()
        }
    }
}

不要在上面的代码中引用我,只需快速输入它就可以给你一个大致的想法。