如何在macOS上将iPhone用作AVCaptureDevice?

问题描述 投票:-1回答:1

我已经实现了下面链接中的代码。但是,由于当前不建议使用AVCaptureDevice.devices(),因此尚未更新。

iOS Device not listed by AVCaptureDevice.devices() unless Quicktime is opened

有人有最新的实现吗?

谢谢!

swift iphone macos avcapturedevice core-media
1个回答
0
投票

好,所以在结合了其他一些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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.