example.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. """
  2. 语音唤醒模块使用示例(支持AEC回音消除)
  3. 演示如何使用独立的语音唤醒模块,包括AEC功能
  4. """
  5. import asyncio
  6. import sys
  7. from pathlib import Path
  8. sys.path.insert(0, str(Path(__file__).parent.parent))
  9. from wake_word_module import WakeWordDetector, AudioCapture, WakeWordConfig, AECProcessor
  10. async def main():
  11. """主函数"""
  12. print("=" * 60)
  13. print("语音唤醒模块示例(支持AEC)")
  14. print("=" * 60)
  15. # 1. 列出可用音频设备
  16. print("\n1. 列出可用音频设备:")
  17. AudioCapture.list_devices()
  18. # 2. 创建配置
  19. print("\n2. 创建语音唤醒配置:")
  20. # 假设模型文件在 models 目录下
  21. model_path = Path("models")
  22. if not model_path.exists():
  23. print(f"错误: 模型目录不存在: {model_path}")
  24. print("请确保以下文件存在于模型目录中:")
  25. print("encoder.onnx")
  26. print("decoder.onnx")
  27. print("joiner.onnx")
  28. print("tokens.txt")
  29. print("keywords.txt")
  30. return
  31. config = WakeWordConfig(
  32. model_path=str(model_path),
  33. sample_rate=16000,
  34. num_threads=4,
  35. provider="cpu",
  36. keywords_score=1.8,
  37. keywords_threshold=0.2,
  38. detection_cooldown=1.5,
  39. )
  40. print(f" 模型路径: {config.model_path}")
  41. print(f" 采样率: {config.sample_rate}Hz")
  42. print(f" 检测阈值: {config.keywords_threshold}")
  43. # 3. 创建音频采集器(启用AEC)
  44. print("\n3. 创建音频采集器:")
  45. print(" 是否启用AEC回音消除: 是")
  46. audio_capture = AudioCapture(
  47. sample_rate=16000,
  48. channels=1,
  49. device_id=None, # 自动选择设备
  50. enable_aec=True, # 启用AEC回音消除
  51. )
  52. # 4. 创建唤醒词检测器
  53. print("\n4. 创建唤醒词检测器:")
  54. detector = WakeWordDetector(config)
  55. # 5. 设置回调函数
  56. def on_wake_word_detected(result, full_text):
  57. """唤醒词检测回调"""
  58. print("\n" + "=" * 60)
  59. print("🎉 检测到唤醒词!唤醒成功!✅")
  60. print(f" 结果: {result}")
  61. print(f" 完整文本: {full_text}")
  62. print("=" * 60 + "\n")
  63. def on_error(error):
  64. """错误回调"""
  65. print(f"❌ 唤醒词检测错误: {error}")
  66. detector.on_detected(on_wake_word_detected)
  67. detector.on_error(on_error)
  68. # 6. 连接音频采集器和检测器
  69. print("\n5. 连接音频采集器和检测器:")
  70. audio_capture.add_audio_listener(detector)
  71. # 7. 启动系统
  72. print("\n6. 启动系统:")
  73. try:
  74. await audio_capture.start()
  75. await detector.start()
  76. print("\n✅ 语音唤醒系统已启动!")
  77. print(" AEC回音消除: 已启用")
  78. print(" 请说出唤醒词进行测试...")
  79. print(" 按 Ctrl+C 停止程序\n")
  80. # 保持运行
  81. while True:
  82. await asyncio.sleep(1)
  83. except KeyboardInterrupt:
  84. print("\n\n收到停止信号...")
  85. except Exception as e:
  86. print(f"\n❌ 发生错误: {e}")
  87. finally:
  88. # 8. 清理资源
  89. print("\n7. 清理资源:")
  90. await detector.stop()
  91. await audio_capture.stop()
  92. print("✅ 资源已清理完毕")
  93. async def main_without_aec():
  94. """不使用AEC的示例"""
  95. print("=" * 60)
  96. print("语音唤醒模块示例(不使用AEC)")
  97. print("=" * 60)
  98. # 1. 列出可用音频设备
  99. print("\n1. 列出可用音频设备:")
  100. AudioCapture.list_devices()
  101. # 2. 创建配置
  102. print("\n2. 创建语音唤醒配置:")
  103. model_path = Path("models")
  104. if not model_path.exists():
  105. print(f"错误: 模型目录不存在: {model_path}")
  106. return
  107. config = WakeWordConfig(
  108. model_path=str(model_path),
  109. sample_rate=16000,
  110. )
  111. # 3. 创建音频采集器(不启用AEC)
  112. print("\n3. 创建音频采集器:")
  113. print(" 是否启用AEC回音消除: 否")
  114. audio_capture = AudioCapture(
  115. sample_rate=16000,
  116. channels=1,
  117. device_id=None,
  118. enable_aec=False, # 不启用AEC
  119. )
  120. # 4. 创建唤醒词检测器
  121. detector = WakeWordDetector(config)
  122. # 5. 设置回调
  123. def on_wake_word_detected(result, full_text):
  124. print(f"\n🎉 检测到唤醒词: {result},唤醒成功!✅")
  125. print(f" 完整文本: {full_text}")
  126. detector.on_detected(on_wake_word_detected)
  127. # 6. 连接并启动
  128. audio_capture.add_audio_listener(detector)
  129. await audio_capture.start()
  130. await detector.start()
  131. print("\n✅ 语音唤醒系统已启动! (不使用AEC)")
  132. print(" 请说出唤醒词进行测试...")
  133. print(" 按 Ctrl+C 停止程序\n")
  134. try:
  135. while True:
  136. await asyncio.sleep(1)
  137. except KeyboardInterrupt:
  138. print("\n\n收到停止信号...")
  139. finally:
  140. await detector.stop()
  141. await audio_capture.stop()
  142. print("✅ 资源已清理完毕")
  143. if __name__ == "__main__":
  144. import argparse
  145. parser = argparse.ArgumentParser(description="语音唤醒模块示例")
  146. parser.add_argument(
  147. "--no-aec",
  148. action="store_true",
  149. help="不使用AEC回音消除"
  150. )
  151. args = parser.parse_args()
  152. try:
  153. if args.no_aec:
  154. asyncio.run(main_without_aec())
  155. else:
  156. asyncio.run(main())
  157. except KeyboardInterrupt:
  158. print("\n程序已退出")
  159. sys.exit(0)