aec_processor.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. """
  2. AEC回音消除处理器
  3. 支持Windows和Linux平台的系统级回音消除功能
  4. """
  5. import platform
  6. from typing import Optional
  7. import numpy as np
  8. class AECProcessor:
  9. """音频回声消除处理器(Windows/Linux系统级AEC)"""
  10. def __init__(self, sample_rate: int = 16000, channels: int = 1):
  11. """
  12. 初始化AEC处理器
  13. Args:
  14. sample_rate: 采样率
  15. channels: 声道数
  16. """
  17. # 平台信息
  18. self._platform = platform.system().lower()
  19. self._is_windows = self._platform == "windows"
  20. self._is_linux = self._platform == "linux"
  21. # 音频参数
  22. self.sample_rate = sample_rate
  23. self.channels = channels
  24. # 状态标志
  25. self._is_initialized = False
  26. self._is_closing = False
  27. async def initialize(self):
  28. """初始化AEC处理器"""
  29. try:
  30. if self._is_windows or self._is_linux:
  31. # Windows 和 Linux 平台使用系统级AEC,无需额外处理
  32. print(f"{self._platform.capitalize()} 平台使用系统级回声消除")
  33. self._is_initialized = True
  34. return print("AEC处理器初始化完成")
  35. else:
  36. print(f"当前平台 {self._platform} 暂不支持AEC功能")
  37. print("提示: 本模块仅支持Windows和Linux平台")
  38. self._is_initialized = True
  39. return print("AEC处理器初始化失败")
  40. except Exception as e:
  41. print(f"AEC处理器初始化失败: {e}")
  42. await self.close()
  43. raise
  44. def process_audio(self, capture_audio: np.ndarray) -> np.ndarray:
  45. """处理音频帧,应用AEC
  46. Args:
  47. capture_audio: 麦克风采集的音频数据 (16kHz, int16)
  48. Returns:
  49. 处理后的音频数据
  50. """
  51. if not self._is_initialized:
  52. return capture_audio
  53. # Windows 和 Linux 平台直接返回原始音频(系统级处理)
  54. if self._is_windows or self._is_linux:
  55. # 系统级AEC已自动处理,无需额外处理
  56. return capture_audio
  57. # 其他平台直接返回原始音频
  58. return capture_audio
  59. async def close(self):
  60. """关闭AEC处理器"""
  61. if self._is_closing:
  62. return
  63. self._is_closing = True
  64. print("开始关闭AEC处理器...")
  65. try:
  66. # Windows/Linux平台无需清理额外资源
  67. print("AEC处理器已关闭(系统级AEC无需额外清理)")
  68. self._is_initialized = False
  69. except Exception as e:
  70. print(f"关闭AEC处理器时发生错误: {e}")
  71. @property
  72. def is_initialized(self) -> bool:
  73. """返回是否已初始化"""
  74. return self._is_initialized
  75. @property
  76. def platform(self) -> str:
  77. """返回当前平台"""
  78. return self._platform