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

browserMicrophones.ts

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