diff --git a/README.md b/README.md index fd051ae..85f8aa6 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,10 @@ WebSpeak 是一个自托管的 TeamSpeak 浏览器客户端与访客接入网关 - Session 生命周期统一管理:连接状态机、WebSocket 心跳、幂等清理和优雅关闭。 - TeamSpeak 临时断线自动重连,固定退避策略最长持续 5 分钟;认证失败不会无限重试,并尽量恢复原频道。 - 完整频道/成员树、频道切换、频道文字聊天和成员实时移动。 -- PCM/Opus 语音桥接、自由麦、按键说话、麦克风选择与音量控制。 +- PCM/Opus 语音桥接、自由麦、按键说话、麦克风与扬声器设备选择、输入/输出音量控制。 +- 音频设置显示权限、实时麦克风音量和 VOX 阈值;VOX 带 attack/hold/release,设备热插拔时自动回退默认设备。 +- 移动端提供不会因触控取消而卡住的“按住说话”;麦克风测试最多录制 5 秒并只在本地播放,不发送到 TeamSpeak。 +- 支持连接、断开、Poke、私聊和重连失败提示音;浏览器不支持输出设备选择时明确降级到默认输出。 - 发言成员头像显示绿色动态边框。 - 频道、服务器和私聊独立标签;成员菜单支持私聊、Poke、复制昵称,频道密码按次输入且不持久化。 - Away、成员状态图标、Session 内服务器事件日志和人类可读的 TeamSpeak 权限错误。 @@ -187,7 +190,7 @@ npm run dev # 前端开发服务;/api 和 /ws 代理到 3040 npm run web:dev -# 自动测试(覆盖 M000–M005) +# 自动测试(覆盖 M000–M007 已实现的后端协议与安全边界) npm test # 后端类型检查与构建 @@ -228,7 +231,10 @@ WebSpeak is a self-hosted TeamSpeak web client and guest gateway. Every browser - Managed session lifecycle with a connection state machine, WebSocket heartbeat, idempotent teardown, and graceful shutdown. - Temporary TeamSpeak failures recover with bounded jittered backoff for up to five minutes; authentication failures are not retried forever, and the previous channel is restored when possible. - Channel/member directory, channel switching, channel text chat, and live member movement. -- PCM/Opus voice bridge, VOX, push-to-talk, microphone selection, and volume controls. +- PCM/Opus voice bridge, VOX, push-to-talk, input/output device selection, and clamped volume controls. +- Audio diagnostics expose permission, live mic level, VOX threshold, and audio context state; device hotplug falls back to the default input/output. +- Mobile push-to-talk handles pointer cancellation and focus loss; local microphone tests record at most five seconds and never send to TeamSpeak. +- Built-in sounds cover connection, disconnection, poke, private messages, and failed reconnects, with a clear default-output fallback when the browser lacks output selection. - Independent channel, server, and private chat tabs; member actions for private message, poke, and nickname copy; channel passwords are entered per session only. - Away, member status icons, a session-local server event log, and readable TeamSpeak permission errors. - Bilingual guest UI and bilingual admin console. diff --git a/web/src/composables/useVoiceWebSocket.ts b/web/src/composables/useVoiceWebSocket.ts index 7d83971..2a7ad69 100644 --- a/web/src/composables/useVoiceWebSocket.ts +++ b/web/src/composables/useVoiceWebSocket.ts @@ -30,6 +30,18 @@ export interface AudioInputDevice { groupId: string; } +export interface AudioOutputDevice { + deviceId: string; + label: string; + groupId: string; +} + +export type AudioPermission = "unknown" | "granted" | "denied"; + +type SinkAudioContext = AudioContext & { + setSinkId?: (sinkId: string) => Promise; +}; + export interface ChannelInfo { id: string; parentID: string; @@ -75,23 +87,34 @@ export function useVoiceWebSocket() { // Audio capture. The ScriptProcessor path remains the most compatible option // for the current browser support matrix, but the graph now has an explicit // input gain and a silent output to avoid monitoring the microphone locally. - let audioCtx: AudioContext | null = null; + let audioCtx: SinkAudioContext | null = null; let micStream: MediaStream | null = null; let scriptNode: ScriptProcessorNode | null = null; let micSource: MediaStreamAudioSourceNode | null = null; let micGain: GainNode | null = null; let silentGain: GainNode | null = null; const inputDevices = reactive([]); + const outputDevices = reactive([]); const selectedInputDeviceId = ref(typeof localStorage !== "undefined" ? localStorage.getItem("webspeak:input-device") ?? "" : ""); + const selectedOutputDeviceId = ref(typeof localStorage !== "undefined" ? localStorage.getItem("webspeak:output-device") ?? "" : ""); + const outputDeviceSupported = ref(false); + const audioPermission = ref("unknown"); + const audioContextState = ref("unknown"); const micLevel = ref(0); const microphoneTestActive = ref(false); + const testAudioUrl = ref(""); + let testRecorder: MediaRecorder | null = null; + let testRecorderTimer: ReturnType | null = null; let pttPressed = false; const micMode = ref<"vox" | "ptt">("vox"); const inputVolume = ref(1); const outputVolume = ref(1); - let voxHold = 0; + const notificationVolume = ref(0.5); + const voxThreshold = ref(0.008); + let voxAttack = 0; + let voxRelease = 0; const VOX_HOLD = 15; - const VOX_THRESHOLD = 0.008; + const VOX_ATTACK_FRAMES = 2; let convBuf = new Int16Array(1024); let accumBuf = new Int16Array(2048); let accumLen = 0; @@ -106,6 +129,8 @@ export function useVoiceWebSocket() { const speakingIds = reactive(new Set()); const speakingTimers = new Map>(); const SPEAKING_HOLD_MS = 360; + const MAX_AUDIO_BUFFERED_BYTES = 192_000; + let droppedAudioFrames = 0; async function saveAudioPreferences(): Promise { await saveLocalPreferences({ @@ -113,8 +138,11 @@ export function useVoiceWebSocket() { preferredInputDeviceId: selectedInputDeviceId.value, inputDeviceId: selectedInputDeviceId.value, voiceMode: micMode.value, + voxThreshold: voxThreshold.value, inputGain: inputVolume.value, outputVolume: outputVolume.value, + notificationVolume: notificationVolume.value, + preferredOutputDeviceId: selectedOutputDeviceId.value, volumesByUid: { ...storedVolumesByUid }, }); } @@ -130,8 +158,11 @@ export function useVoiceWebSocket() { void loadLocalPreferences().then((preferences) => { if (!selectedInputDeviceId.value) selectedInputDeviceId.value = preferences.preferredInputDeviceId ?? preferences.inputDeviceId ?? ""; if (preferences.voiceMode === "vox" || preferences.voiceMode === "ptt") micMode.value = preferences.voiceMode; + if (typeof preferences.voxThreshold === "number") voxThreshold.value = clamp(preferences.voxThreshold, 0.001, 0.08); if (typeof preferences.inputGain === "number") inputVolume.value = Math.max(0, Math.min(1, preferences.inputGain)); if (typeof preferences.outputVolume === "number") outputVolume.value = Math.max(0, Math.min(1, preferences.outputVolume)); + if (!selectedOutputDeviceId.value) selectedOutputDeviceId.value = preferences.preferredOutputDeviceId ?? ""; + if (typeof preferences.notificationVolume === "number") notificationVolume.value = clamp(preferences.notificationVolume, 0, 1); Object.assign(storedVolumesByUid, preferences.volumesByUid ?? {}); syncKnownMemberVolumes(); }); @@ -161,15 +192,40 @@ export function useVoiceWebSocket() { speakingIds.clear(); } - function getAudioCtx(): AudioContext { - if (!audioCtx) audioCtx = new AudioContext({ sampleRate: 48000 }); + function getAudioCtx(): SinkAudioContext { + if (!audioCtx) { + audioCtx = new AudioContext({ sampleRate: 48000 }) as SinkAudioContext; + audioContextState.value = audioCtx.state; + audioCtx.addEventListener("statechange", () => { + if (audioCtx) audioContextState.value = audioCtx.state; + }); + outputDeviceSupported.value = typeof audioCtx.setSinkId === "function"; + if (selectedOutputDeviceId.value && outputDeviceSupported.value) { + void setAudioSink(audioCtx, selectedOutputDeviceId.value).catch(() => undefined); + } + } return audioCtx; } + function clamp(value: number, minimum: number, maximum: number): number { + return Math.max(minimum, Math.min(maximum, value)); + } + + async function setAudioSink(ctx: SinkAudioContext, deviceId: string): Promise { + if (!ctx.setSinkId) { + outputDeviceSupported.value = false; + if (deviceId) throw new Error("当前浏览器不支持扬声器设备选择,将使用默认输出设备"); + return; + } + outputDeviceSupported.value = true; + await ctx.setSinkId(deviceId || "default"); + } + function checkSupport(): string | null { if (typeof window === "undefined") return null; if (!window.isSecureContext) return "语音功能需要 HTTPS 安全连接"; if (!navigator.mediaDevices?.getUserMedia) return "当前浏览器不支持麦克风访问"; + if (typeof AudioContext === "undefined") return "当前浏览器不支持 Web Audio 音频处理"; if (typeof AudioDecoder === "undefined") return "当前浏览器不支持音频解码,请使用最新版 Chrome 或 Edge"; return null; } @@ -186,21 +242,37 @@ export function useVoiceWebSocket() { return constraints; } - async function refreshInputDevices(): Promise { + async function refreshAudioDevices(): Promise { if (!navigator.mediaDevices?.enumerateDevices) { inputDevices.length = 0; + outputDevices.length = 0; return; } const devices = await navigator.mediaDevices.enumerateDevices(); const microphones = devices .filter((device) => device.kind === "audioinput") .map((device) => ({ deviceId: device.deviceId, label: device.label, groupId: device.groupId })); + const speakers = devices + .filter((device) => device.kind === "audiooutput") + .map((device) => ({ deviceId: device.deviceId, label: device.label, groupId: device.groupId })); inputDevices.splice(0, inputDevices.length, ...microphones); + outputDevices.splice(0, outputDevices.length, ...speakers); if (selectedInputDeviceId.value && !microphones.some((device) => device.deviceId === selectedInputDeviceId.value)) { - selectedInputDeviceId.value = microphones[0]?.deviceId ?? ""; + selectedInputDeviceId.value = ""; localStorage.setItem("webspeak:input-device", selectedInputDeviceId.value); void saveAudioPreferences(); + if (micStream) void startMicrophone().catch(() => undefined); } + if (selectedOutputDeviceId.value && !speakers.some((device) => device.deviceId === selectedOutputDeviceId.value)) { + selectedOutputDeviceId.value = ""; + localStorage.setItem("webspeak:output-device", ""); + void saveAudioPreferences(); + if (audioCtx && outputDeviceSupported.value) void setAudioSink(audioCtx, "").catch(() => undefined); + } + } + + async function refreshInputDevices(): Promise { + await refreshAudioDevices(); } async function startMicrophone(): Promise { @@ -208,7 +280,14 @@ export function useVoiceWebSocket() { if (ctx.state === "suspended") await ctx.resume(); // Acquire the replacement stream before tearing down the current graph so // changing devices does not interrupt an active microphone on failure. - const nextStream = await navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() }); + let nextStream: MediaStream; + try { + nextStream = await navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() }); + audioPermission.value = "granted"; + } catch (error) { + if (error instanceof DOMException && ["NotAllowedError", "SecurityError"].includes(error.name)) audioPermission.value = "denied"; + throw error; + } stopMicrophone(false); micStream = nextStream; @@ -224,12 +303,24 @@ export function useVoiceWebSocket() { let sum = 0; for (let i = 0; i < input.length; i++) sum += input[i] * input[i]; micLevel.value = Math.min(1, Math.sqrt(sum / Math.max(1, input.length)) * 6); - const shouldSend = micMode.value === "ptt" ? pttPressed : voxGate(input); + const socket = ws.value; + const shouldSend = !microphoneTestActive.value + && socket?.readyState === WebSocket.OPEN + && (micMode.value === "ptt" ? pttPressed : voxGate(input)); if (!shouldSend) { accumLen = 0; return; } - if (ws.value?.readyState === WebSocket.OPEN) markSpeaking(state.tsClientId); + if (!socket) { + accumLen = 0; + return; + } + if (socket.bufferedAmount > MAX_AUDIO_BUFFERED_BYTES) { + accumLen = 0; + droppedAudioFrames++; + return; + } + markSpeaking(state.tsClientId); if (convBuf.length < input.length) convBuf = new Int16Array(input.length); for (let i = 0; i < input.length; i++) { @@ -243,8 +334,8 @@ export function useVoiceWebSocket() { accumLen = need; let offset = 0; - while (offset + 960 <= accumLen && ws.value?.readyState === WebSocket.OPEN) { - ws.value.send(accumBuf.slice(offset, offset + 960).buffer); + while (offset + 960 <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= MAX_AUDIO_BUFFERED_BYTES) { + socket.send(accumBuf.slice(offset, offset + 960).buffer); offset += 960; } accumLen -= offset; @@ -255,7 +346,7 @@ export function useVoiceWebSocket() { micGain.connect(scriptNode); scriptNode.connect(silentGain); silentGain.connect(ctx.destination); - await refreshInputDevices(); + await refreshAudioDevices(); } async function ensureMicrophone(): Promise { @@ -273,12 +364,14 @@ export function useVoiceWebSocket() { const count = Math.min(256, samples.length); for (let i = 0; i < count; i++) sum += samples[i] * samples[i]; const rms = Math.sqrt(sum / count); - if (rms > VOX_THRESHOLD) { - voxHold = VOX_HOLD; - return true; + if (rms >= voxThreshold.value) { + voxAttack = Math.min(VOX_ATTACK_FRAMES, voxAttack + 1); + voxRelease = VOX_HOLD; + return voxAttack >= VOX_ATTACK_FRAMES; } - if (voxHold > 0) { - voxHold--; + voxAttack = 0; + if (voxRelease > 0) { + voxRelease--; return true; } return false; @@ -286,7 +379,8 @@ export function useVoiceWebSocket() { function stopMicrophone(closeContext = true): void { accumLen = 0; - voxHold = 0; + voxAttack = 0; + voxRelease = 0; micLevel.value = 0; scriptNode?.disconnect(); micGain?.disconnect(); @@ -306,7 +400,7 @@ export function useVoiceWebSocket() { async function prepareInputDevices(): Promise { if (!micStream) await startMicrophone(); - else await refreshInputDevices(); + else await refreshAudioDevices(); } async function setInputDevice(deviceId: string): Promise { @@ -316,7 +410,7 @@ export function useVoiceWebSocket() { void saveAudioPreferences(); try { if (micStream) await startMicrophone(); - await refreshInputDevices(); + await refreshAudioDevices(); } catch (error) { selectedInputDeviceId.value = previousDeviceId; localStorage.setItem("webspeak:input-device", previousDeviceId); @@ -325,15 +419,89 @@ export function useVoiceWebSocket() { } async function startMicrophoneTest(): Promise { - await prepareInputDevices(); microphoneTestActive.value = true; + if (testAudioUrl.value) { + URL.revokeObjectURL(testAudioUrl.value); + testAudioUrl.value = ""; + } + try { + await prepareInputDevices(); + if (typeof MediaRecorder !== "undefined" && micStream) { + const chunks: Blob[] = []; + const recorder = new MediaRecorder(micStream); + testRecorder = recorder; + recorder.ondataavailable = (event) => { + if (event.data.size) chunks.push(event.data); + }; + recorder.onstop = () => { + if (chunks.length) { + testAudioUrl.value = URL.createObjectURL(new Blob(chunks, { type: recorder.mimeType || "audio/webm" })); + } + if (testRecorder === recorder) testRecorder = null; + }; + recorder.start(); + testRecorderTimer = setTimeout(() => stopMicrophoneTest(), 5_000); + } + } catch (error) { + microphoneTestActive.value = false; + throw error; + } } function stopMicrophoneTest(): void { microphoneTestActive.value = false; + if (testRecorderTimer) clearTimeout(testRecorderTimer); + testRecorderTimer = null; + if (testRecorder && testRecorder.state !== "inactive") testRecorder.stop(); if (!state.connected) stopMicrophone(); } + async function setOutputDevice(deviceId: string): Promise { + const previousDeviceId = selectedOutputDeviceId.value; + if (deviceId && !outputDevices.some((device) => device.deviceId === deviceId)) { + throw new Error("所选扬声器当前不可用"); + } + selectedOutputDeviceId.value = deviceId; + localStorage.setItem("webspeak:output-device", deviceId); + try { + await setAudioSink(getAudioCtx(), deviceId); + await saveAudioPreferences(); + } catch (error) { + selectedOutputDeviceId.value = previousDeviceId; + localStorage.setItem("webspeak:output-device", previousDeviceId); + throw error; + } + } + + function playNotification(kind: "connected" | "disconnected" | "poke" | "private" | "reconnectFailed"): void { + if (notificationVolume.value <= 0 || typeof window === "undefined") return; + try { + const ctx = getAudioCtx(); + if (ctx.state === "suspended") return; + const frequencies: Record = { + connected: [660, 880], + disconnected: [440, 330], + poke: [740, 980], + private: [600, 760], + reconnectFailed: [300, 220], + }; + const oscillator = ctx.createOscillator(); + const gain = ctx.createGain(); + const now = ctx.currentTime; + oscillator.frequency.setValueAtTime(frequencies[kind][0], now); + oscillator.frequency.setValueAtTime(frequencies[kind][1], now + 0.08); + gain.gain.setValueAtTime(0.0001, now); + gain.gain.exponentialRampToValueAtTime(Math.max(0.0001, notificationVolume.value * 0.12), now + 0.01); + gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.18); + oscillator.connect(gain); + gain.connect(ctx.destination); + oscillator.start(now); + oscillator.stop(now + 0.2); + } catch { + // Notification sounds are best effort and must never affect the session. + } + } + function playAudioFrame(clientId: number, opusData: Uint8Array): void { if (opusData.length < 3) return; let decoder = remoteDecoders.get(clientId); @@ -736,6 +904,16 @@ export function useVoiceWebSocket() { void saveAudioPreferences(); } + function setVoxThreshold(threshold: number): void { + voxThreshold.value = clamp(threshold, 0.001, 0.08); + void saveAudioPreferences(); + } + + function setNotificationVolume(volume: number): void { + notificationVolume.value = clamp(volume, 0, 1); + void saveAudioPreferences(); + } + return { ws, state, @@ -747,20 +925,33 @@ export function useVoiceWebSocket() { micMode, inputVolume, outputVolume, + notificationVolume, + voxThreshold, inputDevices, + outputDevices, selectedInputDeviceId, + selectedOutputDeviceId, + outputDeviceSupported, + audioPermission, + audioContextState, identityMaterial, micLevel, microphoneTestActive, + testAudioUrl, speakingIds, volumes, setVolume, setInputVolume, setOutputVolume, + setVoxThreshold, + setNotificationVolume, prepareInputDevices, + refreshAudioDevices, setInputDevice, + setOutputDevice, startMicrophoneTest, stopMicrophoneTest, + playNotification, connect, reconnectNow, disconnect, diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue index 9e72832..5f21359 100644 --- a/web/src/views/WebClient.vue +++ b/web/src/views/WebClient.vue @@ -157,11 +157,12 @@ -
- - -
- +
+ + +
+ + @@ -205,8 +206,8 @@ @@ -236,20 +237,33 @@ const { micMode, inputVolume, outputVolume, + notificationVolume, + voxThreshold, inputDevices, + outputDevices, selectedInputDeviceId, + selectedOutputDeviceId, + outputDeviceSupported, + audioPermission, + audioContextState, identityMaterial, micLevel, microphoneTestActive, + testAudioUrl, speakingIds, volumes, setVolume, setInputVolume, setOutputVolume, + setVoxThreshold, + setNotificationVolume, prepareInputDevices, + refreshAudioDevices, setInputDevice, + setOutputDevice, startMicrophoneTest, stopMicrophoneTest, + playNotification, connect, reconnectNow, disconnect, @@ -427,6 +441,8 @@ const translations: Record> = { freeMic: "自由麦", pushToTalk: "按键说话", pushToTalkHint: "按住空格说话", + holdToTalk: "按住说话", + releaseToTalk: "松开结束", sending: "正在发送", micReady: "麦克风已就绪", exitVoice: "退出语音", @@ -465,10 +481,18 @@ const translations: Record> = { microphoneMode: "麦克风模式", defaultMicrophone: "默认浏览器麦克风", microphoneNumber: "麦克风 {{index}}", + speakerNumber: "扬声器 {{index}}", + permission: "权限", + permissionUnknown: "尚未请求", + permissionGranted: "已允许", + permissionDenied: "已拒绝", inputVolume: "输入音量", + voxThreshold: "语音激活阈值", + micLevel: "麦克风音量", microphoneTest: "麦克风测试", stopTest: "停止测试", startTest: "开始测试", + localMicTestHint: "本地测试:录音只在浏览器中播放,不会发送到 TeamSpeak。", silence: "安静", optimal: "最佳", loud: "较响", @@ -476,6 +500,12 @@ const translations: Record> = { speakers: "扬声器 / 耳机", defaultOutput: "默认浏览器输出", outputVolume: "输出音量", + outputDeviceUnsupported: "当前浏览器不支持扬声器设备选择,将使用默认输出设备。", + notificationVolume: "通知音量", + audioStatus: "音频状态", + audioReady: "音频已就绪", + audioSuspended: "音频被浏览器暂停", + audioUnknown: "尚未初始化", audioPrivacy: "WebSpeak 会在浏览器安全上下文中处理音频,不会保存录音。", cancel: "取消", saveChanges: "保存更改", @@ -611,6 +641,8 @@ const translations: Record> = { freeMic: "Open mic", pushToTalk: "Push to talk", pushToTalkHint: "Hold Space to talk", + holdToTalk: "Hold to talk", + releaseToTalk: "Release to stop", sending: "Sending", micReady: "Microphone ready", exitVoice: "Leave voice", @@ -649,10 +681,18 @@ const translations: Record> = { microphoneMode: "Microphone mode", defaultMicrophone: "Default browser microphone", microphoneNumber: "Microphone {{index}}", + speakerNumber: "Speaker {{index}}", + permission: "Permission", + permissionUnknown: "Not requested", + permissionGranted: "Granted", + permissionDenied: "Denied", inputVolume: "Input volume", + voxThreshold: "Voice activation threshold", + micLevel: "Mic level", microphoneTest: "Microphone test", stopTest: "Stop test", startTest: "Start test", + localMicTestHint: "Local test: the recording is played in this browser and never sent to TeamSpeak.", silence: "Silence", optimal: "Optimal", loud: "Loud", @@ -660,6 +700,12 @@ const translations: Record> = { speakers: "Speakers / headphones", defaultOutput: "Default browser output", outputVolume: "Output volume", + outputDeviceUnsupported: "Output device selection is not supported by this browser. Using the default output device.", + notificationVolume: "Notification volume", + audioStatus: "Audio status", + audioReady: "Audio ready", + audioSuspended: "Audio paused by the browser", + audioUnknown: "Not initialized", audioPrivacy: "WebSpeak processes audio in the browser's secure context and does not save recordings.", cancel: "Cancel", saveChanges: "Save changes", @@ -700,7 +746,10 @@ function localizedMessage(message: string) { const exact: Record = { "语音功能需要 HTTPS 安全连接": "Voice requires a secure HTTPS connection", "当前浏览器不支持麦克风访问": "This browser does not support microphone access", + "当前浏览器不支持 Web Audio 音频处理": "This browser does not support Web Audio processing", "当前浏览器不支持音频解码,请使用最新版 Chrome 或 Edge": "Audio decoding is unavailable. Use the latest Chrome or Edge", + "当前浏览器不支持扬声器设备选择,将使用默认输出设备": "Output device selection is not supported by this browser. Using the default output device", + "所选扬声器当前不可用": "The selected speaker is not available", "连接服务器失败,请检查邀请链接或服务器状态": "Could not connect. Check the invite link or server status", "TeamSpeak 连接已断开": "The TeamSpeak connection was closed", "连接已断开": "The connection was closed", @@ -825,6 +874,10 @@ watch(channelTree, (list) => { } }, { deep: true }); watch([() => chatMessages.length, chatTab, privateClientId], () => nextTick(scrollChatToEnd)); +watch(() => chatMessages.length, (length, previousLength) => { + const latest = chatMessages[length - 1]; + if (latest && length > previousLength && latest.scope === "private" && !latest.isSelf) playNotification("private"); +}); watch(() => voiceState.errorCode, (code) => { if (code !== "CHANNEL_PASSWORD_REQUIRED" || !selectedChannelId.value) return; const password = window.prompt(t("channelPasswordPrompt"), ""); @@ -834,6 +887,7 @@ watch(() => pokeNotifications.length, (length, previousLength) => { const latest = pokeNotifications[length - 1]; if (!latest || length <= previousLength) return; showToast(`${latest.invokerName} ${t("pokedYou")}${latest.message ? `:${latest.message}` : ""}`); + playNotification("poke"); if (typeof Notification !== "undefined" && Notification.permission === "granted") new Notification(t("poke"), { body: `${latest.invokerName}: ${latest.message || t("pokedYou")}` }); }); watch(settingsOpen, (open) => { @@ -855,7 +909,11 @@ watch([rememberIdentity, identityMaterial], ([remember, material]) => { if (!remember && material) identityMaterial.value = ""; }); watch(() => voiceState.connected, (connected) => { - if (!connected) return; + if (!connected) { + stopPointerTalk(); + return; + } + playNotification("connected"); const address = serverAddress.value.trim(); if (!address) return; const recent: RecentServer = { @@ -868,8 +926,18 @@ watch(() => voiceState.connected, (connected) => { }; void recordRecentServer(recent).then(() => listRecentServers().then((items) => { recentServers.value = items; })); }); +watch(() => voiceState.reconnecting, (reconnecting, wasReconnecting) => { + if (reconnecting && !wasReconnecting) { + stopPointerTalk(); + playNotification("disconnected"); + } +}); +watch(() => voiceState.reconnectFailed, (failed, wasFailed) => { + if (failed && !wasFailed) playNotification("reconnectFailed"); +}); let deviceChangeHandler: (() => void) | undefined; +let releasePttHandler: (() => void) | undefined; onMounted(() => { browserError.value = checkSupport() ?? ""; @@ -885,12 +953,20 @@ onMounted(() => { }); void listFavorites().then((items) => { favoriteServers.value = items; }); void listRecentServers().then((items) => { recentServers.value = items; }); - deviceChangeHandler = () => { void prepareInputDevices().catch(() => undefined); }; + deviceChangeHandler = () => { void refreshAudioDevices().catch(() => undefined); }; navigator.mediaDevices?.addEventListener("devicechange", deviceChangeHandler); + releasePttHandler = () => stopPointerTalk(); + window.addEventListener("blur", releasePttHandler); + document.addEventListener("visibilitychange", releasePttHandler); }); onUnmounted(() => { + stopPointerTalk(); disconnect(); if (deviceChangeHandler) navigator.mediaDevices?.removeEventListener("devicechange", deviceChangeHandler); + if (releasePttHandler) { + window.removeEventListener("blur", releasePttHandler); + document.removeEventListener("visibilitychange", releasePttHandler); + } if (toastTimer) clearTimeout(toastTimer); }); @@ -908,6 +984,7 @@ function doConnect() { } function doDisconnect() { + stopPointerTalk(); disconnect(); selectedChannelId.value = ""; showToast(t("leftToast")); @@ -1127,6 +1204,14 @@ function onOutputVolume(event: Event) { setOutputVolume(Number((event.target as HTMLInputElement).value) / 100); } +function onVoxThreshold(event: Event) { + setVoxThreshold(Number((event.target as HTMLInputElement).value) / 1000); +} + +function onNotificationVolume(event: Event) { + setNotificationVolume(Number((event.target as HTMLInputElement).value) / 100); +} + async function onInputDeviceChange(event: Event) { audioSettingsError.value = ""; try { @@ -1136,6 +1221,15 @@ async function onInputDeviceChange(event: Event) { } } +async function onOutputDeviceChange(event: Event) { + audioSettingsError.value = ""; + try { + await setOutputDevice((event.target as HTMLSelectElement).value); + } catch (error: unknown) { + audioSettingsError.value = localizedMessage(error instanceof Error ? error.message : "无法切换扬声器"); + } +} + async function toggleMicTest() { audioSettingsError.value = ""; try { @@ -1192,6 +1286,19 @@ function stopPointerTalk() { pttActive.value = false; setPTT(false); } + +function onMobilePttDown(event: PointerEvent) { + if (micMode.value !== "ptt") return; + const target = event.currentTarget as HTMLElement | null; + if (target?.setPointerCapture && !target.hasPointerCapture(event.pointerId)) target.setPointerCapture(event.pointerId); + startPointerTalk(); +} + +function onMobilePttUp(event: PointerEvent) { + const target = event.currentTarget as HTMLElement | null; + if (target?.releasePointerCapture && target.hasPointerCapture(event.pointerId)) target.releasePointerCapture(event.pointerId); + stopPointerTalk(); +}