在 Python 中获取音频设备 GUID

get audio device GUID in Python

我正在尝试获取音频设备的 GUID。 GUID 可以在注册表中找到 Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\ guid 应该看起来像 {0.0.0.00000000}.{37e73048-025a-47ea-bf9f-59d5ef8f2b43}

基本上是这样的。但我想要 python

我自己试过了,但我唯一能找到的就是使用命令行并在 Python

中解析它
import subprocess

sd = subprocess.run(
    ["pnputil", "/enum-devices", "/connected", "/class", "AudioEndpoint"],
    capture_output=True,
    text=True,
)

output = sd.stdout.split("\n")[1:-1]

def getDevices(devices):
    deviceList = {}
    for device in range(len(devices)):
        if "Instance ID:" in devices[device]:
            deviceList[devices[device+1].split(":")[-1].strip()] = devices[device].split("\")[-1].strip()
    return deviceList

print(getDevices(output))

这让我感动

{'Headset (Soundcore Life Q30 Hands-Free)': '{0.0.0.00000000}.{4ac89ef7-f00d-4069-b96b-421bd3276295}', 'Speakers (Echo Dot-BQP)': '{0.0.0.00000000}.{8085b216-297a-4d02-bc3d-83b997b79524}', 'Headphones (Soundcore Life Q30)': '{0.0.0.00000000}.{37e73048-025a-47ea-bf9f-59d5ef8f2b43}'}

希望有更好的方法

from __future__ import print_function
import comtypes
from pycaw.pycaw import AudioUtilities, IMMDeviceEnumerator, EDataFlow, DEVICE_STATE
from pycaw.constants import CLSID_MMDeviceEnumerator

def MyGetAudioDevices(direction="in", State = DEVICE_STATE.ACTIVE.value):
    devices = []
    # for all use EDataFlow.eAll.value
    if direction == "in":
        Flow = EDataFlow.eCapture.value     # 1
    else:
        Flow = EDataFlow.eRender.value      # 0
    
    deviceEnumerator = comtypes.CoCreateInstance(
        CLSID_MMDeviceEnumerator,
        IMMDeviceEnumerator,
        comtypes.CLSCTX_INPROC_SERVER)
    if deviceEnumerator is None:
        return devices
    

    collection = deviceEnumerator.EnumAudioEndpoints(Flow, State)
    if collection is None:
        return devices

    count = collection.GetCount()
    for i in range(count):
        dev = collection.Item(i)
        if dev is not None:
            if not ": None" in str(AudioUtilities.CreateDevice(dev)):
                devices.append(AudioUtilities.CreateDevice(dev))
    return devices

output_device = MyGetAudioDevices("out")
input_device = MyGetAudioDevices("in")

print(output_device)
print(input_device)

这对我有用