如何用Python筛选并列出系统中真实可用的麦克风设备?
筛选PyAudio中的真实麦克风输入设备
要筛选出系统「设置>系统>声音」中显示的真实麦克风,可通过两个核心条件过滤设备列表:
- 仅保留具备输入通道的设备(排除纯输出设备)
- 排除虚拟/重复设备(通过名称去重或指定系统原生音频API)
方法1:基础过滤+去重
先筛选出有输入通道的设备,再通过设备名称去重,避免同一物理设备被不同音频API重复识别:
import pyaudio p = pyaudio.PyAudio() print("Available real audio input devices:") seen_devices = set() for i in range(p.get_device_count()): dev_info = p.get_device_info_by_index(i) # 仅保留输入设备(输入通道数>0) if dev_info['maxInputChannels'] > 0: dev_name = dev_info['name'].strip() # 去重:合并同一物理设备的重复条目 if dev_name not in seen_devices: seen_devices.add(dev_name) print(f"{i}: {dev_name}") device_index = int(input("Enter the index of the audio input device you want to use: ")) p.terminate()
方法2:指定系统原生API(更精准)
如果基础去重仍存在虚拟设备,可指定使用系统默认的音频API(Windows用WASAPI,macOS用Core Audio),系统设置里的设备通常通过这些API暴露:
Windows(WASAPI)
import pyaudio p = pyaudio.PyAudio() WASAPI_API_INDEX = p.get_host_api_by_type(pyaudio.paWASAPI)['index'] print("Available real audio input devices (WASAPI):") seen_devices = set() for i in range(p.get_device_count()): dev_info = p.get_device_info_by_index(i) # 筛选WASAPI下的输入设备并去重 if dev_info['hostApi'] == WASAPI_API_INDEX and dev_info['maxInputChannels'] > 0: dev_name = dev_info['name'].strip() if dev_name not in seen_devices: seen_devices.add(dev_name) print(f"{i}: {dev_name}") device_index = int(input("Enter the index of the audio input device you want to use: ")) p.terminate()
macOS(Core Audio)
import pyaudio p = pyaudio.PyAudio() COREAUDIO_API_INDEX = p.get_host_api_by_type(pyaudio.paCoreAudio)['index'] print("Available real audio input devices (Core Audio):") seen_devices = set() for i in range(p.get_device_count()): dev_info = p.get_device_info_by_index(i) # 筛选Core Audio下的输入设备并去重 if dev_info['hostApi'] == COREAUDIO_API_INDEX and dev_info['maxInputChannels'] > 0: dev_name = dev_info['name'].strip() if dev_name not in seen_devices: seen_devices.add(dev_name) print(f"{i}: {dev_name}") device_index = int(input("Enter the index of the audio input device you want to use: ")) p.terminate()
关键说明
maxInputChannels > 0:确保只保留能接收音频输入的设备,排除扬声器、耳机等纯输出设备- 去重逻辑:同一物理设备可能被MME、WASAPI等多个音频API识别,导致重复条目,通过名称去重可合并这些冗余项
- 指定API:系统设置内显示的设备与系统原生音频API绑定,此方法能精准匹配系统可见的真实设备
内容的提问来源于stack exchange,提问作者Nitaki
相关产品推荐
相关产品推荐

