"""마이크 등 입력 장치 캡처 (Windows). 루프백(=스피커로 나가는 소리)이 아니라 **들어오는 소리**를 받는다. 통화나 합주처럼 상대 목소리가 내 스피커로 나오지 않는 상황, 또는 내가 말하는 것을 그대로 번역해 보고 싶을 때 쓴다. WasapiLoopbackCapture 와 스트림을 여는 모양이 비슷하지만 합치지 않았다. 장치 목록을 만드는 방법(루프백 전용 열거 vs 일반 입력 장치)과 기본 장치를 고르는 방법이 서로 달라서, 한 클래스에 넣으면 분기가 코드의 절반이 된다. """ 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 InputDeviceCapture(CaptureBackend): name = "input" 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 = int(pa.get_default_input_device_info()["index"]) for i in range(pa.get_device_count()): info = pa.get_device_info_by_index(i) if int(info.get("maxInputChannels", 0)) <= 0: continue # 루프백 장치는 '출력 장치' 목록에서 이미 보여주고 있다. # 여기서 또 내보내면 같은 것이 두 목록에 걸쳐 나온다. if info.get("isLoopbackDevice"): continue sources.append( AudioSource( kind="input", identifier=str(i), label=str(info["name"]), detail="기본 입력 장치" if i == 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_input_device_info() 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 = max(1, int(info["maxInputChannels"])) 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()