如何在 macOS 上获取 iPhone 作为 AVCaptureDevice?

How to get iPhone as AVCaptureDevice on macOS?

我已经实现了下面链接的 post 中的代码。但是,它没有更新以说明 AVCaptureDevice.devices() 现在已被弃用。

有人有这个的最新实现吗?

谢谢!

好的,所以在结合了其他一些 Stack Overflow 答案后,我能够让它与 AVCaptureDevice.DiscoverySession 的最新实现一起工作。

诀窍是在启用屏幕捕获设备后调用 DiscoverSession 来获取设备。然后添加观察者寻找新连接的设备就会显示。

之前的回答都是用了老的AVCaptureDevice.devices()方法。我下面的示例使用更新的方法。

import Cocoa
import Foundation
import AVKit
import CoreMediaIO

class PlayerNSView: NSView{
    private let playerLayer = AVPlayerLayer()
    private let nc = NotificationCenter.default

    override init(frame:CGRect){
        super.init(frame: frame)


        let urlVideo = URL(string: "https://www.radiantmediaplayer.com/media/bbb-360p.mp4")!
        let player = AVPlayer(url: urlVideo)
        //player.play()
        playerLayer.player = player
        if layer == nil{
            layer = CALayer()
        }
        layer?.addSublayer(playerLayer)

        self.enableDalDevices()

        let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.externalUnknown], mediaType: nil, position: .unspecified)



        nc.addObserver(self, selector: #selector(newDevice), name: NSNotification.Name.AVCaptureDeviceWasConnected, object: nil)

    }

    @objc func newDevice() {
        let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.externalUnknown], mediaType: nil, position: .unspecified)
        print("Devices: \(discoverySession.devices)")
    }



    public func enableDalDevices() {


        var property = CMIOObjectPropertyAddress(mSelector: CMIOObjectPropertySelector(kCMIOHardwarePropertyAllowScreenCaptureDevices), mScope: CMIOObjectPropertyScope(kCMIOObjectPropertyScopeGlobal), mElement: CMIOObjectPropertyElement(kCMIOObjectPropertyElementMaster))
        var allow : UInt32 = 1
        let sizeOfAllow = MemoryLayout.size(ofValue: allow)
        CMIOObjectSetPropertyData(CMIOObjectID(kCMIOObjectSystemObject), &property, 0, nil, UInt32(sizeOfAllow), &allow)

    }


    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layout() {
        super.layout()

        playerLayer.backgroundColor = .black
        playerLayer.frame = bounds
    }
}