1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
"use client";
export const DEFAULT_AUDIO_INPUT_DEVICE_ID = "default";
export interface VoiceOverInputDevice {
deviceId: string;
label: string;
isDefault: boolean;
}
export function buildVoiceOverAudioConstraints({
deviceId,
}: {
deviceId?: string | null;
}): MediaStreamConstraints {
const audio: MediaTrackConstraints = {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
};
if (deviceId && deviceId !== DEFAULT_AUDIO_INPUT_DEVICE_ID) {
audio.deviceId = { exact: deviceId };
}
return { audio };
}
export function normalizeSelectedDeviceId({
deviceId,
devices,
}: {
deviceId: string | null;
devices: VoiceOverInputDevice[];
}): string | null {
if (!deviceId) {
return null;
}
if (deviceId === DEFAULT_AUDIO_INPUT_DEVICE_ID) {
return deviceId;
}
return devices.some((device) => device.deviceId === deviceId)
? deviceId
: null;
}
export async function listVoiceOverInputDevices({
requestPermission = false,
}: {
requestPermission?: boolean;
} = {}): Promise<VoiceOverInputDevice[]> {
const mediaDevices = navigator.mediaDevices;
if (!mediaDevices?.enumerateDevices) {
throw new Error("Microphone selection is not supported in this browser");
}
let permissionStream: MediaStream | null = null;
if (requestPermission) {
permissionStream = await mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
},
});
}
try {
const devices = await mediaDevices.enumerateDevices();
let inputIndex = 1;
return devices
.filter((device) => device.kind === "audioinput")
.map((device) => {
const isDefault = device.deviceId === DEFAULT_AUDIO_INPUT_DEVICE_ID;
const fallbackLabel = isDefault
? "System default microphone"
: `Microphone ${inputIndex++}`;
return {
deviceId: device.deviceId,
label: device.label || fallbackLabel,
isDefault,
};
});
} finally {
if (permissionStream) {
for (const track of permissionStream.getTracks()) {
track.stop();
}
}
}
}
|