gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:32:50 24 4
gpt4 key购买 nike

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

当前:视频循环播放,按钮不执行任何操作

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

想法:我认为基于 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

-- 单击按钮时 --

  • 从父级中删除 AVPlayerLayer
  • 停止 AVPlayer(旧视频)
  • 使用新视频网址转到第 1 步
  • 关于ios - Swift 3、XCode 8 - 按下按钮时更改本地视频 - AVPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43287182/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com