如何捕获 AVPlayer 的 keydown 事件?
how to capture the keydown event of the AVPlayer?
我正在用macOS下的AVkit编写一个视频播放器,AVPlayer可以响应键盘事件,例如,space键向下到pause/play视频,左箭头键向下将视频后移。
我想捕获keydown事件,这样我就可以对AVPlayer做更多的控制,怎么办?
以下是我的示例代码:
import SwiftUI
import AVKit
import AVFoundation
public class VideoItem: ObservableObject {
@Published var player: AVPlayer = AVPlayer()
@Published var playerItem: AVPlayerItem?
func open(_ url: URL) {
let asset = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
self.playerItem = playerItem
player.replaceCurrentItem(with: playerItem)
}
}
public struct PlayerView: NSViewRepresentable {
@Binding var player: AVPlayer
var titles:[Title] = []
public init(player:Binding<AVPlayer>,currentSeconds:Binding<Double>,subtitleFile:Binding<String>,currentTitle:Binding<Title?>)
{
self._player = player
}
public func updateNSView(_ NSView: NSView, context: NSViewRepresentableContext<PlayerView>) {
guard let view = NSView as? AVPlayerView else {
debugPrint("unexpected view")
return
}
// status = player.timeControlStatus.rawValue
view.player = player
}
public func makeNSView(context: Context) -> NSView {
let av = AVPlayerView(frame: .zero)
return av
}
}
我有一个解决方案,可以捕获按键事件,我们可以从 AVPlayerView 创建一个子类并覆盖它的按键事件。
我正在用macOS下的AVkit编写一个视频播放器,AVPlayer可以响应键盘事件,例如,space键向下到pause/play视频,左箭头键向下将视频后移。
我想捕获keydown事件,这样我就可以对AVPlayer做更多的控制,怎么办?
以下是我的示例代码:
import SwiftUI
import AVKit
import AVFoundation
public class VideoItem: ObservableObject {
@Published var player: AVPlayer = AVPlayer()
@Published var playerItem: AVPlayerItem?
func open(_ url: URL) {
let asset = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
self.playerItem = playerItem
player.replaceCurrentItem(with: playerItem)
}
}
public struct PlayerView: NSViewRepresentable {
@Binding var player: AVPlayer
var titles:[Title] = []
public init(player:Binding<AVPlayer>,currentSeconds:Binding<Double>,subtitleFile:Binding<String>,currentTitle:Binding<Title?>)
{
self._player = player
}
public func updateNSView(_ NSView: NSView, context: NSViewRepresentableContext<PlayerView>) {
guard let view = NSView as? AVPlayerView else {
debugPrint("unexpected view")
return
}
// status = player.timeControlStatus.rawValue
view.player = player
}
public func makeNSView(context: Context) -> NSView {
let av = AVPlayerView(frame: .zero)
return av
}
}
我有一个解决方案,可以捕获按键事件,我们可以从 AVPlayerView 创建一个子类并覆盖它的按键事件。