最近想完善视音频设备功能,所以研究下windows的热插拔实现。本篇主要介绍视音频设备,如摄像头、麦克风、扬声器等热插拔的代码实现。
新建一个DeviceDetector类来实现热插拔功能,如下:
1、开始监测设备热插拔
要监测的设备GUID
static GUID GUID_DEVINTERFACE_LIST[] =
{
// KSCATEGORY_AUDIO
{
0x6994AD04, 0x93EF, 0x11D0,{
0xA3, 0xCC, 0x00, 0xA0, 0xC9, 0x22, 0x31, 0x96 } },
// GUID_DEVINTERFACE_USB_DEVICE
{
0xA5DCBF10, 0x6530, 0x11D2,{
0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } }
};
启动监测线程
int DeviceDetector::startDetect()
{
if (m_detecting) {
return ERROR_CODE_OK;
}
m_detecting = true;
m_thread = std::thread(std::bind(&DeviceDetector::detecting, this));
return ERROR_CODE_OK;
}
监测线程函数。获取摄像头、麦克风、扬声器设备列表,注册监测窗口并处理窗口消息。
void DeviceDetector::detecting()
{
m_hwnd = createDevice();
registerDevice(m_hwnd);
VideoDevice::getCameraDevices(m_cameras);
AudioDevice::getMicDevices(m_mics);
AudioDevice::getSpeakerDevices(m_speakers);
MSG msg;
while (GetMessageA(&msg, m_hwnd, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessageA(&msg);
}
}
获取摄像头、麦克风、扬声器设备列表的实现详见《【音视频】获取音频设备-mmdeviceapi(八)》和《【音视频】获取视频设备-MMDeviceAPI&MONITORINFOEX(2-3)》。
下面是创建、注册监测窗口(隐藏窗口)实现。
HWND DeviceDetector::createDevice()
{
WNDCLASSA wc;
SecureZeroMemory(&wc, sizeof(wc));
wc.lpszClassName = "__hcmdr_device_detector__";
wc.lpfnWndProc = DeviceDetector::deviceChanged;
RegisterClassA(&wc);
HWND hwnd = CreateWindowA(wc.lpszClassName, "", 0, 0, 0, 0, 0, nullptr, nullptr,
GetModuleHandleA(nullptr), nullptr);
return hwnd;
}
void DeviceDetector::registerDevice(HWND hwnd)
{
HDEVNOTIFY hDevNotify;
DEV_BROADCAST_DEVICEINTERFACE_A notificationFilter;
SecureZeroMemory(¬ificationFilter, sizeof(notificationFilter));
notificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE_A)