"""
USBRecorder
Records an input with sounddevice and writes a 16-bit WAV. sounddevice's
wheels carry PortAudio, so this does not use PyAudio.
"""
import wave
from typing import List, Optional, Tuple
from decologr import Decologr as log
from jdxi_editor.audio import portaudio
#: Bytes per sample. The stream is int16; the widget's "32bit" label records
#: the same width.
[docs]
def _sounddevice():
"""The sounddevice module, or None when it did not import."""
try:
import sounddevice as module
except Exception:
return None
return module
[docs]
def _query_devices():
"""sounddevice's device list, or None when it cannot be queried."""
module = _sounddevice()
if module is None:
return None
try:
return module.query_devices()
except Exception:
return None
[docs]
def _query_hostapis() -> list:
"""
sounddevice's host APIs, or ``[]``.
Windows lists one device once per host API under an identical name, so
the API is what tells those entries apart. An empty list is tolerated:
the labelling falls back to the position.
:return: list
"""
module = _sounddevice()
if module is None:
return []
try:
return list(module.query_hostapis())
except Exception:
return []
[docs]
class _PcmStream:
"""A sounddevice input whose ``read`` returns PCM bytes."""
def __init__(self, stream) -> None:
# Registered while recording: refreshing PortAudio's device list
# terminates every stream in the process, and losing a take to that
# would be worse than a SoundFont that waits for the next attempt.
[docs]
self._hold = portaudio.hold("USB recording")
[docs]
def read(self, frames: int) -> bytes:
data, _overflowed = self._stream.read(frames)
return bytes(data)
[docs]
def stop_stream(self) -> None:
self._stream.stop()
[docs]
def close(self) -> None:
portaudio.release(self._hold)
self._hold = None
self._stream.close()
[docs]
class USBRecorder:
"""
A convenient class for recording audio from a USB input device.
"""
def __init__(
self,
input_device_index: int = None,
channels: int = 2,
rate: int = 44100,
frames_per_buffer: int = 1024,
):
"""
Initializes the recorder with the specified settings.
Stereo is the default: many USB amps (e.g. Yamaha THRII) open as mono
on Windows but then return silence; the Audio Monitor already prefers
two channels for the same reason.
"""
[docs]
self.channels = channels
[docs]
self.frames_per_buffer = frames_per_buffer
[docs]
self.file_save_recording: bool = False # Default to false
[docs]
self.sample_width = SAMPLE_WIDTH
[docs]
self.usb_recording_rates = {"16bit": "int16", "32bit": "int16"}
[docs]
def list_devices(self):
"""
Logs every PortAudio entry, and returns the lines.
This one is for diagnosing a report, not for choosing from, so it
keeps the position and names the host API: the same device appears
once per API on Windows, and which one was picked matters.
"""
log.message("[USBRecorder] Available audio input devices:")
devices = _query_devices()
if devices is None:
return []
apis = _query_hostapis()
device_list = []
for index, info in enumerate(devices):
api = portaudio.host_api_name(info, apis)
where = f" [{api}]" if api else ""
device_info = (
f"{index}: {info['name']}{where} "
f"(input channels: {info['max_input_channels']})"
)
log.info(device_info)
device_list.append(device_info)
return device_list
[docs]
def record(self, duration, output_file, rate="16bit"):
"""
Records audio for the specified duration and saves to a .wav file.
"""
del rate # the stream is int16 whichever label the caller passes
log.message("[USBRecorder] Recording...")
try:
stream = self.open_input()
except Exception as e:
log.error(f"[USBRecorder] Unable to open stream: {e}")
return
frames = []
try:
for _ in range(0, int(self.rate / self.frames_per_buffer * duration)):
frames.append(stream.read(self.frames_per_buffer))
except Exception as ex:
log.error(f"[USBRecorder] Error while recording: {ex}")
stream.stop_stream()
stream.close()
log.message("[USBRecorder] Recording finished")
if not frames:
log.warning("[USBRecorder] No audio captured.")
return
with wave.open(output_file, "wb") as f:
f.setnchannels(self.channels)
f.setsampwidth(self.sample_width)
f.setframerate(self.rate)
f.writeframes(b"".join(frames))
print(f"[USBRecorder] File successfully saved to {output_file}")
[docs]
def close(self):
"""Nothing to shut down; sounddevice keeps no session object."""
return None
[docs]
def stop_recording(self):
"""
stop_recording
:return: None
"""
try:
if hasattr(self, "usb_recording_thread"):
self.usb_recording_thread.stop_recording()
except Exception as ex:
log.error(f"[USBRecorder] Error {ex} occurred stopping USB recording")
# 🔹 Example usage 🔹
if __name__ == "__main__":
recorder = USBRecorder()
recorder.list_devices()
recorder.input_device_index = 7 # Change to your preferred device index
recorder.record(duration=270, output_file="new_order_ceremony.wav")
recorder.close()