py_audio_scanner.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import numpy as np
  4. import sounddevice as sd
  5. def detect_audio_devices():
  6. """
  7. 检测并列出所有音频设备 (使用sounddevice)
  8. """
  9. print("\n===== 音频设备检测 (SoundDevice) =====\n")
  10. # 获取默认设备
  11. default_input = sd.default.device[0] if sd.default.device else None
  12. default_output = sd.default.device[1] if sd.default.device else None
  13. # 存储找到的设备
  14. input_devices = []
  15. output_devices = []
  16. # 列出所有设备
  17. devices = sd.query_devices()
  18. for i, dev_info in enumerate(devices):
  19. # 打印设备信息
  20. print(f"设备 {i}: {dev_info['name']}")
  21. print(f" - 输入通道: {dev_info['max_input_channels']}")
  22. print(f" - 输出通道: {dev_info['max_output_channels']}")
  23. print(f" - 默认采样率: {dev_info['default_samplerate']}")
  24. # 标记默认设备
  25. if i == default_input:
  26. print(" - 🎤 系统默认输入设备")
  27. if i == default_output:
  28. print(" - 🔊 系统默认输出设备")
  29. # 识别输入设备(麦克风)
  30. if dev_info["max_input_channels"] > 0:
  31. input_devices.append((i, dev_info["name"]))
  32. if "USB" in dev_info["name"]:
  33. print(" - 可能是USB麦克风 🎤")
  34. # 识别输出设备(扬声器)
  35. if dev_info["max_output_channels"] > 0:
  36. output_devices.append((i, dev_info["name"]))
  37. if "Headphones" in dev_info["name"]:
  38. print(" - 可能是耳机输出 🎧")
  39. elif "USB" in dev_info["name"] and dev_info["max_output_channels"] > 0:
  40. print(" - 可能是USB扬声器 🔊")
  41. print("")
  42. # 总结找到的设备
  43. print("\n===== 设备总结 =====\n")
  44. print("找到的输入设备(麦克风):")
  45. for idx, name in input_devices:
  46. default_mark = " (默认)" if idx == default_input else ""
  47. print(f" - 设备 {idx}: {name}{default_mark}")
  48. print("\n找到的输出设备(扬声器):")
  49. for idx, name in output_devices:
  50. default_mark = " (默认)" if idx == default_output else ""
  51. print(f" - 设备 {idx}: {name}{default_mark}")
  52. # 推荐设备
  53. print("\n推荐设备配置:")
  54. # 推荐麦克风
  55. recommended_mic = None
  56. if default_input is not None:
  57. recommended_mic = (default_input, devices[default_input]["name"])
  58. elif input_devices:
  59. # 优先USB设备
  60. for idx, name in input_devices:
  61. if "USB" in name:
  62. recommended_mic = (idx, name)
  63. break
  64. if recommended_mic is None:
  65. recommended_mic = input_devices[0]
  66. # 推荐扬声器
  67. recommended_speaker = None
  68. if default_output is not None:
  69. recommended_speaker = (default_output, devices[default_output]["name"])
  70. elif output_devices:
  71. # 优先耳机
  72. for idx, name in output_devices:
  73. if "Headphones" in name:
  74. recommended_speaker = (idx, name)
  75. break
  76. if recommended_speaker is None:
  77. recommended_speaker = output_devices[0]
  78. if recommended_mic:
  79. print(f" - 麦克风: 设备 {recommended_mic[0]} ({recommended_mic[1]})")
  80. else:
  81. print(" - 未找到可用麦克风")
  82. if recommended_speaker:
  83. print(f" - 扬声器: 设备 {recommended_speaker[0]} ({recommended_speaker[1]})")
  84. else:
  85. print(" - 未找到可用扬声器")
  86. print("\n===== SoundDevice配置示例 =====\n")
  87. if recommended_mic:
  88. print("# 麦克风初始化代码")
  89. print(f"input_device_id = {recommended_mic[0]} # {recommended_mic[1]}")
  90. print("input_stream = sd.InputStream(")
  91. print(" samplerate=16000,")
  92. print(" channels=1,")
  93. print(" dtype=np.int16,")
  94. print(" blocksize=1024,")
  95. print(f" device={recommended_mic[0]},")
  96. print(" callback=input_callback)")
  97. if recommended_speaker:
  98. print("\n# 扬声器初始化代码")
  99. print(
  100. f"output_device_id = {recommended_speaker[0]} # "
  101. f"{recommended_speaker[1]}"
  102. )
  103. print("output_stream = sd.OutputStream(")
  104. print(" samplerate=44100,")
  105. print(" channels=1,")
  106. print(" dtype=np.int16,")
  107. print(" blocksize=1024,")
  108. print(f" device={recommended_speaker[0]},")
  109. print(" callback=output_callback)")
  110. print("\n===== 设备测试 =====\n")
  111. # 测试推荐设备
  112. if recommended_mic:
  113. print(f"正在测试麦克风 (设备 {recommended_mic[0]})...")
  114. try:
  115. sd.rec(
  116. int(1 * 16000),
  117. samplerate=16000,
  118. channels=1,
  119. device=recommended_mic[0],
  120. dtype=np.int16,
  121. )
  122. sd.wait()
  123. print("✓ 麦克风测试成功")
  124. except Exception as e:
  125. print(f"✗ 麦克风测试失败: {e}")
  126. if recommended_speaker:
  127. print(f"正在测试扬声器 (设备 {recommended_speaker[0]})...")
  128. try:
  129. # 生成测试音频 (440Hz正弦波)
  130. duration = 0.5
  131. sample_rate = 44100
  132. t = np.linspace(0, duration, int(sample_rate * duration))
  133. test_audio = (0.3 * np.sin(2 * np.pi * 440 * t)).astype(np.int16)
  134. sd.play(test_audio, samplerate=sample_rate, device=recommended_speaker[0])
  135. sd.wait()
  136. print("✓ 扬声器测试成功")
  137. except Exception as e:
  138. print(f"✗ 扬声器测试失败: {e}")
  139. return recommended_mic, recommended_speaker
  140. if __name__ == "__main__":
  141. try:
  142. mic, speaker = detect_audio_devices()
  143. print("\n检测完成!")
  144. except Exception as e:
  145. print(f"检测过程中出错: {e}")