"""WASAPI 장치 루프백 캡처 (Windows). 출력 장치 전체의 소리를 받는다. 프로그램별 분리는 안 되지만 의존성이 `PyAudioWPatch` 하나뿐이라 어디서나 바로 동작하는 기본 백엔드다. """ from __future__ import annotations import contextlib import logging import numpy as np from ..constants import FRAME_SAMPLES from .base import AudioSource, CaptureBackend, CaptureError, to_mono_16k log = logging.getLogger(__name__) try: # pragma: no cover - 플랫폼 의존 import pyaudiowpatch as pyaudio except ImportError: # pragma: no cover pyaudio = None # type: ignore[assignment] class WasapiLoopbackCapture(CaptureBackend): name = "device" per_process = False def __init__(self, device_index: int = -1) -> None: super().__init__() self.device_index = device_index @staticmethod def available() -> bool: return pyaudio is not None @staticmethod def list_sources() -> list[AudioSource]: if pyaudio is None: return [] sources: list[AudioSource] = [] pa = pyaudio.PyAudio() try: default_index = -1 with contextlib.suppress(OSError, LookupError): default_index = pa.get_default_wasapi_loopback()["index"] for info in pa.get_loopback_device_info_generator(): idx = int(info["index"]) sources.append( AudioSource( kind="device", identifier=str(idx), label=str(info["name"]).replace(" [Loopback]", ""), detail="기본 출력 장치" if idx == default_index else "출력 장치", ) ) finally: pa.terminate() return sources def _resolve_device(self, pa) -> dict: if self.device_index >= 0: return pa.get_device_info_by_index(self.device_index) return pa.get_default_wasapi_loopback() def _run(self) -> None: # pragma: no cover - 실제 오디오 장치 필요 if pyaudio is None: raise CaptureError("PyAudioWPatch가 설치되지 않았습니다.") pa = pyaudio.PyAudio() stream = None try: info = self._resolve_device(pa) if info is None: raise CaptureError("루프백 장치를 찾지 못했습니다.") rate = int(info["defaultSampleRate"]) channels = int(info["maxInputChannels"]) or 2 chunk = max(FRAME_SAMPLES, int(rate * 0.02)) stream = pa.open( format=pyaudio.paFloat32, channels=channels, rate=rate, input=True, input_device_index=int(info["index"]), frames_per_buffer=chunk, ) log.info("장치 루프백 캡처 시작: %s (%dHz, %dch)", info["name"], rate, channels) while not self._stop.is_set(): raw = stream.read(chunk, exception_on_overflow=False) data = np.frombuffer(raw, dtype=np.float32) self._emit(to_mono_16k(data, channels, rate)) finally: if stream is not None: stream.stop_stream() stream.close() pa.terminate()