Я использую этот проект от Github в качестве базы: https://github.com/banjun/PhotoStudioPlayer
Он работает при захвате экрана одного устройства. Когда я пытаюсь получить второй одновременно, я получаю сообщение об ошибке. Любопытно, что время от времени он работает случайным образом, так как я могу это исправить?
Часть кода ViewController:
import Cocoa
import AVFoundation
class ViewController: NSViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
var device: AVCaptureDevice? = nil {
didSet { setupPreviewLayer() }
}
private var session: AVCaptureSession?
private var previewLayer: AVCaptureVideoPreviewLayer? {
didSet {
oldValue?.removeFromSuperlayer()
previewLayer?.videoGravity = .resizeAspect
guard let layer = view.layer, let newValue = previewLayer else { return }
newValue.frame = layer.bounds
newValue.autoresizingMask = [.layerWidthSizable, .layerHeightSizable]
layer.addSublayer(newValue)
}
}
private lazy var videoDataOutput: AVCaptureVideoDataOutput = {
let o = AVCaptureVideoDataOutput()
o.setSampleBufferDelegate(self, queue: videoDataQueue)
return o
}()
private let videoDataQueue = DispatchQueue.global(qos: .userInitiated)
private var movieOutput: AVCaptureMovieFileOutput?
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
NotificationCenter.default.addObserver(forName: AppDelegate.AppGlobalStateDidChange, object: nil, queue: nil) { [weak self] _ in
self?.readyCaptureFrameIfNeeded()
self?.changeWindowLevelIfNeeded()
}
NotificationCenter.default.addObserver(forName: .AVCaptureSessionRuntimeError, object: nil, queue: nil) { n in
if n.object as? AVCaptureSession != self.session {
return
}
if let error = n.userInfo?["AVCaptureSessionErrorKey"] as? Error {
if let window = self.view.window {
self.presentError(error, modalFor: window, delegate: self, didPresent: #selector(self.closeWindow(_:)), contextInfo: nil)
} else {
self.presentError(error)
}
}
}
}
override func viewDidLayout() {
super.viewDidLayout()
guard let layer = view.layer else { return }
previewLayer?.frame = layer.bounds
}
override func viewDidAppear() {
super.viewDidAppear()
if let w = view.window {
w.title = ""
// w.isOpaque = false
// w.backgroundColor = .clear
// w.hasShadow = false
// w.styleMask = .borderless
// w.titleVisibility = .visible
w.isMovableByWindowBackground = true
}
}
func setupPreviewLayer() {
guard let device = device else { return }
self.session?.stopRunning()
let session = AVCaptureSession()
do {
let input = try AVCaptureDeviceInput(device: device)
session.addInput(input)
readyCaptureFrameIfNeeded()
previewLayer = AVCaptureVideoPreviewLayer(session: session)
view.layerUsesCoreImageFilters = true
switchToCoolStage(nil)
self.session = session
session.startRunning()
} catch {
NSLog("%@", "\(error)")
}
}