bsw215583320
2025-01-13 230ededfe695de5d6d3b994dc9404343090cba5c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import comtypes
from comtypes.gen import DirectShowLib
 
class EnumerateDevices(object):
    def __init__(self, device_type):
        self._device_type = device_type
        self._devices = []
 
    def _enumerate(self):
        system_device_enumerator = comtypes.CoCreateInstance(
            DirectShowLib.CLSID_SystemDeviceEnum,
            None,
            comtypes.CLSCTX_INPROC_SERVER,
            DirectShowLib.IID_ICreateDevEnum
        )
        enum_moniker = system_device_enumerator.CreateClassEnumerator(self._device_type, 0)
        if enum_moniker is None:
            raise Exception("No devices found")
        moniker, num_fetched = enum_moniker.Next(1)
 
        while moniker is not None:
            dev_moniker = moniker.QueryInterface(comtypes.IMoniker)
            dev_name, dev_class = self._get_dev_info(dev_moniker)
            self._devices.append((dev_name, dev_class))
            moniker, num_fetched = enum_moniker.Next(1)
 
    def _get_dev_info(self, dev_moniker):
        dev_prop_bag = dev_moniker.BindToStorage(0, 0, comtypes.IID_IPersistPropertyBag)
        dev_prop_bag = dev_prop_bag.QueryInterface(DirectShowLib.IID_IPersistPropertyBag)
        dev_name = comtypes.VARIANT()
        dev_class = comtypes.VARIANT()
        dev_prop_bag.Read("FriendlyName", dev_name, None)
        dev_prop_bag.Read("DevicePath", dev_class, None)
        return dev_name.value, dev_class.value
 
    def get_devices(self):
        self._enumerate()
        return self._devices
 
if __name__ == '__main__':
    video_input_devices = EnumerateDevices(DirectShowLib.CLSID_VideoInputDeviceCategory)
    print(video_input_devices.get_devices())