我试图获得音频设备的GUID。GUID可以在注册表ComputerHKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionMMDevicesAudioRender
中找到,GUID应该看起来像{0.0.0.00000000}.{37e73048-025a-47ea-bf9f-59d5ef8f2b43}
基本上是这样的。但是我想在python中获取音频输出设备(扬声器,耳机)的GUID
我已经尝试过了,但我唯一能找到的是使用命令行并在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)
This works for me