繁体   English   中英

MacOS 使用 AVFoundation 截图

[英]MacOS take a Screenshot with AVFoundation

我有 Swift 代码:

    func makeSceenshot() {
        // Set up the inputs
        var displayCount: UInt32 = 0;
        var result = CGGetActiveDisplayList(0, nil, &displayCount)
        if (result != CGError.success) {
            print("error when try to get displays: \(result)")
            return
        }
        let allocated = Int(displayCount)
        let activeDisplays = UnsafeMutablePointer<CGDirectDisplayID>.allocate(capacity: allocated)
        result = CGGetActiveDisplayList(displayCount, activeDisplays, &displayCount)
        
        if (result != CGError.success) {
            print("error whe try get displays list: \(result)")
            return
        }
        
        for i in 1...displayCount {
            // Set up the input
            let display: CGDirectDisplayID = activeDisplays[Int(i-1)]
            guard let input = AVCaptureScreenInput(displayID: display) else {
                    print("error AVCaptureScreenInput")
                    return
            }
            input.minFrameDuration = CMTimeMake(value: 1, timescale: Int32(FPS))
            
            let session = AVCaptureSession()
            
            if session.canAddInput(input) {
                print("Input added")
                session.addInput(input)
            } else {
                print("Input error")
            }
            
            // Set up the output
            let output = AVCapturePhotoOutput()
            let screenshotSettings = AVCapturePhotoSettings()
            
            if session.canAddOutput(output) {
                print("Output added")
                session.addOutput(output)
            } else {
                print("Output error")
            }
            
            session.startRunning()
                
            output.capturePhoto(with: screenshotSettings, delegate: self)
                
            session.stopRunning()
            
        }
  
    }

}

和代表:

extension ViewController: AVCapturePhotoCaptureDelegate {
        func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
            
            if (error != nil) {
                print("\(String(describing: error?.localizedDescription)) debug: \(error.debugDescription)")
                return
            }
            
            guard let imageData = photo.cgImageRepresentation() else {
                    print("eror")
                    return
            }
            
            let unixTimestamp = CreateTimeStamp()
            let path = folderName + "\(unixTimestamp)" + ".jpg"
            let fileUrl = URL(fileURLWithPath: path, isDirectory: true)
            let bitmapRep = NSBitmapImageRep(cgImage: imageData.takeUnretainedValue())
            let jpegData = bitmapRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
    
            do {
                try jpegData.write(to: fileUrl, options: .atomic)
            }
            catch {print("error: \(error)")}
        }
    
        func CreateTimeStamp() -> Int32
          {
              return Int32(Date().timeIntervalSince1970)
          }
    }

我有一个问题:当我点击按钮时,我需要从所有 Mac 显示器上截屏。 但是当我点击按钮时,我在日志中收到这条消息:

Optional("The operation could not be completed") debug: Optional(Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSLocalizedDescription=The operation could not be completed, NSLocalizedFailureReason=An unknown error occurred (-11800)})
    

但是这个 function

截图()

如果我从viewDidLoad()启动它,但它不会从按钮操作启动

有任何想法吗?

您可以使用:

let id = CGMainDisplayID()
let image = CGDisplayCreateImage(id)

然后,将弹出一个警报,要求用户授予您的应用屏幕录制权限。 当用户将您的应用添加到安全和隐私设置中的列表时,CGDisplayCreateImage 将捕获所有 windows 和整个屏幕。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM