feat: add microphone selection utils

Providing two functions, one to choose the default microphone, the other to choose a microphone interactively. With tests.

ref: N25B-119
This commit is contained in:
Twirre Meulenbelt
2025-10-22 11:44:51 +02:00
parent 4da83a0a7e
commit 0f60f67ab9
2 changed files with 161 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
import logging
logger = logging.getLogger(__name__)
def choose_mic_interactive(audio):
"""
Choose a microphone to use, interactively in the CLI.
:param audio: An instance of PyAudio to use.
:type audio: pyaudio.PyAudio
:return: A dictionary from PyAudio containing information about the microphone to use, or None
if there is no microphone.
:rtype: dict | None
"""
device_count = audio.get_device_count()
if device_count == 0: return None
print("Found {} audio devices:".format(device_count))
for i in range(device_count):
print("- {}: {}".format(i, audio.get_device_info_by_index(i)["name"]))
microphone_index = None
while microphone_index is None:
chosen = raw_input("Which device would you like to use?\n> ")
try:
chosen = int(chosen)
if chosen < 0 or chosen >= device_count: raise ValueError()
microphone_index = chosen
except ValueError:
print("Please enter a number between 0 and {}".format(device_count-1))
chosen_microphone = audio.get_device_info_by_index(microphone_index)
logger.info("Chose microphone \"{}\"".format(chosen_microphone["name"]))
return chosen_microphone
def choose_mic_default(audio):
"""
Get the system's default microphone to use.
:param audio: An instance of PyAudio to use.
:type audio: pyaudio.PyAudio
:return: A dictionary from PyAudio containing information about the microphone to use, or None
if there is no microphone.
:rtype: dict | None
"""
device_count = audio.get_device_count()
if device_count == 0: return None
default_device = audio.get_default_input_device_info()
return default_device