Fail fast when configured recording input cannot be resolved

This commit is contained in:
Thales Maciel 2026-02-26 16:39:36 -03:00
parent 386ba4af92
commit aa77dbc395
2 changed files with 107 additions and 2 deletions

View file

@ -36,12 +36,17 @@ def resolve_input_device(spec: str | int | None) -> int | None:
if spec is None:
return None
if isinstance(spec, int):
return spec
if _input_device_exists(spec):
return spec
return None
text = str(spec).strip()
if not text:
return None
if text.isdigit():
return int(text)
device_idx = int(text)
if _input_device_exists(device_idx):
return device_idx
return None
lowered = text.lower()
for device in list_input_devices():
name = (device.get("name") or "").lower()
@ -54,6 +59,11 @@ def start_recording(input_spec: str | int | None) -> tuple[Any, RecordResult]:
sd = _sounddevice()
record = RecordResult()
device = resolve_input_device(input_spec)
if _is_explicit_input_spec(input_spec) and device is None:
raise ValueError(
f"recording.input '{input_spec}' did not match any input device; "
f"available inputs: {_available_input_devices_summary()}"
)
def callback(indata, _frames, _time, _status):
record.frames.append(indata.copy())
@ -105,3 +115,28 @@ def _flatten_frames(frames: Iterable[np.ndarray]) -> np.ndarray:
if data.ndim > 1:
data = np.squeeze(data, axis=-1)
return np.asarray(data, dtype=np.float32).reshape(-1)
def _input_device_exists(device_idx: int) -> bool:
for device in list_input_devices():
if int(device.get("index", -1)) == int(device_idx):
return True
return False
def _is_explicit_input_spec(input_spec: str | int | None) -> bool:
if input_spec is None:
return False
if isinstance(input_spec, int):
return True
return bool(str(input_spec).strip())
def _available_input_devices_summary(limit: int = 8) -> str:
devices = list_input_devices()
if not devices:
return "<none>"
items = [f"{d['index']}:{d['name']}" for d in devices[:limit]]
if len(devices) > limit:
items.append("...")
return ", ".join(items)