fix: make WebRTC playback reliable

This commit is contained in:
illusia committed 2026-09-03 14:28:47 +08:00
1 parent 61f66ab319
commit d0a2e9edc0
2 files changed
+61 -21

No files matched your search

+6 -2
View File
@@ -140,7 +140,6 @@ export class WebRtcAudioSession {
pushTeamSpeakVoice(data: TSVoiceData): void { pushTeamSpeakVoice(data: TSVoiceData): void {
if (this.closed || data.codec !== 4) return; if (this.closed || data.codec !== 4) return;
this.activeSpeakerIds.add(data.clientId);
let decoder = this.decoderByClient.get(data.clientId); let decoder = this.decoderByClient.get(data.clientId);
if (!decoder) { if (!decoder) {
try { try {
@@ -155,7 +154,12 @@ export class WebRtcAudioSession {
} }
try { try {
const pcm = decoder.decode(data.data); const pcm = decoder.decode(data.data);
if (pcm.length >= AUDIO_FRAME_BYTES) this.pendingFrames.set(data.clientId, pcm.subarray(0, AUDIO_FRAME_BYTES)); // Only advertise speaking after a valid TeamSpeak Opus frame has been
// decoded. Otherwise the UI can show activity while the mixer has no
// audio to send, which is especially confusing on the WebRTC path.
if (pcm.length < AUDIO_FRAME_BYTES) return;
this.pendingFrames.set(data.clientId, pcm.subarray(0, AUDIO_FRAME_BYTES));
this.activeSpeakerIds.add(data.clientId);
} catch { } catch {
// A malformed or codec-transition packet is discarded without touching // A malformed or codec-transition packet is discarded without touching
// the peer connection. The next valid Opus frame can recover the stream. // the peer connection. The next valid Opus frame can recover the stream.
+55 -19
View File
@@ -44,6 +44,10 @@ type SinkAudioContext = AudioContext & {
setSinkId?: (sinkId: string) => Promise<void>; setSinkId?: (sinkId: string) => Promise<void>;
}; };
type SinkAudioElement = HTMLAudioElement & {
setSinkId?: (sinkId: string) => Promise<void>;
};
export interface ChannelInfo { export interface ChannelInfo {
id: string; id: string;
parentID: string; parentID: string;
@@ -83,8 +87,7 @@ export function useVoiceWebSocket() {
let connectionSequence = 0; let connectionSequence = 0;
let lastConnection: { target: string; channel: string; nickname: string; serverPassword: string; identity?: string; rememberIdentity: boolean } | null = null; let lastConnection: { target: string; channel: string; nickname: string; serverPassword: string; identity?: string; rememberIdentity: boolean } | null = null;
let webrtcPeer: RTCPeerConnection | null = null; let webrtcPeer: RTCPeerConnection | null = null;
let webrtcOutputSource: MediaStreamAudioSourceNode | null = null; let webrtcOutputElement: SinkAudioElement | null = null;
let webrtcOutputGain: GainNode | null = null;
let webrtcNegotiationPromise: Promise<void> | null = null; let webrtcNegotiationPromise: Promise<void> | null = null;
let webrtcFallbackStarted = false; let webrtcFallbackStarted = false;
const webrtcActive = ref(false); const webrtcActive = ref(false);
@@ -255,7 +258,8 @@ export function useVoiceWebSocket() {
audioCtx.addEventListener("statechange", () => { audioCtx.addEventListener("statechange", () => {
if (audioCtx) audioContextState.value = audioCtx.state; if (audioCtx) audioContextState.value = audioCtx.state;
}); });
outputDeviceSupported.value = typeof audioCtx.setSinkId === "function"; outputDeviceSupported.value = typeof audioCtx.setSinkId === "function"
|| typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function";
if (selectedOutputDeviceId.value && outputDeviceSupported.value) { if (selectedOutputDeviceId.value && outputDeviceSupported.value) {
void setAudioSink(audioCtx, selectedOutputDeviceId.value).catch(() => undefined); void setAudioSink(audioCtx, selectedOutputDeviceId.value).catch(() => undefined);
} }
@@ -268,13 +272,15 @@ export function useVoiceWebSocket() {
} }
async function setAudioSink(ctx: SinkAudioContext, deviceId: string): Promise<void> { async function setAudioSink(ctx: SinkAudioContext, deviceId: string): Promise<void> {
if (!ctx.setSinkId) { const mediaSinkSupported = typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function";
if (!ctx.setSinkId && !mediaSinkSupported) {
outputDeviceSupported.value = false; outputDeviceSupported.value = false;
if (deviceId) throw new Error("当前浏览器不支持扬声器设备选择,将使用默认输出设备"); if (deviceId) throw new Error("当前浏览器不支持扬声器设备选择,将使用默认输出设备");
return; return;
} }
outputDeviceSupported.value = true; outputDeviceSupported.value = true;
await ctx.setSinkId(deviceId || "default"); if (ctx.setSinkId) await ctx.setSinkId(deviceId || "default");
if (webrtcOutputElement?.setSinkId) await webrtcOutputElement.setSinkId(deviceId || "default");
} }
function checkSupport(): string | null { function checkSupport(): string | null {
@@ -486,15 +492,43 @@ export function useVoiceWebSocket() {
peer.addTrack(track, micStream); peer.addTrack(track, micStream);
peer.ontrack = (event) => { peer.ontrack = (event) => {
const stream = event.streams[0] ?? new MediaStream([event.track]); const stream = event.streams[0] ?? new MediaStream([event.track]);
const ctx = getAudioCtx(); // Use the browser's native WebRTC media output. Routing the remote
if (ctx.state === "suspended") void ctx.resume(); // track through AudioContext made playback depend on autoplay policy:
webrtcOutputSource?.disconnect(); // the control channel could report speaking while a suspended context
webrtcOutputGain?.disconnect(); // silently discarded the actual audio. A hidden autoplaying media
webrtcOutputSource = ctx.createMediaStreamSource(stream); // element keeps WebRTC's decoder and jitter buffer on the native path.
webrtcOutputGain = ctx.createGain(); webrtcOutputElement?.pause();
webrtcOutputGain.gain.value = outputVolume.value; if (webrtcOutputElement) {
webrtcOutputSource.connect(webrtcOutputGain); webrtcOutputElement.srcObject = null;
webrtcOutputGain.connect(ctx.destination); webrtcOutputElement.remove();
}
const output = document.createElement("audio") as SinkAudioElement;
output.autoplay = true;
output.setAttribute("playsinline", "");
output.volume = outputVolume.value;
output.setAttribute("aria-hidden", "true");
output.tabIndex = -1;
output.style.position = "fixed";
output.style.width = "1px";
output.style.height = "1px";
output.style.opacity = "0";
output.style.pointerEvents = "none";
output.srcObject = stream;
document.body.append(output);
webrtcOutputElement = output;
if (selectedOutputDeviceId.value && output.setSinkId) {
void output.setSinkId(selectedOutputDeviceId.value).catch(() => undefined);
}
void output.play().catch(() => {
// A browser may require a later user gesture to start media playback.
// Retry on the next pointer interaction without interrupting the
// active voice connection.
const retry = () => {
if (webrtcOutputElement !== output) return;
void output.play().catch(() => undefined);
};
window.addEventListener("pointerdown", retry, { once: true, passive: true });
});
}; };
peer.onconnectionstatechange = () => { peer.onconnectionstatechange = () => {
if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket); if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket);
@@ -571,10 +605,12 @@ export function useVoiceWebSocket() {
webrtcPeer = null; webrtcPeer = null;
webrtcActive.value = false; webrtcActive.value = false;
webrtcNegotiationPromise = null; webrtcNegotiationPromise = null;
webrtcOutputSource?.disconnect(); webrtcOutputElement?.pause();
webrtcOutputGain?.disconnect(); if (webrtcOutputElement) {
webrtcOutputSource = null; webrtcOutputElement.srcObject = null;
webrtcOutputGain = null; webrtcOutputElement.remove();
}
webrtcOutputElement = null;
if (peer) void peer.close(); if (peer) void peer.close();
} }
@@ -1281,7 +1317,7 @@ export function useVoiceWebSocket() {
function setOutputVolume(volume: number): void { function setOutputVolume(volume: number): void {
outputVolume.value = Math.max(0, Math.min(1, volume)); outputVolume.value = Math.max(0, Math.min(1, volume));
for (const [clientId, gain] of remoteGains) gain.gain.value = (volumes[clientId] ?? 1) * outputVolume.value; for (const [clientId, gain] of remoteGains) gain.gain.value = (volumes[clientId] ?? 1) * outputVolume.value;
if (webrtcOutputGain) webrtcOutputGain.gain.value = outputVolume.value; if (webrtcOutputElement) webrtcOutputElement.volume = outputVolume.value;
void saveAudioPreferences(); void saveAudioPreferences();
} }