【问题标题】:Unable to get devices using AVCaptureDevice无法使用 AVCaptureDevice 获取设备
【发布时间】:2015-09-16 03:26:20
【问题描述】:

我设法找到了一些代码,可以让我访问手机的设备(例如相机)。问题是当我使用 Xcode 编译代码(并且打印不同的设备)时,我得到一个空数组。

这是我写的:

import UIKit
import AVFoundation

class ViewController: UIViewController {

  let captureSession = AVCaptureSession()
  var previewLayer : AVCaptureVideoPreviewLayer?

  // If we find a device we'll store it here for later us
  var captureDevice : AVCaptureDevice?

  override func viewDidLoad() {
    super.viewDidLoad()            
    // Do any additional setup after loading the view, typically from a nib.

    captureSession.sessionPreset = AVCaptureSessionPresetHigh

    let devices = AVCaptureDevice.devices()
    println(devices)
    // Loop through all the capture devices on this phone
    for (device in devices) {
        // Make sure this particular device supports video
        if (device.hasMediaType(AVMediaTypeVideo)) {
         // Finally check the position and confirm we've got the back camera
            if(device.position == AVCaptureDevicePosition.Back) {
                captureDevice = device as? AVCaptureDevice
                if captureDevice != nil {
                    println("Capture device found")
                    beginSession()
                }
            }
        }
      }

    }

    func beginSession() {

      var err : NSError? = nil
      captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))

      if err != nil {
          println("error: \(err?.localizedDescription)")
      }

      previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
      self.view.layer.addSublayer(previewLayer)
      previewLayer?.frame = self.view.layer.frame

      captureSession.startRunning()

    }

  }

你对我为什么得到一个空数组有任何想法吗?

【问题讨论】:

  • 您在设备上试用吗?

标签: ios swift camera avcapturesession avcapturedevice


【解决方案1】:

检查 Swift 4 的当前授权状态

 AVCaptureDevice.authorizationStatus(for: AVMediaType.video)

【讨论】:

  • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 【如何写出好的答案? ](stackoverflow.com/help/how-to-answer)
【解决方案2】:

首先查看授权的当前状态

AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)

更多细节你可以阅读this article

【讨论】:

    【解决方案3】:

    如果您只在模拟器中运行它,则该数组将始终为空,因为它没有可供选择的物理硬件。事实上,如果你试图访问模拟器内部的物理硬件,它就会崩溃。如果您插入设备但仍然得到一个空数组,请告诉我。

    【讨论】:

    • 是的,因为发布的代码与 Apple 文档中的代码非常相似,而找不到绝对 zero AVCaptureDevices 的一个常见原因是因为它正在在模拟器中运行。以下是带有类似 OP 代码的文档:developer.apple.com/library/prerelease/ios/documentation/…
    • 这绝对是正确答案。世界上谁反对这个??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多