我在KVO
上建立了具有循环播放功能的视频片段的自动播放序列。但是,除了自动播放外,我还想使用NSButton
来推进所有剪辑。因此,如果在自动播放序列时按Next Video
按钮,此操作会将我带到队列中的下一个剪辑。但这不是正确的方法。
问题是:当队列结束时,队列中的所有剪辑都没有循环。仅在第一个剪辑有一个循环(如果我按了Next Video
按钮10次– 仅第一个剪辑循环了10次),之后所有剪辑都可以正常自动播放。
问题:如何(在前进时)使用NSButton循环浏览所有视频?
这是我的代码:
import Cocoa
import AVFoundation
import AVKit
class ViewController: NSViewController {
@IBOutlet weak var avPlayerView: AVPlayerView!
@IBOutlet weak var nextVideoButton: NSButton!
@objc private let player = AVQueuePlayer()
let clips = ["One", "Two", "Three", "Four"]
private var token: NSKeyValueObservation?
override func viewDidAppear() {
super.viewDidAppear()
addAllVideosToPlayer()
}
func addAllVideosToPlayer() {
avPlayerView.player = player
for clip in clips {
let urlPath = Bundle.main.path(forResource: clip, ofType: "mov")!
let url = URL(fileURLWithPath: urlPath)
let playerItem = AVPlayerItem(url: url)
player.insert(playerItem, after: player.items().last)
token = player.observe(\.currentItem) { [weak self] player, _ in
if self!.player.items().count == 1 { self?.addAllVideosToPlayer() }
}
player.play()
avPlayerView.controlsStyle = .none
}
}
@IBAction func nextVideo(_ sender: Any) {
var number: Int = 0
let clip = clips[number]
let urlPath = Bundle.main.path(forResource: clip, ofType: "mov")!
let url = URL(fileURLWithPath: urlPath)
let playerItem = AVPlayerItem(url: url)
player.insert(playerItem, after: player.items().last)
player.advanceToNextItem()
number += 1
if number >= clips.count {
number = 0
player.advanceToNextItem()
number += 1
}
}
}
这是我的ViewController:
答案 0 :(得分:2)
您始终在此处访问第一个视频:
var quarters = [{
beginning: 11,
end: 1
},
{
beginning: 2,
end: 4
},
{
beginning: 5,
end: 7
},
{
beginning: 8,
end: 10
}
];
function findQuarter(month) {
// Sort your quarters
quarters = quarters.sort(function(a, b) {
return a.beginning < b.beginning;
});
return quarters.find(function(q) {
if (q.beginning <= q.end)
return q.beginning <= month && month <= q.end;
if (q.beginning > q.end)
return q.beginning <= month && month <= 12 ||
1 <= month && month <= q.end;
});
}
for (var i = 1; i <= 12; i++) {
console.log("For month " + i + " quarter: " + JSON.stringify(findQuarter(i)));
}
数字始终为零。将其保留为该类的成员,并在需要时进行更新。
答案 1 :(得分:0)
这是我的问题的解决方案(感谢@giorashc):
class ViewController: NSViewController {
var number: Int = 0 // class member
.........................................
.........................................
@IBAction func nextVideo(_ sender: Any) {
let clip = clips[number % 4] // modulus of 4
let urlPath = Bundle.main.path(forResource: clip, ofType: "mov")!
let url = URL(fileURLWithPath: urlPath)
let playerItem = AVPlayerItem(url: url)
player.insert(playerItem, after: player.items().last)
player.advanceToNextItem()
number += 1
}
}