连接/断开USB摄像头后,AVCaptureDevice列表不会刷新

时间:2018-04-13 21:15:28

标签: objective-c macos avfoundation avcapturedevice

我有一个简单的C或Objective-C程序,可以使用AVFoundation框架在MacOS上打印所有连接的视频设备。 当我断开连接或连接新的视频捕获设备列表时,直到我停止程序并再次运行它才会刷新。

我的代码如下:

#import <AVFoundation/AVFoundation.h>
#include <stdio.h>

void print_devices() {
  NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  for (AVCaptureDevice *device in devices) {
    const char *name = [[device localizedName] UTF8String];
    fprintf(stderr, "Device: %s\n", name);
  }
}

int main() {
  print_devices();

  sleep(10);
  // I connect or disconnect new capture device here via USB

  print_devices();
  // second print_devices(); displays exact same devices
  // as first call to this function.

  return 0;
}

我的实际程序看起来有点不同,我从Go程序调用代码,但这是最小的再现代码,看看问题出在哪里。 我总是打印相同的设备,直到我停止程序并再次启动它,然后正确检测到新设备。

捕获的地方或我在这里失踪了什么?

1 个答案:

答案 0 :(得分:1)

您需要运行一个事件循环。

最有可能的是,AVFoundation仅更新其设备列表以响应事件。你在这个应用程序中调用sleep()。在睡觉时,应用程序不会收到通知。因此,sleep()之前和之后的devices数组将是相同的。

如果您正在使用Apple的Foundation / AppKit / UIKit框架,则需要以Apple的方式编写程序。这意味着使用运行循环和计时器,而不是sleep();

相关问题