Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

browserMicrophones.ts

49 lines1.8 KB

1import {
2 getClientSettings,
3 isClientSettingsHydrated,
4 updateClientSettings,
5} from "../hooks/useSettings";
6import {
7 type MicrophoneEntry,
8 microphoneOrder,
9 preferredMicrophoneId,
10 rememberMicrophones,
11} from "./microphoneOrder";
12​
13export type BrowserMicrophone = Pick<MediaDeviceInfo, "deviceId" | "label">;
14​
15/** Audio inputs as the browser reports them. Labels stay empty until microphone permission. */
16export async function listAudioInputs(): Promise<BrowserMicrophone[]> {
17 const devices = await navigator.mediaDevices.enumerateDevices();
18 return devices
19 .filter((device) => device.kind === "audioinput")
20 .map(({ deviceId, label }) => ({ deviceId, label }));
22​
23export async function listBrowserMicrophones(): Promise<BrowserMicrophone[]> {
24 return (await listAudioInputs()).map(({ deviceId, label }, index) => ({
25 deviceId,
26 label: label || `Microphone ${index + 1}`,
27 }));
29​
30/** Applies a change to the saved order. Skipped before hydration so defaults never replace a saved order. */
31export function updateMicrophoneOrder(
32 change: (order: ReadonlyArray<MicrophoneEntry>) => ReadonlyArray<MicrophoneEntry>,
33): ReadonlyArray<MicrophoneEntry> {
34 const known = microphoneOrder(getClientSettings());
35 if (!isClientSettingsHydrated()) return known;
36 const next = change(known);
37 if (next !== known) void updateClientSettings({ voiceMicrophones: [...next] });
38 return next;
40​
41/** Remembers newly seen microphones and returns the device id to record from, empty for System default. */
42export async function chooseRecordingMicrophone(): Promise<string> {
43 // Rejects where the browser has no media devices, such as plain HTTP.
44 const devices = await listAudioInputs().catch(() => []);
45 return preferredMicrophoneId(
46 updateMicrophoneOrder((order) => rememberMicrophones(order, devices)),
47 devices,
48 );