簡體   English   中英

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")
    }
}

看起來像什么

如果要在每次單擊按鈕時更改視頻,則必須始終創建新的AVPlayer對象。

  1. 創建並記住您的AVPlayer對象
  2. 創建並記住您的AVPlayerLayer

-單擊按鈕時-

  1. 從父級移除AVPlayerLayer
  2. 停止AVPlayer(舊視頻)
  3. 轉到帶有新視頻網址的第1步

這是我的解決方案:

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()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM