Swift 3、XCode 8 - 按下按钮时更改本地视频 - AVPlayer

Swift 3, XCode 8 - Changing Local Video on Button Press - AVPlayer

我正在尝试创建一个应用程序,它会在每次按下按钮时更改视频。

当前:视频循环播放,按钮无任何反应

目标: 该按钮将根据数组索引循环到下一个视频。我计划将另一个数组与文本描述相关联,以配合每个视频。

想法: 我认为基于 JSON 的实现可能会更好。这是我的第一个 iOS 应用程序,我尽量保持简单。非常感谢您的想法和帮助!

这是循环播放视频的函数。视频名称保存在名为 videoId 的数组中:

class WorkoutViewController: UIViewController{
@IBOutlet weak var videoView: UIView!
@IBOutlet weak var infoCardView: UIView!

var currentVidIndex: Int = 0    

var player: AVPlayer?
var playerLayer: AVPlayerLayer?    

override func viewDidLoad() {
    super.viewDidLoad()
    shadowBackground()
}
var videoId: [String] = ["bodyweight_fitness_arch","bodyweight_fitness_assisted_squat","bodyweight_fitness_band_dislocates"]


func setLoopingVideo(){
    let path = Bundle.main.path(forResource: videoId[currentVidIndex], ofType: "mp4")
    let url = URL.init(fileURLWithPath: path!)
    let player = AVPlayer(url: url)
    let playerLayer = AVPlayerLayer(player: player) 
    playerLayer.frame = videoView.bounds
    self.videoView.layer.insertSublayer(playerLayer, at: 0)
    player.play()

    // Create observer to monitor when video ends, when it does so set the video time to the start (zero)

    NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: player.currentItem, queue: nil)

    {
        Notification in player.seek(to: kCMTimeZero)
        player.play()  
    }   

func shadowBackground(){
    infoCardView.layer.cornerRadius = 3.0
    infoCardView.layer.shadowColor = 
           UIColor.black.withAlphaComponent(0.6).cgColor
    infoCardView.layer.shadowOffset = CGSize(width: 0, height: 0)
    infoCardView.layer.shadowOpacity = 0.9        

    videoView.layer.cornerRadius = 3.0
    videoView.layer.shadowColor = 
    UIColor.black.withAlphaComponent(0.6).cgColor
    videoView.layer.shadowOffset = CGSize(width: 0, height: 0)
    videoView.layer.shadowOpacity = 0.9

}
override func viewDidAppear(_ animated: Bool) {
    setLoopingVideo()
}

@IBAction func showNextVideo(_ sender: UIButton) {
    if currentVidIndex < videoId.count{
        currentVidIndex += 1
        print (currentVidIndex)
    } else {
        NSLog("Nothing")
    }
}

What it looks like

如果您想在每次单击按钮时更改视频,则必须始终创建新的 AVPlayer 对象。

  1. 创建并记住您的 AVPlayer 对象
  2. 创建并记住您的 AVPlayerLayer

-- 当按钮被点击时 --

  1. 从父级移除 AVPlayerLayer
  2. 停止 AVPlayer(旧视频)
  3. 使用新视频转到第 1 步 URL

这是我的解决方案:

func clearVid(){
    if let player = self.player{
        player.pause()
        self.player = nil

    }
    if let layer = self.playerLayer{
        layer.removeFromSuperlayer()
        self.playerLayer = nil
    }

   self.videoView.layer.sublayers?.removeAll()
}