A mic-selector component from ElevenLabs UI.
From ElevenLabs UIMITSource
1"use client"
2
3import { useCallback, useEffect, useState } from "react"
4import { Check, ChevronsUpDown, Mic, MicOff } from "lucide-react"
5
6import { cn } from "@/lib/utils"
7import { Button } from "@/components/ui/button"
8import {
9 DropdownMenu,
10 DropdownMenuContent,
11 DropdownMenuItem,
12 DropdownMenuSeparator,
13 DropdownMenuTrigger,
14} from "@/components/ui/dropdown-menu"
15import { LiveWaveform } from "@/components/ui/live-waveform"
16
17export interface AudioDevice {
18 deviceId: string
19 label: string
20 groupId: string
21}
22
23export interface MicSelectorProps {
24 value?: string
25 onValueChange?: (deviceId: string) => void
26 muted?: boolean
27 onMutedChange?: (muted: boolean) => void
28 disabled?: boolean
29 className?: string
30}
31
32export function MicSelector({
33 value,
34 onValueChange,
35 muted,
36 onMutedChange,
37 disabled,
38 className,
39}: MicSelectorProps) {
40 const { devices, loading, error, hasPermission, loadDevices } =
41 useAudioDevices()
42 const [selectedDevice, setSelectedDevice] = useState<string>(value || "")
43 const [internalMuted, setInternalMuted] = useState(false)
44 const [isDropdownOpen, setIsDropdownOpen] = useState(false)
45
46 // Use controlled muted if provided, otherwise use internal state
47 const isMuted = muted !== undefined ? muted : internalMuted
48
49 // Update internal state when controlled value changes
50 useEffect(() => {
51 if (value !== undefined) {
52 setSelectedDevice(value)
53 }
54 }, [value])
55
56 // Select first device by default
57 const defaultDeviceId = devices[0]?.deviceId || ""
58 useEffect(() => {
59 if (!selectedDevice && defaultDeviceId) {
60 const newDevice = defaultDeviceId
61 setSelectedDevice(newDevice)
62 onValueChange?.(newDevice)
63 }
64 }, [defaultDeviceId, selectedDevice, onValueChange])
65
66 const currentDevice = devices.find((d) => d.deviceId === selectedDevice) ||
67 devices[0] || {
68 label: loading ? "Loading..." : "No microphone",
69 deviceId: "",
70 }
71
72 const handleDeviceSelect = (deviceId: string, e?: React.MouseEvent) => {
73 e?.preventDefault()
74 setSelectedDevice(deviceId)
75 onValueChange?.(deviceId)
76 }
77
78 const handleDropdownOpenChange = async (open: boolean) => {
79 setIsDropdownOpen(open)
80 if (open && !hasPermission && !loading) {
81 await loadDevices()
82 }
83 }
84
85 const toggleMute = () => {
86 const newMuted = !isMuted
87 if (muted === undefined) {
88 setInternalMuted(newMuted)
89 }
90 onMutedChange?.(newMuted)
91 }
92
93 const isPreviewActive = isDropdownOpen && !isMuted
94
95 return (
96 <DropdownMenu onOpenChange={handleDropdownOpenChange}>
97 <DropdownMenuTrigger asChild>
98 <Button
99 variant="ghost"
100 size="sm"
101 className={cn(
102 "hover:bg-accent flex w-48 cursor-pointer items-center gap-1.5",
103 className
104 )}
105 disabled={loading || disabled}
106 >
107 {isMuted ? (
108 <MicOff className="h-4 w-4 flex-shrink-0" />
109 ) : (
110 <Mic className="h-4 w-4 flex-shrink-0" />
111 )}
112 <span className="flex-1 truncate text-left">
113 {currentDevice.label}
114 </span>
115 <ChevronsUpDown className="h-3 w-3 flex-shrink-0" />
116 </Button>
117 </DropdownMenuTrigger>
118 <DropdownMenuContent align="center" side="top" className="w-72">
119 {loading ? (
120 <DropdownMenuItem disabled>Loading devices...</DropdownMenuItem>
121 ) : error ? (
122 <DropdownMenuItem disabled>Error: {error}</DropdownMenuItem>
123 ) : (
124 devices.map((device) => (
125 <DropdownMenuItem
126 key={device.deviceId}
127 onClick={(e) => handleDeviceSelect(device.deviceId, e)}
128 onSelect={(e) => e.preventDefault()}
129 className="flex items-center justify-between"
130 >
131 <span className="truncate">{device.label}</span>
132 {selectedDevice === device.deviceId && (
133 <Check className="h-4 w-4 flex-shrink-0" />
134 )}
135 </DropdownMenuItem>
136 ))
137 )}
138 {devices.length > 0 && (
139 <>
140 <DropdownMenuSeparator />
141 <div className="flex items-center gap-2 p-2">
142 <Button
143 variant="ghost"
144 size="sm"
145 onClick={(e) => {
146 e.preventDefault()
147 toggleMute()
148 }}
149 className="h-8 gap-2"
150 >
151 {isMuted ? (
152 <MicOff className="h-4 w-4" />
153 ) : (
154 <Mic className="h-4 w-4" />
155 )}
156 <span className="text-sm">{isMuted ? "Unmute" : "Mute"}</span>
157 </Button>
158 <div className="bg-accent ml-auto w-16 overflow-hidden rounded-md p-1.5">
159 <LiveWaveform
160 active={isPreviewActive}
161 deviceId={selectedDevice || defaultDeviceId}
162 mode="static"
163 height={15}
164 barWidth={3}
165 barGap={1}
166 />
167 </div>
168 </div>
169 </>
170 )}
171 </DropdownMenuContent>
172 </DropdownMenu>
173 )
174}
175
176export function useAudioDevices() {
177 const [devices, setDevices] = useState<AudioDevice[]>([])
178 const [loading, setLoading] = useState(true)
179 const [error, setError] = useState<string | null>(null)
180 const [hasPermission, setHasPermission] = useState(false)
181
182 const loadDevicesWithoutPermission = useCallback(async () => {
183 try {
184 setLoading(true)
185 setError(null)
186
187 const deviceList = await navigator.mediaDevices.enumerateDevices()
188
189 const audioInputs = deviceList
190 .filter((device) => device.kind === "audioinput")
191 .map((device) => {
192 let cleanLabel =
193 device.label || `Microphone ${device.deviceId.slice(0, 8)}`
194 cleanLabel = cleanLabel.replace(/\s*\([^)]*\)/g, "").trim()
195
196 return {
197 deviceId: device.deviceId,
198 label: cleanLabel,
199 groupId: device.groupId,
200 }
201 })
202
203 setDevices(audioInputs)
204 } catch (err) {
205 setError(
206 err instanceof Error ? err.message : "Failed to get audio devices"
207 )
208 console.error("Error getting audio devices:", err)
209 } finally {
210 setLoading(false)
211 }
212 }, [])
213
214 const loadDevicesWithPermission = useCallback(async () => {
215 if (loading) return
216
217 try {
218 setLoading(true)
219 setError(null)
220
221 const tempStream = await navigator.mediaDevices.getUserMedia({
222 audio: true,
223 })
224 tempStream.getTracks().forEach((track) => track.stop())
225
226 const deviceList = await navigator.mediaDevices.enumerateDevices()
227
228 const audioInputs = deviceList
229 .filter((device) => device.kind === "audioinput")
230 .map((device) => {
231 let cleanLabel =
232 device.label || `Microphone ${device.deviceId.slice(0, 8)}`
233 cleanLabel = cleanLabel.replace(/\s*\([^)]*\)/g, "").trim()
234
235 return {
236 deviceId: device.deviceId,
237 label: cleanLabel,
238 groupId: device.groupId,
239 }
240 })
241
242 setDevices(audioInputs)
243 setHasPermission(true)
244 } catch (err) {
245 setError(
246 err instanceof Error ? err.message : "Failed to get audio devices"
247 )
248 console.error("Error getting audio devices:", err)
249 } finally {
250 setLoading(false)
251 }
252 }, [loading])
253
254 useEffect(() => {
255 loadDevicesWithoutPermission()
256 }, [loadDevicesWithoutPermission])
257
258 useEffect(() => {
259 const handleDeviceChange = () => {
260 if (hasPermission) {
261 loadDevicesWithPermission()
262 } else {
263 loadDevicesWithoutPermission()
264 }
265 }
266
267 navigator.mediaDevices.addEventListener("devicechange", handleDeviceChange)
268
269 return () => {
270 navigator.mediaDevices.removeEventListener(
271 "devicechange",
272 handleDeviceChange
273 )
274 }
275 }, [hasPermission, loadDevicesWithPermission, loadDevicesWithoutPermission])
276
277 return {
278 devices,
279 loading,
280 error,
281 hasPermission,
282 loadDevices: loadDevicesWithPermission,
283 }
284}
285