Compare commits

...
2 Commits
18 changed files with 594 additions and 34 deletions

No files matched your search

+2
View File
@@ -21,6 +21,8 @@
当前版本 / Current version: **[v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2)** · [更新内容 / Release notes](./docs/README.zh-CN.md#latest-release-notes)
dev 实验功能 / dev experiment: [锁屏通话 / Lock-screen calls](./docs/EXPERIMENTAL_BACKGROUND_CALLS.md)(默认关闭,尚未通过真机锁屏验收 / off by default; physical-device validation pending)。
## 关于 WebSpeak · Overview
WebSpeak 将 TeamSpeak 3 / TeamSpeak 6 带到浏览器:无需安装桌面客户端,即可加入语音频道、发送消息和分享屏幕。你可以自行部署网关,并通过网页后台管理服务器、访问策略、皮肤和运行数据。
+43
View File
@@ -0,0 +1,43 @@
# 锁屏通话实验 / Experimental lock-screen calls
此功能目前只用于 dev 分支实验,默认关闭。它改善浏览器的音频路径,不能保证浏览器或操作系统允许锁屏后一直录音、联网或播放。尚未完成 Android/iOS 真机锁屏验收。
## 使用
在音频配置中开启“锁屏通话(实验性)”,然后断开并重新进入语音房间。设置只在下次连接生效,通话中修改不会突然更换麦克风路径。需要网关及浏览器支持 WebRTC。没有 WebRTC 或协商失败时,回退到原有兼容传输,音频配置中的原生模式提示会消失。
原生模式直接发送系统麦克风音轨,并用浏览器原生 `<audio srcObject>` 接收。浏览器的回声消除、标准降噪仍可使用;RNNoise 强降噪、软件输入增益、客户端音量计、语音阈值和伴奏不参与这条路径。非零输入增益不会缩放声音,0% 仍禁止发送。此模式持续发送未静音的麦克风,请在不需要说话时静音。静音同时控制音轨与网关的麦克风状态。关闭实验选项并重新连接可恢复普通处理。
支持的浏览器会显示系统媒体控制。Pause 同时静音麦克风及接收声音;Play 只恢复接收,不解除麦克风静音。麦克风切换需要明确操作,Stop/Hang up 会结束连接并释放采集。在支持 Audio Session API 的平台上声明 `play-and-record`,离开时恢复之前的类型。系统暂停或结束音轨时,音频配置会显示中断提示。
## 实现与边界
- 普通模式保留现有 Web Audio、WebRTC 与 PCM 回退。原生模式不创建麦克风的 AudioContext、AudioWorklet、分析器或混音节点。
- 远端原生音频的 `play()` 不再等待采集 AudioContext 的 `resume()`;未完成的恢复请求不会连带阻塞收听。
- 返回前台和系统 Play 只重试当前会话的播放。它们不会重新申请麦克风、取消静音或重新建立已结束的通话。
- Media Session 是系统控制接口,不是后台保活权限。PWA、Service Worker、屏幕常亮都不能绕过系统限制;不播放静音文件或伪造音乐来保活。
- WebSocket 兼容模式仍依赖 JavaScript 解码与 Web Audio,不作锁屏持续通话保证。真实语音需要持续网络连接,不能像音乐文件那样提前缓冲。
- Android APK 目前仍为 WebView 与嵌入式网关。这次未添加原生前台音频服务,也未完成 APK 后台双向语音验收。
## 验证
自动化测试覆盖原始音轨发送、静音、权限请求取消、WebRTC 失败/缺失后的回退、系统 API 缺失/部分支持、旧系统动作隔离、采集恢复不阻塞播放,以及前台恢复不自动开麦。
2026-11-24 本地验证:`npm run verify` 的 1023 项测试全部通过,前后端构建成功。Windows Edge 使用模拟麦克风、两个真实浏览器 RTCPeerConnection 做回环,确认原生轨道收发 RTP、播放不等待采集恢复、静音切换及资源释放;1440px 与 390px 视口检查了全部五种语言的设置界面。该回环未连接 TeamSpeak,移动视口也不是手机系统锁屏测试。
真机验收应连接真实 TeamSpeak 房间,用第二个独立客户端双向监听,并分别记录:
1. Android Chrome、iPhone Safari、已安装 PWA 和 APK 的版本、系统版本、网络与省电设置。
2. 普通模式与实验模式下,前台、切应用、锁屏各 1/5/15 分钟的收听和发送;每次恢复说话前后都检查第二端实际听感及媒体收发计数。
3. 开麦/静音/输入音量 0%、系统 Play/Pause/麦克风控制、蓝牙切换、电话打断、网络切换和网关重连。
4. 断开或撤销权限后系统录音指示消失;旧权限请求或系统按钮不能重新启动采集。关闭实验并重连后强降噪、伴奏和普通音量控制恢复。
桌面模拟移动视口、无头浏览器和单元测试不代表通过真机锁屏验收。
## References
- HollyMusic [`useAudioPlayer.ts`](https://github.com/redcatH/HollyMusic/blob/abbae61d4ee7a7ac53a417c4da6802ff70b10717/hooks/useAudioPlayer.ts) and [`audio-analysis.ts`](https://github.com/redcatH/HollyMusic/blob/abbae61d4ee7a7ac53a417c4da6802ff70b10717/lib/client/audio-analysis.ts): native playback separated from optional Web Audio processing. This implementation uses the same architectural idea; no HollyMusic source was copied.
- [Media Session API](https://web.dev/articles/media-session) and [Audio Session draft](https://www.w3.org/TR/audio-session/).
- [Android foreground service types](https://developer.android.com/develop/background-work/services/fgs/service-types).
The experiment is off by default and applies on the next connection. It uses native WebRTC microphone tracks and native remote playback, while keeping mute, hangup and compatibility fallback. Optional Web Audio processing and accompaniment are unavailable in the native route. OS playback controls never unmute the microphone implicitly. Browser/OS restrictions still apply; physical-device background calling and native Android foreground audio services remain unverified/unimplemented respectively.
+1 -1
View File
@@ -11,7 +11,7 @@
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs",
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs web/src/services/call-media-session.test.ts",
"verify": "npm test && npm run build && npm run web:build",
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
+5 -4
View File
@@ -47,15 +47,16 @@
:value="inputVolume * 100"
:style="rangeStyle(inputVolume, 1)"
:aria-label="t('inputVolume')"
:disabled="backgroundCallActive"
@input="onInputVolume"
/>
<div class="dock-panel-divider"></div>
<label class="dock-switch-row">
<span><strong>{{ t("noiseSuppression") }}</strong></span>
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
<select class="noise-suppression-level" :value="backgroundCallActive && noiseSuppressionLevel === 'strong' ? 'standard' : noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
<option value="off">{{ t("noiseSuppressionOff") }}</option>
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
<option value="strong" :disabled="backgroundCallActive">{{ t("noiseSuppressionStrong") }}</option>
</select>
</label>
</div>
@@ -131,12 +132,12 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js";
import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js";
const props = defineProps<{
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive">;
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive" | "backgroundCallActive">;
controls: Pick<ReturnType<typeof useWebClientAudioControls>, "toggleMicrophone" | "toggleNoiseSuppression" | "onInputVolume" | "onOutputVolume" | "onNoiseSuppressionChange" | "toggleAccompaniment">;
t: (key: string) => string;
rangeStyle: (value: number, max: number) => Record<string, string>;
}>();
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive } = props.model;
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive, backgroundCallActive } = props.model;
const { toggleMicrophone, onInputVolume, onOutputVolume, onNoiseSuppressionChange, toggleAccompaniment } = props.controls;
const emit = defineEmits<{ settings: []; outputMute: [] }>();
</script>
@@ -25,6 +25,15 @@
:size="19" /></button></header
><div class="settings-content">
<div class="settings-audio-card">
<section class="settings-section">
<label class="settings-form-row background-call-setting">
<span><strong>{{ t("backgroundCallTitle") }}</strong><small>{{ t("backgroundCallHint") }}</small></span>
<input type="checkbox" :checked="backgroundCallEnabled" @change="onBackgroundCallChange" />
</label>
<p v-if="backgroundCallActive" class="settings-hint background-call-note">{{ t("backgroundCallProcessingHint") }}</p>
<p v-if="backgroundCallActive && backgroundCallInterrupted" class="settings-error background-call-note">{{ t("backgroundCallInterrupted") }}</p>
<p v-else-if="!backgroundCallActive && backgroundCallEnabled" class="settings-hint background-call-note">{{ t("backgroundCallPending") }}</p>
</section>
<section class="settings-section"
><h3
><Icon
@@ -78,10 +87,10 @@
></div
><label class="settings-form-row">
<span><strong>{{ t("noiseSuppression") }}</strong><small>{{ t("noiseSuppressionHint") }}</small></span>
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
<select class="noise-suppression-level" :value="backgroundCallActive && noiseSuppressionLevel === 'strong' ? 'standard' : noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
<option value="off">{{ t("noiseSuppressionOff") }}</option>
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
<option value="strong" :disabled="backgroundCallActive">{{ t("noiseSuppressionStrong") }}</option>
</select>
</label
><div class="settings-form-row settings-range-form-row"
@@ -97,6 +106,7 @@
:value="inputVolume * 100"
:style="rangeStyle(inputVolume, 1)"
:aria-label="t('inputVolume')"
:disabled="backgroundCallActive"
@input="onInputVolume"
/></div
></div
@@ -113,12 +123,13 @@
:value="voxThreshold * 1000"
:style="rangeStyle(voxThreshold, 0.08)"
:aria-label="t('voxThreshold')"
:disabled="backgroundCallActive"
@input="onVoxThreshold"
/></div
></div
><div class="audio-level-row"
><span>{{ t("micLevel") }}</span
><strong>{{ Math.round(micLevel * 100) }}%</strong></div
><strong>{{ backgroundCallActive ? t('backgroundCallNative') : `${Math.round(micLevel * 100)}%` }}</strong></div
><div class="audio-level-track"
><i :style="{ width: `${Math.round(micLevel * 100)}%` }"></i></div
><div class="mic-test"
@@ -214,7 +225,9 @@
><div class="audio-diagnostic"
><span>{{ t("audioStatus") }}</span
><strong>{{
audioContextState === "running"
backgroundCallActive && backgroundCallInterrupted
? t("audioSuspended")
: backgroundCallActive || audioContextState === "running"
? microphoneError
? t("audioUnavailable")
: t("audioReady")
@@ -255,6 +268,10 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js";
import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js";
type AudioSettingsState = Pick<ReturnType<typeof useVoiceWebSocket>,
| "backgroundCallEnabled"
| "backgroundCallActive"
| "backgroundCallInterrupted"
| "setBackgroundCallEnabled"
| "inputDevices"
| "outputDevices"
| "selectedInputDeviceId"
@@ -300,6 +317,10 @@ const { onDialogKeydown } = useDialogFocus(dialog, () => emit("close"));
// The page owns the stable voice refs and audio controller; this dialog only presents them.
const {
backgroundCallEnabled,
backgroundCallActive,
backgroundCallInterrupted,
setBackgroundCallEnabled,
inputDevices,
outputDevices,
selectedInputDeviceId,
@@ -332,6 +353,10 @@ const {
toggleMicrophone,
} = props.controls;
function onBackgroundCallChange(event: Event): void {
setBackgroundCallEnabled((event.target as HTMLInputElement).checked);
}
const inputDeviceOptions = computed(() => [
{ value: "", label: props.t("defaultMicrophone") },
...inputDevices.map((device, index) => ({
@@ -347,3 +372,12 @@ const outputDeviceOptions = computed(() => [
})),
]);
</script>
<style scoped>
.background-call-setting { display: flex; align-items: flex-start; gap: 16px; }
.background-call-setting span { flex: 1; min-width: 0; }
.background-call-setting strong, .background-call-setting small { display: block; }
.background-call-setting small { margin-top: 6px; font-size: 12px; line-height: 1.65; color: var(--text-muted); }
.background-call-setting input { flex: none; width: 18px; height: 18px; margin: 2px 0 0; accent-color: var(--accent); }
.background-call-note { font-size: 12px; line-height: 1.65; }
</style>
+91 -16
View File
@@ -5,6 +5,8 @@ export type { MicrophoneProcessingSettings } from "../voice/microphone-capture.j
import { createAudioSinkRouter } from "../voice/audio-sink.js";
import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accompaniment.js";
import { createWebRtcTransport } from "../voice/webrtc-transport.js";
import { createNativeMicrophoneCapture } from "../voice/native-microphone.js";
import { createCallMediaSession } from "../services/call-media-session.js";
import { createVoiceConnection } from "../voice/connection.js";
import { createVoiceCommands } from "../voice/commands.js";
import { createVoiceSessionState } from "../voice/session-state.js";
@@ -21,7 +23,7 @@ import type { ChatMessage } from "../../../src/shared/voice-models.js";
import type { ClientCommandPayloads, ClientCommandType } from "../../../src/shared/client-commands.js";
export type { ScreenShareStreamDescription as ScreenShareStream, ScreenShareViewerDescription as ScreenShareViewer, ScreenSharePeerSignal as ScreenShareSignal } from "../../../src/shared/screen-share.js";
export type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
import { computed, onBeforeUnmount, reactive, ref, shallowRef } from "vue";
import { computed, onScopeDispose, reactive, ref, shallowRef, watch } from "vue";
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
export interface VoiceState {
@@ -257,6 +259,11 @@ export function useVoiceWebSocket() {
let micStream: MediaStream | null = null;
const microphoneCaptureFactory = createMicrophoneCaptureFactory();
let microphoneCapture: MicrophoneCapture | null = null;
let microphoneNative = false;
const backgroundCallEnabled = ref(false);
const backgroundCallActive = ref(false);
const backgroundCallInterrupted = ref(false);
let backgroundCallTouched = false;
let pendingMicrophoneCapture: AbortController | null = null;
const accompanimentActive = ref(false);
const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia));
@@ -345,7 +352,7 @@ export function useVoiceWebSocket() {
stunServer: () => webRtcStunServer,
prepareMicrophone: async () => {
await ensureMicrophone();
return micStream ? { context: getAudioCtx(), stream: micStream,
return micStream ? { context: microphoneNative ? null : getAudioCtx(), stream: micStream,
processedStream: microphoneCapture?.processedStream ?? micStream } : null;
},
stopPcm: stopCaptureGraph,
@@ -366,6 +373,7 @@ export function useVoiceWebSocket() {
async onFallback(reason, isCurrent) {
if (!isCurrent()) return;
sessionTrace.record("webrtc.fallback", { code: safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE" });
backgroundCallActive.value = false;
setAudioNotice("WEBRTC_FALLBACK", `实时语音(WebRTC)不可用(错误代码:${safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE"}),已切换为兼容传输:延迟与音质可能下降`);
try { await startMicrophone(); }
catch (error) { if (isCurrent()) setMicrophoneError(error); }
@@ -387,6 +395,38 @@ export function useVoiceWebSocket() {
onPlaying: syncAudioContextNotice,
},
});
const callMediaSession = createCallMediaSession({
resume() {
// A media Play command resumes listening only. Unmuting needs an explicit
// microphone action, never a page visibility or system playback event.
outputMuted.value = false;
applyOutputVolume();
webrtc.resumePlayback();
},
pause() {
setMicrophoneMuted(true);
outputMuted.value = true;
applyOutputVolume();
},
toggleMicrophone: () => setMicrophoneMuted(!microphoneMuted.value),
hangup: () => disconnect(),
});
function syncCallMediaSession(): void {
callMediaSession.sync({ active: state.connected && backgroundCallActive.value,
muted: microphoneMuted.value, outputMuted: outputMuted.value, title: serverInfo.value?.name || "WebSpeak" });
}
watch([() => state.connected, backgroundCallActive, microphoneMuted, outputMuted, serverInfo], syncCallMediaSession);
const resumeVisibleCall = () => {
if (!state.connected || !backgroundCallActive.value || document.visibilityState !== "visible") return;
webrtc.resumePlayback();
};
document.addEventListener("visibilitychange", resumeVisibleCall);
window.addEventListener("pageshow", resumeVisibleCall);
onScopeDispose(() => {
callMediaSession.dispose();
document.removeEventListener("visibilitychange", resumeVisibleCall);
window.removeEventListener("pageshow", resumeVisibleCall);
});
const audioDiagnostics = createAudioDiagnostics({
source() {
const socket = ws.value;
@@ -398,7 +438,7 @@ export function useVoiceWebSocket() {
presentation({ peer }) {
return {
microphoneMuted: microphoneMuted.value,
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live")),
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live" && !track.muted)),
microphonePermission: audioPermission.value,
playbackState: peer
? webrtc.output ? webrtc.output.paused ? "paused" : "playing" : "unavailable"
@@ -414,6 +454,7 @@ export function useVoiceWebSocket() {
preferredInputDeviceId: committedInputDeviceId,
inputDeviceId: committedInputDeviceId,
microphoneMuted: microphoneMuted.value,
backgroundCallEnabled: backgroundCallEnabled.value,
noiseSuppressionEnabled: committedNoiseSuppressionLevel !== "off",
noiseSuppressionLevel: committedNoiseSuppressionLevel,
voxThreshold: voxThreshold.value,
@@ -433,6 +474,7 @@ export function useVoiceWebSocket() {
}
const audioPreferencesReady = loadLocalPreferences().then((preferences) => {
if (!backgroundCallTouched) backgroundCallEnabled.value = preferences.backgroundCallEnabled === true;
if (!inputDeviceTouched) {
if (!selectedInputDeviceId.value) selectedInputDeviceId.value = preferences.preferredInputDeviceId ?? preferences.inputDeviceId ?? "";
committedInputDeviceId = selectedInputDeviceId.value;
@@ -549,7 +591,7 @@ export function useVoiceWebSocket() {
/** A suspended AudioContext silently swallows capture: say so instead of pretending. */
function syncAudioContextNotice(): void {
if (audioCtx && audioCtx.state === "suspended") {
if (!microphoneNative && audioCtx && audioCtx.state === "suspended") {
setAudioNotice("AUDIO_CONTEXT_SUSPENDED", "浏览器的音频处理被暂停(需要一次页面交互),麦克风与扬声器可能无声:请点击页面任意位置后重试");
} else {
clearAudioNotice("AUDIO_CONTEXT_SUSPENDED");
@@ -702,9 +744,10 @@ export function useVoiceWebSocket() {
pendingMicrophoneCapture?.abort();
const controller = new AbortController();
pendingMicrophoneCapture = controller;
const ctx = getAudioCtx();
const native = backgroundCallActive.value;
const ctx = native ? null : getAudioCtx();
const assertCurrent = (): void => {
if (generation !== microphoneGeneration || audioCtx !== ctx || controller.signal.aborted) throw new CancelledMediaOperation();
if (generation !== microphoneGeneration || (ctx && audioCtx !== ctx) || controller.signal.aborted) throw new CancelledMediaOperation();
};
let nextStream: MediaStream | null = null;
let nextCapture: MicrophoneCapture | null = null;
@@ -712,24 +755,35 @@ export function useVoiceWebSocket() {
try {
nextStream = await requestMediaBeforeAudioResume(
() => navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() }),
() => ctx.state === "suspended" ? ctx.resume() : Promise.resolve(),
() => ctx?.state === "suspended" ? ctx.resume() : Promise.resolve(),
);
assertCurrent();
audioPermission.value = "granted";
factoryOwnsStream = true;
nextCapture = await microphoneCaptureFactory.prepare({
context: ctx, stream: nextStream, signal: controller.signal, assertCurrent,
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
});
if (native) {
nextCapture = createNativeMicrophoneCapture(nextStream);
factoryOwnsStream = true;
} else {
factoryOwnsStream = true;
nextCapture = await microphoneCaptureFactory.prepare({
context: ctx!, stream: nextStream, signal: controller.signal, assertCurrent,
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
});
}
assertCurrent();
// Commit only a complete graph. Permission and node failures leave the
// previous stream, PCM route and WebRTC peer untouched.
stopMicrophone(false);
micStream = nextStream;
microphoneCapture = nextCapture;
microphoneNative = native;
backgroundCallInterrupted.value = false;
sessionTrace.record("microphone.route", { native });
const microphoneTrack = nextStream.getAudioTracks()[0];
if (microphoneTrack) {
const recordTrack = (stateName: string) => sessionTrace.record("microphone.track", { state: stateName, muted: microphoneTrack.muted });
const recordTrack = (stateName: string) => {
sessionTrace.record("microphone.track", { state: stateName, muted: microphoneTrack.muted });
if (micStream === nextStream && native) backgroundCallInterrupted.value = microphoneTrack.muted || microphoneTrack.readyState !== "live";
};
recordTrack(microphoneTrack.readyState);
microphoneTrack.addEventListener("mute", () => recordTrack("mute"));
microphoneTrack.addEventListener("unmute", () => recordTrack("unmute"));
@@ -759,8 +813,8 @@ export function useVoiceWebSocket() {
// 导出给 WebClient:开麦前先 await 此函数完成真实采集,避免出现“假成功”
async function ensureMicrophone(): Promise<void> {
if (microphoneStartPromise) return microphoneStartPromise;
if (micStream) return;
if (microphoneStartPromise) await microphoneStartPromise;
if (micStream && microphoneNative === backgroundCallActive.value) return;
if (!microphoneStartPromise) {
const generation = microphoneGeneration + 1;
const pending = startMicrophone().then(async () => {
@@ -793,6 +847,10 @@ export function useVoiceWebSocket() {
}
async function startAccompaniment(): Promise<void> {
if (backgroundCallActive.value) {
accompanimentErrorCode.value = "backgroundMode";
throw new DOMException("Accompaniment is unavailable in native call mode", "NotSupportedError");
}
await accompaniment.start();
}
@@ -827,6 +885,8 @@ export function useVoiceWebSocket() {
if (micStream) sessionTrace.record("microphone.track", { state: "released" });
microphoneCapture?.dispose();
microphoneCapture = null;
microphoneNative = false;
backgroundCallInterrupted.value = false;
webrtc.releaseInput();
micStream = null;
if (closeContext) {
@@ -1067,6 +1127,8 @@ export function useVoiceWebSocket() {
commands.clear(new Error("语音连接已关闭"));
screenShare.stopTransport(sendScreenStop);
webrtc.stop();
backgroundCallActive.value = false;
callMediaSession.dispose();
remotePlayback.clearAll();
stopMicrophone();
clearSpeakingState();
@@ -1106,6 +1168,9 @@ export function useVoiceWebSocket() {
sendCmd("setMicrophoneMuted", { muted: microphoneMuted.value });
screenShare.setIceServers(msg.screenShareIceServers);
webRtcStunServer = msg.webRtcStunServer ?? "";
backgroundCallActive.value = backgroundCallEnabled.value && msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined";
sessionTrace.record("call.background", { requested: backgroundCallEnabled.value, native: backgroundCallActive.value });
syncCallMediaSession();
sessionState.connected(msg);
applyWhisperState(msg.whisperTargetIds, msg.whisperActive);
if (typeof msg.identity === "string" && msg.identity.length <= 8192) {
@@ -1441,6 +1506,12 @@ export function useVoiceWebSocket() {
void saveAudioPreferences();
}
function setBackgroundCallEnabled(enabled: boolean): void {
backgroundCallTouched = true;
backgroundCallEnabled.value = enabled;
void saveAudioPreferences();
}
async function setNoiseSuppressionLevel(level: "off" | "standard" | "strong"): Promise<void> {
if (noiseSuppressionLevel.value === level) return;
noiseSuppressionTouched = true;
@@ -1479,7 +1550,7 @@ export function useVoiceWebSocket() {
void saveAudioPreferences();
}
onBeforeUnmount(() => sessionTrace.dispose());
onScopeDispose(() => { disconnect(); sessionTrace.dispose(); });
return {
pluginSession,
@@ -1495,6 +1566,10 @@ export function useVoiceWebSocket() {
serverEvents,
pokeNotifications,
microphoneMuted,
backgroundCallEnabled,
backgroundCallActive,
backgroundCallInterrupted,
setBackgroundCallEnabled,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
@@ -166,7 +166,9 @@ export function useWebClientAudioControls({
await startAccompaniment();
if (accompanimentActive.value) showToast(t("accompanimentStarted"));
} catch {
const messageKey = accompanimentErrorCode.value === "needsWebRtc"
const messageKey = accompanimentErrorCode.value === "backgroundMode"
? "backgroundCallProcessingHint"
: accompanimentErrorCode.value === "needsWebRtc"
? "accompanimentNeedsWebRtc"
: accompanimentErrorCode.value === "noAudio"
? "accompanimentNoAudio"
+30
View File
@@ -347,6 +347,12 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
exportAudioTrace: "导出最近两分钟的音频诊断",
audioTraceHint: "可导出不含语音内容、昵称或服务器地址的本地诊断记录。",
backgroundVoiceHint: "浏览器后台麦克风受浏览器和系统策略限制;锁屏或切后台后可能暂停。",
backgroundCallTitle: "锁屏通话(实验性)",
backgroundCallHint: "默认关闭,下次连接生效。尝试使用系统原生语音链路;锁屏或后台通话仍受浏览器与系统限制。",
backgroundCallProcessingHint: "本次通话使用系统麦克风处理并持续开麦(可手动静音)。强降噪、输入增益、音量计、语音阈值和伴奏不可用;关闭此选项后重新连接可恢复。",
backgroundCallPending: "等待下次连接启用;需要网关与浏览器支持 WebRTC,不可用时仍使用兼容传输。",
backgroundCallNative: "系统原生语音",
backgroundCallInterrupted: "系统已暂停或结束麦克风采集。返回页面后检查权限,必要时重新连接;不会自动取消静音。",
rnnoise: "RNNoise 降噪",
echoCancellation: "回声消除",
autoGainControl: "自动增益",
@@ -779,6 +785,12 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
exportAudioTrace: "Export the last two minutes of audio diagnostics",
audioTraceHint: "The local trace excludes audio content, nicknames, and server addresses.",
backgroundVoiceHint: "Background microphone capture depends on browser and OS policy and may pause when hidden or locked.",
backgroundCallTitle: "Lock-screen calls (experimental)",
backgroundCallHint: "Off by default; applies on the next connection. Tries the native audio path. Browser and OS background restrictions still apply.",
backgroundCallProcessingHint: "This call uses system microphone processing with continuous transmission unless muted. Strong denoising, input gain, level meters, voice threshold and accompaniment are unavailable. Disable this option and reconnect to restore them.",
backgroundCallPending: "Waiting for the next connection. Requires browser and gateway WebRTC support; otherwise compatibility transport is used.",
backgroundCallNative: "Native system audio",
backgroundCallInterrupted: "The system paused or ended microphone capture. Return to the page, check permission and reconnect if needed. Your microphone will not be unmuted automatically.",
rnnoise: "RNNoise suppression",
echoCancellation: "Echo cancellation",
autoGainControl: "Automatic gain control",
@@ -1204,6 +1216,12 @@ webClientTranslations.de = {
exportAudioTrace: "Letzte zwei Minuten der Audiodiagnose exportieren",
audioTraceHint: "Der lokale Verlauf enthält keine Audioinhalte, Namen oder Serveradressen.",
backgroundVoiceHint: "Die Mikrofonaufnahme im Hintergrund hängt von Browser und Betriebssystem ab und kann pausieren.",
backgroundCallTitle: "Telefonieren bei gesperrtem Bildschirm (experimentell)",
backgroundCallHint: "Standardmäßig aus; gilt ab der nächsten Verbindung. Verwendet nach Möglichkeit den nativen Audiopfad. Browser- und Systembeschränkungen gelten weiterhin.",
backgroundCallProcessingHint: "Dieser Anruf nutzt die Mikrofonverarbeitung des Systems und sendet dauerhaft, sofern nicht stummgeschaltet. Starke Rauschunterdrückung, Eingangsverstärkung, Pegelanzeige, Sprachschwelle und Begleitung sind nicht verfügbar. Zum Wiederherstellen deaktivieren und neu verbinden.",
backgroundCallPending: "Wartet auf die nächste Verbindung. Erfordert WebRTC im Browser und Gateway; andernfalls wird der Kompatibilitätsmodus verwendet.",
backgroundCallNative: "Natives Systemaudio",
backgroundCallInterrupted: "Das System hat die Mikrofonaufnahme unterbrochen oder beendet. Zur Seite zurückkehren, Berechtigung prüfen und bei Bedarf neu verbinden. Das Mikrofon wird nicht automatisch eingeschaltet.",
rnnoise: "RNNoise-Geräuschunterdrückung",
echoCancellation: "Echounterdrückung",
autoGainControl: "Automatische Verstärkungsregelung",
@@ -1379,6 +1397,12 @@ webClientTranslations.ru = {
exportAudioTrace: "Экспортировать диагностику звука за последние две минуты",
audioTraceHint: "Локальная запись не содержит аудио, имён или адресов серверов.",
backgroundVoiceHint: "Фоновая запись с микрофона зависит от браузера и ОС и может приостанавливаться.",
backgroundCallTitle: "Звонки при блокировке экрана (эксперимент)",
backgroundCallHint: "По умолчанию выключено; применяется при следующем подключении. Использует системный аудиотракт, когда возможно. Ограничения браузера и ОС сохраняются.",
backgroundCallProcessingHint: "Используется системная обработка микрофона с непрерывной передачей, пока микрофон не выключен. Сильное шумоподавление, усиление входа, индикаторы уровня, порог голоса и аккомпанемент недоступны. Для восстановления выключите опцию и подключитесь заново.",
backgroundCallPending: "Ожидание следующего подключения. Нужна поддержка WebRTC браузером и шлюзом; иначе используется совместимый режим.",
backgroundCallNative: "Системный аудиотракт",
backgroundCallInterrupted: "Система приостановила или завершила запись. Вернитесь на страницу, проверьте разрешение и при необходимости подключитесь заново. Микрофон не включается автоматически.",
highQuality: "Качественный звук",
opusAudio: "Передача Opus с низкой задержкой",
secureJoin: "Безопасное подключение",
@@ -1598,6 +1622,12 @@ webClientTranslations.ja = {
exportAudioTrace: "直近 2 分間の音声診断をエクスポート",
audioTraceHint: "音声、ニックネーム、サーバーアドレスを含まないローカル診断です。",
backgroundVoiceHint: "バックグラウンドでのマイク利用はブラウザーと OS の制御を受け、停止する場合があります。",
backgroundCallTitle: "ロック画面で通話(試験機能)",
backgroundCallHint: "初期設定はオフ。次回接続時に適用されます。システムの音声経路を試しますが、ブラウザーと OS のバックグラウンド制限は適用されます。",
backgroundCallProcessingHint: "システムのマイク処理を使い、ミュートするまで連続送信します。強いノイズ抑制、入力ゲイン、レベル表示、音声しきい値、伴奏は使えません。元に戻すにはオフにして再接続してください。",
backgroundCallPending: "次回接続を待っています。ブラウザーとゲートウェイの WebRTC 対応が必要です。非対応の場合は互換モードになります。",
backgroundCallNative: "システム音声",
backgroundCallInterrupted: "システムがマイク収録を一時停止または終了しました。ページに戻り権限を確認し、必要なら再接続してください。ミュートは自動解除されません。",
highQuality: "高品質な音声",
opusAudio: "低遅延 Opus 転送",
secureJoin: "安全に参加",
@@ -0,0 +1,77 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { createCallMediaSession } from "./call-media-session.js";
function fixture(t: TestContext, unsupported = false) {
const original = Object.getOwnPropertyDescriptor(globalThis, "MediaMetadata");
Object.defineProperty(globalThis, "MediaMetadata", { configurable: true, value: class {
title: string;
constructor(init: { title: string }) { this.title = init.title; }
} });
t.after(() => {
if (original) Object.defineProperty(globalThis, "MediaMetadata", original);
else Reflect.deleteProperty(globalThis, "MediaMetadata");
});
const handlers = new Map<string, (() => void) | null>();
const events: string[] = [];
const session = {
metadata: null as MediaMetadata | null, playbackState: "none" as MediaSessionPlaybackState,
setActionHandler(action: string, callback: (() => void) | null) {
if (unsupported && action === "togglemicrophone") throw new Error("Not supported");
handlers.set(action, callback);
},
setMicrophoneActive(active: boolean) { events.push(`mic:${active}`); },
};
const audioSession = { type: "auto" };
const controller = createCallMediaSession({ resume: () => events.push("play"), pause: () => events.push("pause"),
toggleMicrophone: () => events.push("toggle"), hangup: () => events.push("hangup") }, { mediaSession: session as unknown as MediaSession, audioSession });
t.after(() => controller.dispose());
const sync = (active = true, muted = false) => controller.sync({ active, muted, outputMuted: false, title: "Test room" });
return { controller, handlers, events, session, audioSession, sync };
}
test("call media controls are opt-in, reflect mute, and restore OS state on release", t => {
const f = fixture(t);
f.sync(false);
assert.equal(f.handlers.size, 0);
f.sync();
assert.equal(f.audioSession.type, "play-and-record");
assert.equal(f.session.metadata?.title, "Test room");
f.handlers.get("play")!();
f.handlers.get("pause")!();
f.handlers.get("togglemicrophone")!();
f.sync(true, true);
assert.ok(f.events.includes("mic:false"));
f.sync(false);
assert.equal(f.audioSession.type, "auto");
assert.equal(f.session.metadata, null);
assert.equal(f.session.playbackState, "none");
assert.ok([...f.handlers.values()].every(value => value === null));
});
test("a queued OS action cannot affect a disconnected or replacement call", t => {
const f = fixture(t);
f.sync();
const stale = f.handlers.get("togglemicrophone")!;
f.sync(false);
f.sync();
stale();
assert.ok(!f.events.includes("toggle"));
f.handlers.get("togglemicrophone")!();
assert.equal(f.events.filter(e => e === "toggle").length, 1);
});
test("partial API support leaves the other call controls functional", t => {
const f = fixture(t, true);
assert.doesNotThrow(() => f.sync());
f.handlers.get("hangup")!();
assert.ok(f.events.includes("hangup"));
assert.equal(f.handlers.has("togglemicrophone"), false);
assert.doesNotThrow(() => f.controller.dispose());
});
test("missing system APIs never prevent calling", () => {
const controller = createCallMediaSession({ resume() {}, pause() {}, toggleMicrophone() {}, hangup() {} }, {});
assert.doesNotThrow(() => controller.sync({ active: true, muted: false, outputMuted: false, title: "Room" }));
assert.doesNotThrow(() => controller.dispose());
});
+75
View File
@@ -0,0 +1,75 @@
interface CallSnapshot { active: boolean; muted: boolean; outputMuted: boolean; title: string }
interface AudioSession { type: string }
type CallAction = MediaSessionAction | "hangup" | "togglemicrophone";
type CallNavigator = Pick<Navigator, "mediaSession"> & { audioSession?: AudioSession };
interface CallActions {
resume(): void;
pause(): void;
toggleMicrophone(): void;
hangup(): void;
}
/** Optional OS integration, never a keepalive or permission to restart capture. */
export function createCallMediaSession(actions: CallActions, target: Partial<CallNavigator> = navigator) {
let active = false;
let generation = 0;
let metadata: MediaMetadata | null = null;
let oldMetadata: MediaMetadata | null = null;
let oldPlayback: MediaSessionPlaybackState = "none";
let oldAudioType: string | undefined;
const installed: CallAction[] = [];
const safely = (operation: () => void) => { try { operation(); } catch { /* platform may only implement part of the API */ } };
function stop(): void {
if (!active) return;
active = false;
generation++;
const session = target.mediaSession;
safely(() => (session as (MediaSession & { setMicrophoneActive?: (active: boolean) => void }) | undefined)?.setMicrophoneActive?.(false));
for (const action of installed.splice(0)) safely(() => session?.setActionHandler(action as MediaSessionAction, null));
if (session && session.metadata === metadata) {
safely(() => { session.metadata = oldMetadata; session.playbackState = oldPlayback; });
}
safely(() => {
if (target.audioSession?.type === "play-and-record" && oldAudioType !== undefined) target.audioSession.type = oldAudioType;
});
metadata = null;
}
return {
sync(snapshot: CallSnapshot): void {
if (!snapshot.active) { stop(); return; }
const session = target.mediaSession;
if (!active) {
active = true;
const currentGeneration = ++generation;
oldMetadata = session?.metadata ?? null;
oldPlayback = session?.playbackState ?? "none";
safely(() => {
oldAudioType = target.audioSession?.type;
if (target.audioSession) target.audioSession.type = "play-and-record";
});
if (session) {
const handlers: Partial<Record<CallAction, () => void>> = {
play: actions.resume, pause: actions.pause,
stop: actions.hangup, hangup: actions.hangup, togglemicrophone: actions.toggleMicrophone,
};
for (const [action, handler] of Object.entries(handlers)) safely(() => {
session.setActionHandler(action as MediaSessionAction, () => { if (active && generation === currentGeneration) handler(); });
installed.push(action as CallAction);
});
}
}
if (!session) return;
safely(() => {
if (!metadata || metadata.title !== snapshot.title) {
metadata = new MediaMetadata({ title: snapshot.title, artist: "WebSpeak" });
session.metadata = metadata;
}
session.playbackState = snapshot.outputMuted ? "paused" : "playing";
});
safely(() => (session as MediaSession & { setMicrophoneActive?: (active: boolean) => void }).setMicrophoneActive?.(!snapshot.muted));
},
dispose: stop,
};
}
+1
View File
@@ -145,6 +145,7 @@ export interface LocalPreferences {
theme?: "system" | "light" | "dark";
skinId?: string;
microphoneMuted?: boolean;
backgroundCallEnabled?: boolean;
noiseSuppressionEnabled?: boolean;
noiseSuppressionLevel?: "off" | "standard" | "strong";
voxThreshold?: number;
+9 -1
View File
@@ -1048,6 +1048,10 @@ const {
serverEvents,
pokeNotifications,
microphoneMuted,
backgroundCallEnabled,
backgroundCallActive,
backgroundCallInterrupted,
setBackgroundCallEnabled,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
@@ -1302,8 +1306,12 @@ function reconnectMobile(): void {
reconnectNow();
}
const { toggleMicrophone, stopWhisperTalk } = audioControls;
const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive };
const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive, backgroundCallActive };
const audioSettingsState = {
backgroundCallEnabled,
backgroundCallActive,
backgroundCallInterrupted,
setBackgroundCallEnabled,
inputDevices,
outputDevices,
selectedInputDeviceId,
+1 -1
View File
@@ -1,4 +1,4 @@
export type AccompanimentErrorCode = "" | "unsupported" | "needsWebRtc" | "noAudio" | "permission" | "audio";
export type AccompanimentErrorCode = "" | "unsupported" | "needsWebRtc" | "noAudio" | "permission" | "audio" | "backgroundMode";
interface AccompanimentTarget {
setAccompaniment(stream: MediaStream | null): void;
+28
View File
@@ -0,0 +1,28 @@
import type { MicrophoneCapture } from "./microphone-capture.js";
/** Native browser processing only: no RNNoise, PCM worklet, analyser or gain graph. */
export function createNativeMicrophoneCapture(stream: MediaStream): MicrophoneCapture {
const track = stream.getAudioTracks()[0];
if (!track || track.readyState !== "live") throw new DOMException("No live microphone", "NotReadableError");
const settings = track.getSettings();
let disposed = false;
return {
processedStream: stream,
processing: {
echoCancellation: typeof settings.echoCancellation === "boolean" ? settings.echoCancellation : null,
noiseSuppression: typeof settings.noiseSuppression === "boolean" ? settings.noiseSuppression : null,
autoGainControl: typeof settings.autoGainControl === "boolean" ? settings.autoGainControl : null,
rnnoise: false,
},
activate() {},
setVolume() {},
stopCapture() {},
dispose() {
if (disposed) return;
disposed = true;
for (const item of stream.getTracks()) {
try { item.stop(); } catch { /* release the other tracks too */ }
}
},
};
}
+17
View File
@@ -5,6 +5,23 @@ export interface WebRtcInput {
dispose(): void;
}
/** The capture owner releases this stream; no Web Audio graph or clone owns it. */
export function createNativeWebRtcInput(stream: MediaStream, volume: number): WebRtcInput {
const track = stream.getAudioTracks()[0];
if (!track || track.readyState !== "live") throw new Error("No live native microphone track");
let disposed = false;
const setVolume = (value: number) => { if (!disposed) track.enabled = value > 0; };
setVolume(volume);
return {
stream,
setVolume,
setAccompaniment(source) {
if (source) throw new DOMException("Native call input does not mix accompaniment", "NotSupportedError");
},
dispose() { disposed = true; },
};
}
// Own only the mixing nodes and their output. Capture controllers own the input
// streams. Keep the sender track alive when accompaniment starts/stops/changes.
export function createWebRtcInput(context: AudioContext, microphone: MediaStream, volume: number): WebRtcInput {
+4 -1
View File
@@ -58,7 +58,9 @@ export function createWebRtcPlayback(options: WebRtcPlaybackOptions) {
const task = (async () => {
const context = options.context();
if (context?.state === "suspended") {
try { await context.resume(); } catch { /* a real user gesture may still be required */ }
// Capture may never resume while locked. Native remote playback must
// not wait on that independent graph, including on a retry gesture.
try { void context.resume().catch(() => undefined); } catch { /* retry on a user gesture */ }
}
if (!isCurrent(record)) return;
try {
@@ -108,6 +110,7 @@ export function createWebRtcPlayback(options: WebRtcPlaybackOptions) {
return {
attach, stop,
resume(): void { if (current) void play(current); },
get output(): SinkAudioElement | null { return current?.output ?? null; },
setVolume(value: number): void { if (current) current.output.volume = value; },
};
+6 -4
View File
@@ -1,11 +1,11 @@
import { isSessionDescription, type WebRtcClientMessage } from "../../../src/shared/webrtc.js";
import { createWebRtcInput, type WebRtcInput } from "./webrtc-input.js";
import { createNativeWebRtcInput, createWebRtcInput, type WebRtcInput } from "./webrtc-input.js";
import { createMicrophoneMeter, type MicrophoneMeter } from "./microphone-meter.js";
import { createWebRtcPlayback, type WebRtcPlaybackOptions } from "./webrtc-playback.js";
import { addOpusFmtpParameters } from "../../../src/shared/opus-sdp.js";
interface Microphone {
context: AudioContext;
context: AudioContext | null;
stream: MediaStream;
processedStream: MediaStream;
}
@@ -134,7 +134,8 @@ export function createWebRtcTransport(options: TransportOptions) {
const peer = new RTCPeerConnection({ iceServers: stunServer ? [{ urls: stunServer }] : [] });
record.peer = peer;
track.enabled = !options.muted();
const input = createWebRtcInput(context, processedStream, options.muted() ? 0 : options.inputVolume());
const volume = options.muted() ? 0 : options.inputVolume();
const input = context ? createWebRtcInput(context, processedStream, volume) : createNativeWebRtcInput(stream, volume);
record.input = input;
peer.addTrack(input.stream.getAudioTracks()[0]!, input.stream);
peer.ontrack = event => {
@@ -142,7 +143,7 @@ export function createWebRtcTransport(options: TransportOptions) {
try { playback.attach(event.streams[0] ?? new MediaStream([event.track])); }
catch { void fail(record, "WEBRTC_PLAYBACK_FAILED"); }
};
record.meter = createMicrophoneMeter(context, stream, rms => options.onLevel(rms, track));
if (context) record.meter = createMicrophoneMeter(context, stream, rms => options.onLevel(rms, track));
peer.onconnectionstatechange = () => {
options.onConnectionState?.(peer.connectionState);
if (isCurrent(record) && peer.connectionState === "failed") void fail(record, "WEBRTC_CONNECTION_FAILED");
@@ -196,5 +197,6 @@ export function createWebRtcTransport(options: TransportOptions) {
get active(): boolean { return current?.active ?? false; },
get output() { return playback.output; },
setOutputVolume: playback.setVolume,
resumePlayback: playback.resume,
};
}
+163 -1
View File
@@ -156,6 +156,7 @@ let useWebClientChat;
let useWebClientChannels;
let webClientTranslations;
let voice;
let voiceScope;
const savedGlobals = new Map();
function replaceGlobal(name, value) {
if (!savedGlobals.has(name)) savedGlobals.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
@@ -224,12 +225,14 @@ beforeEach(() => {
getUserMedia: async () => microphoneStream(),
enumerateDevices: async () => [],
} });
voice = useVoiceWebSocket();
voiceScope = effectScope();
voice = voiceScope.run(() => useVoiceWebSocket());
});
afterEach(() => {
voice?.stopMicrophoneTest();
voice?.disconnect();
voiceScope?.stop();
for (const timer of browserTimers) clearTimeout(timer);
browserTimers.clear();
});
@@ -733,6 +736,165 @@ async function connectWebRtc() {
return { socket, peer: TestPeer.instances.at(-1) };
}
test("experimental calls send the native mic without creating a Web Audio graph and preserve mute", async () => {
const stream = microphoneStream();
navigator.mediaDevices.getUserMedia = async () => stream;
assert.equal(voice.backgroundCallEnabled.value, false);
voice.setBackgroundCallEnabled(true);
const { peer, socket } = await connectWebRtc();
assert.equal(voice.backgroundCallActive.value, true);
assert.equal(peer.sender.track, stream.track);
assert.equal(AudioContextStub.instances.length, 0);
assert.equal(voice.microphoneProcessing.rnnoise, false);
voice.setMicrophoneMuted(true);
assert.equal(stream.track.enabled, false);
assert.ok(socket.messages.some(m => m.type === "setMicrophoneMuted" && m.payload.muted));
voice.setMicrophoneMuted(false);
assert.equal(stream.track.enabled, true);
await assert.rejects(voice.startAccompaniment(), /unavailable/);
assert.equal(voice.accompanimentErrorCode.value, "backgroundMode");
voice.disconnect();
assert.equal(stream.track.readyState, "ended");
assert.equal(peer.connectionState, "closed");
assert.equal(voice.backgroundCallActive.value, false);
});
test("changing the experiment applies only to the next connection", async () => {
await connectWebRtc();
voice.setBackgroundCallEnabled(true);
assert.equal(voice.backgroundCallActive.value, false);
const { peer } = await connectWebRtc();
const track = peer.sender.track;
voice.setBackgroundCallEnabled(false);
assert.equal(voice.backgroundCallActive.value, true);
assert.equal(track.readyState, "live");
await connectWebRtc();
assert.equal(voice.backgroundCallActive.value, false);
});
test("native input at zero gain stays silent and scope disposal releases the microphone", async () => {
voice.setBackgroundCallEnabled(true);
voice.setInputVolume(0);
const { peer } = await connectWebRtc();
assert.equal(peer.sender.track.enabled, false);
voice.setMicrophoneMuted(true);
voice.setMicrophoneMuted(false);
assert.equal(peer.sender.track.enabled, false, "unmute must preserve a zero input level");
voiceScope.stop();
assert.equal(peer.sender.track.readyState, "ended");
assert.equal(peer.connectionState, "closed");
});
test("native system microphone interruption is reported without changing user mute", async () => {
voice.setBackgroundCallEnabled(true);
const { peer } = await connectWebRtc();
const track = peer.sender.track;
track.muted = true;
track.dispatchEvent(new Event("mute"));
assert.equal(voice.backgroundCallInterrupted.value, true);
voice.setMicrophoneMuted(true);
track.muted = false;
track.dispatchEvent(new Event("unmute"));
assert.equal(voice.backgroundCallInterrupted.value, false);
assert.equal(voice.microphoneMuted.value, true);
assert.equal(track.enabled, false);
});
test("an experimental connection replaces a processing preview still waiting on permission", async () => {
const permission = deferred();
const preview = microphoneStream();
const native = microphoneStream();
let requests = 0;
navigator.mediaDevices.getUserMedia = () => ++requests === 1 ? permission.promise : Promise.resolve(native);
const preparation = voice.prepareInputDevices();
voice.setBackgroundCallEnabled(true);
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
permission.resolve(preview);
await preparation.catch(() => {});
await nextTurn();
assert.equal(preview.track.readyState, "ended");
assert.equal(TestPeer.instances.at(-1).sender.track, native.track);
assert.equal(voice.backgroundCallActive.value, true);
});
test("native mode falls back to processed PCM after WebRTC failure", async () => {
const streams = [];
navigator.mediaDevices.getUserMedia = async () => { const stream = microphoneStream(); streams.push(stream); return stream; };
voice.setBackgroundCallEnabled(true);
const { peer } = await connectWebRtc();
peer.connectionState = "failed";
peer.onconnectionstatechange();
await nextTurn();
assert.equal(voice.backgroundCallActive.value, false);
assert.equal(streams[0].track.readyState, "ended");
assert.equal(streams.at(-1).track.readyState, "live");
assert.ok(AudioContextStub.processors.length > 0);
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FALLBACK");
});
test("a gateway without WebRTC keeps compatibility capture with the experiment enabled", async () => {
voice.setBackgroundCallEnabled(true);
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1 });
await nextTurn();
assert.equal(voice.backgroundCallActive.value, false);
assert.ok(AudioContextStub.processors.length > 0);
assert.equal(TestPeer.instances.length, 0);
});
test("disconnect retires a pending native microphone permission request", async () => {
const pending = deferred();
navigator.mediaDevices.getUserMedia = () => pending.promise;
voice.setBackgroundCallEnabled(true);
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
await nextTurn();
voice.disconnect();
const stream = microphoneStream();
pending.resolve(stream);
await nextTurn();
assert.equal(stream.track.readyState, "ended");
assert.equal(TestPeer.instances.length, 0);
assert.equal(voice.backgroundCallActive.value, false);
});
test("native remote playback does not wait for a suspended capture context to resume", async () => {
const { peer } = await connectWebRtc();
const context = AudioContextStub.instances.at(-1);
context.state = "suspended";
context.resume = () => new Promise(() => {});
let plays = 0;
const output = new TestAudioElement();
output.play = async () => { plays++; };
document.createElement = () => output;
peer.ontrack({ streams: [microphoneStream()] });
await nextTurn();
assert.equal(plays, 1);
});
test("OS playback resume and page restoration never unmute a native call", async () => {
const handlers = new Map();
navigator.mediaSession = { metadata: null, playbackState: "none", setActionHandler: (action, handler) => handlers.set(action, handler) };
navigator.audioSession = { type: "auto" };
voice.setBackgroundCallEnabled(true);
const { peer } = await connectWebRtc();
handlers.get("pause")();
await nextTurn();
assert.equal(peer.sender.track.enabled, false);
handlers.get("play")();
document.visibilityState = "visible";
document.dispatchEvent(new Event("visibilitychange"));
await nextTurn();
assert.equal(voice.microphoneMuted.value, true);
assert.equal(peer.sender.track.enabled, false);
handlers.get("togglemicrophone")();
assert.equal(peer.sender.track.enabled, true);
handlers.get("hangup")();
assert.equal(peer.connectionState, "closed");
assert.equal(navigator.audioSession.type, "auto");
});
function enableMicrophoneMeter(t) {
const analysers = [];
const intervals = [];