|
| 1 | +/** |
| 2 | + * 课堂音频自动恢复 hook(静音诊断 / 窗口源回退 / 设备变更重启) |
| 3 | + * |
| 4 | + * @ai-context: 从 useClassroomAudio 拆出的独立恢复层。三条恢复路径: |
| 5 | + * ①窗口源静音回退——Windows 上窗口源(window:xxx)getUserMedia 可能"成功但 |
| 6 | + * 给出纯静音轨"(不抛错,异常降级不会触发),SilenceTracker 检出连续静音后 |
| 7 | + * 自动 stop→start 以环回源重启(每会话仅回退一次); |
| 8 | + * ②输出设备不匹配提示——已在环回源仍持续静音,说明视频声音输出到了 |
| 9 | + * 非默认设备,提示用户核对默认输出设备; |
| 10 | + * ③设备变更重启——默认输出设备切换后环回仍绑定旧设备,devicechange 时 |
| 11 | + * 自动重启重新绑定。 |
| 12 | + * @ai-context: 仅依赖 refs 的稳定回调,重启经 restartingRef 互斥防止并发。 |
| 13 | + */ |
| 14 | +import { useEffect, useRef, useCallback } from 'react'; |
| 15 | +import type { CaptureMode, SessionStatus } from '@/lib/capture'; |
| 16 | +import { |
| 17 | + computeChunkRms, SilenceTracker, |
| 18 | + getDefaultOutputDeviceLabel, subscribeDeviceChange, |
| 19 | +} from '@/lib/audio/outputDeviceMonitor'; |
| 20 | + |
| 21 | +/** 与 useSessionControl 启动参数保持一致的音频采集配置 */ |
| 22 | +const AUDIO_START_OPTIONS = { chunkDurationMs: 5000, sampleRate: 16000, channels: 1 }; |
| 23 | +/** 重启前等待渲染端管道清理完成的时间 */ |
| 24 | +const RESTART_CLEANUP_DELAY_MS = 500; |
| 25 | + |
| 26 | +interface UseAudioRecoveryOptions { |
| 27 | + status: SessionStatus; |
| 28 | + mode: CaptureMode; |
| 29 | + /** 方案A:会话选中窗口的源 ID(回退环回后置空) */ |
| 30 | + audioSourceId?: string | null; |
| 31 | + onNotify: (type: 'warning' | 'error', message: string) => void; |
| 32 | +} |
| 33 | + |
| 34 | +export function useAudioRecovery({ status, mode, audioSourceId, onNotify }: UseAudioRecoveryOptions) { |
| 35 | + const notifyRef = useRef(onNotify); |
| 36 | + notifyRef.current = onNotify; |
| 37 | + /** 当前生效的音频源(窗口源回退环回后变为 undefined) */ |
| 38 | + const effectiveSourceRef = useRef<string | undefined>(audioSourceId ?? undefined); |
| 39 | + const silenceTrackerRef = useRef(new SilenceTracker()); |
| 40 | + /** 本会话是否已执行过窗口源→环回回退 */ |
| 41 | + const fellBackRef = useRef(false); |
| 42 | + const restartingRef = useRef(false); |
| 43 | + |
| 44 | + const audioEnabled = status === 'capturing' && (mode === 'audio' || mode === 'mixed'); |
| 45 | + |
| 46 | + // 会话开始时重置恢复状态(audioSourceId 取会话启动瞬间的快照) |
| 47 | + useEffect(() => { |
| 48 | + if (status !== 'capturing') return; |
| 49 | + effectiveSourceRef.current = audioSourceId ?? undefined; |
| 50 | + fellBackRef.current = false; |
| 51 | + silenceTrackerRef.current.reset(); |
| 52 | + // eslint-disable-next-line react-hooks/exhaustive-deps -- 仅会话开始时快照 audioSourceId |
| 53 | + }, [status]); |
| 54 | + |
| 55 | + /** stop→start 重启音频捕获(互斥),成功返回 true */ |
| 56 | + const restartCapture = useCallback(async (sourceId?: string): Promise<boolean> => { |
| 57 | + if (!window.electronAPI || restartingRef.current) return false; |
| 58 | + restartingRef.current = true; |
| 59 | + try { |
| 60 | + await window.electronAPI.invoke('audio_capture_stop'); |
| 61 | + await new Promise((r) => setTimeout(r, RESTART_CLEANUP_DELAY_MS)); |
| 62 | + const result = await window.electronAPI.invoke('audio_capture_start', { |
| 63 | + ...AUDIO_START_OPTIONS, sourceId, |
| 64 | + }) as { success: boolean; error?: string }; |
| 65 | + if (result.success) silenceTrackerRef.current.reset(); |
| 66 | + else console.warn('[useAudioRecovery] 音频捕获重启失败:', result.error); |
| 67 | + return result.success; |
| 68 | + } catch (err) { |
| 69 | + console.error('[useAudioRecovery] 音频捕获重启异常:', err); |
| 70 | + return false; |
| 71 | + } finally { |
| 72 | + restartingRef.current = false; |
| 73 | + } |
| 74 | + }, []); |
| 75 | + |
| 76 | + // 静音诊断:窗口源先自动回退环回;已是环回仍静音则提示核对输出设备 |
| 77 | + useEffect(() => { |
| 78 | + if (!audioEnabled || !window.electronAPI) return; |
| 79 | + const off = window.electronAPI.on('audio_capture_chunk', (...args: unknown[]) => { |
| 80 | + const chunk = args[0] as { audioBuffer: ArrayBuffer }; |
| 81 | + if (!silenceTrackerRef.current.push(computeChunkRms(chunk.audioBuffer))) return; |
| 82 | + |
| 83 | + const src = effectiveSourceRef.current; |
| 84 | + if (src?.startsWith('window:') && !fellBackRef.current) { |
| 85 | + // 方案A 漏洞补偿:窗口源"成功但静音"不抛错,只能靠静音检测触发回退 |
| 86 | + fellBackRef.current = true; |
| 87 | + effectiveSourceRef.current = undefined; |
| 88 | + console.warn('[useAudioRecovery] 窗口音频源持续静音,自动回退系统环回'); |
| 89 | + void restartCapture(undefined).then((ok) => { |
| 90 | + if (ok) notifyRef.current('warning', '窗口音频源持续静音,已自动切换为系统环回捕获'); |
| 91 | + }); |
| 92 | + return; |
| 93 | + } |
| 94 | + void getDefaultOutputDeviceLabel().then((label) => { |
| 95 | + notifyRef.current('warning', |
| 96 | + `持续收到静音音频:请确认视频声音正在播放,且输出到系统默认设备${label ? `「${label}」` : ''}(音频捕获只能录到默认输出设备的声音)`); |
| 97 | + }); |
| 98 | + }); |
| 99 | + return off; |
| 100 | + }, [audioEnabled, restartCapture]); |
| 101 | + |
| 102 | + // 设备变更自动重启:重新绑定新的默认输出设备 |
| 103 | + useEffect(() => { |
| 104 | + if (!audioEnabled || !window.electronAPI) return; |
| 105 | + const unsubscribe = subscribeDeviceChange(() => { |
| 106 | + console.info('[useAudioRecovery] 检测到音频设备变更,自动重启音频捕获'); |
| 107 | + void restartCapture(effectiveSourceRef.current).then((ok) => { |
| 108 | + if (ok) notifyRef.current('warning', '检测到音频输出设备变更,已自动重新绑定音频捕获'); |
| 109 | + else notifyRef.current('error', '音频设备变更后重启捕获失败,请停止后重新开始采集'); |
| 110 | + }); |
| 111 | + }); |
| 112 | + return unsubscribe; |
| 113 | + }, [audioEnabled, restartCapture]); |
| 114 | +} |
0 commit comments