import sounddevice as sd
def get_default_speaker_info():
"""使用 sounddevice 获取默认音频设备的详细信息"""
try:
# 获取默认音频设备信息
devices = sd.query_devices()
default_device_idx = sd.default.device[1] # 默认输出设备索引
default_device = devices[default_device_idx]
# 获取设备名称
device_name = default_device['name']
# 获取通道数
channels = default_device['max_output_channels']
# 获取支持的采样率
# sounddevice 可以通过 extra_settings 获取更多设备信息
supported_samplerates = []
# 常见的采样率列表
common_rates = [8000, 11025, 16000, 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 352800, 384000]
# 检查设备支持的采样率
for rate in common_rates:
try:
sd.check_output_settings(device=default_device_idx, samplerate=rate, channels=min(channels, 2))
supported_samplerates.append(rate)
except Exception:
# 不支持的采样率
pass
# 使用第一个支持的采样率作为默认值
default_samplerate = supported_samplerates[0] if supported_samplerates else 44100
return {
'device_name': device_name,
'channels': channels,
'default_samplerate': default_samplerate,
'supported_samplerates': supported_samplerates
}
except Exception as e:
return {'error': str(e)}
def list_all_devices():
"""列出所有音频设备的信息"""
try:
devices = sd.query_devices()
print("=== 所有音频设备信息 ===")
print(devices)
return devices
except Exception as e:
print(f"获取设备信息时出错: {e}")
return None
def main():
"""主函数,打印默认扬声器信息"""
print("正在获取默认音频设备信息...")
# 首先列出所有设备
list_all_devices()
# 获取默认设备信息
speaker_info = get_default_speaker_info()
if 'error' in speaker_info:
print(f"获取音频设备信息时出错: {speaker_info['error']}")
return
print("\n=== 默认音频设备信息 ===")
print(f"设备名称: {speaker_info['device_name']}")
print(f"最大输出通道数: {speaker_info['channels']}")
print(f"推荐采样率: {speaker_info['default_samplerate']} Hz")
if speaker_info['supported_samplerates']:
print(f"支持的采样率: {', '.join([str(rate) + ' Hz' for rate in speaker_info['supported_samplerates']])}")
else:
print("未能检测到支持的采样率")
if __name__ == "__main__":
main()