如何在Mac OS Mojave的Swift游乐场中访问相机? 过去在High Sierra上可以正常使用,但是代码似乎无法正确执行,因为操场上的运行符号不断旋转,并且相机灯不亮。
我得到了一个示例代码,该代码去年可以正常工作,但今天不再可用了,有人知道出了什么问题以及如何解决它吗?
import Cocoa
import AVFoundation
import AVKit
import QuartzCore
import PlaygroundSupport
let view = NSView(frame: NSRect(x: 0.0, y: 0.0, width: 640.0, height: 480.0))
let session = AVCaptureSession()
session.sessionPreset = AVCaptureSession.Preset.vga640x480
session.beginConfiguration()
session.commitConfiguration()
var input : AVCaptureDeviceInput
if let devices : [AVCaptureDevice] = AVCaptureDevice.devices() as? [AVCaptureDevice] {
for device in devices {
if device.hasMediaType(AVMediaType.video) && device.supportsSessionPreset(AVCaptureSession.Preset.vga640x480) {
do {
input = try AVCaptureDeviceInput(device: device as AVCaptureDevice) as AVCaptureDeviceInput
if session.canAddInput(input) {
session.addInput(input)
break
}
}
catch {
error
}
}
}
let output = AVCaptureVideoDataOutput()
output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable as! String: Int(kCVPixelFormatType_32BGRA)]
output.alwaysDiscardsLateVideoFrames = true
if session.canAddOutput(output) {
session.addOutput(output)
}
let captureLayer = AVCaptureVideoPreviewLayer(session: session)
view.wantsLayer = true
view.layer = captureLayer
session.startRunning()
//View -> Assistant Editor -> Show Assistant Editor
PlaygroundPage.current.liveView = view
}
查看了关于如何请求访问我尝试过的相机的苹果文档,但是它似乎在操场上不起作用,因为实施该相机时我仍然遇到相同的问题。
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized: // The user has previously granted access to the camera.
self.setupCaptureSession()
case .notDetermined: // The user has not yet been asked for camera access.
AVCaptureDevice.requestAccess(for: .video) { granted in
if granted {
self.setupCaptureSession()
}
}
case .denied: // The user has previously denied access.
return
case .restricted: // The user can't grant access due to restrictions.
return
}