mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
Initial release
This commit is contained in:
commit
8d9b8d5627
27 files changed
+8140
No files matched your search
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#006a64" />
|
||||
<meta name="description" content="WebSpeak — TeamSpeak browser voice workspace" />
|
||||
<title>WebSpeak · TeamSpeak Web Client</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+1660
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "webspeak-webclient-frontend",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"pinia": "^3.0.2",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.3",
|
||||
"typescript": "~5.7.0",
|
||||
"vite": "^6.3.0",
|
||||
"vue-tsc": "^2.2.8"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
<template>
|
||||
<router-view />
|
||||
</template>
|
||||
@@ -0,0 +1,81 @@
|
||||
<template>
|
||||
<svg
|
||||
class="ui-icon"
|
||||
:width="size"
|
||||
:height="size"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.8"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path v-if="name === 'home'" d="m3 10 9-7 9 7v10a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" />
|
||||
<path v-else-if="name === 'activity'" d="M3 12h4l2.2-7 4.1 14 2.2-7H21" />
|
||||
<template v-else-if="name === 'server'">
|
||||
<rect x="4" y="3" width="16" height="7" rx="1.5" />
|
||||
<rect x="4" y="14" width="16" height="7" rx="1.5" />
|
||||
<path d="M8 6.5h.01M8 17.5h.01M11 6.5h5M11 17.5h5" />
|
||||
</template>
|
||||
<template v-else-if="name === 'compass'">
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="m15.5 8.5-2.2 4.8-4.8 2.2 2.2-4.8z" />
|
||||
</template>
|
||||
<template v-else-if="name === 'download'">
|
||||
<path d="M12 3v12m0 0 4-4m-4 4-4-4M4 19v2h16v-2" />
|
||||
</template>
|
||||
<template v-else-if="name === 'settings'">
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
<path d="M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-1.42 1.42-.06-.06a1.7 1.7 0 0 0-1.88-.34 1.7 1.7 0 0 0-1.03 1.56V20h-2v-.09a1.7 1.7 0 0 0-1.03-1.56 1.7 1.7 0 0 0-1.88.34l-.06.06-1.42-1.42.06-.06A1.7 1.7 0 0 0 9.4 15a1.7 1.7 0 0 0-1.56-1.03H7v-2h.84A1.7 1.7 0 0 0 9.4 11a1.7 1.7 0 0 0-.34-1.88L9 9.06l1.42-1.42.06.06a1.7 1.7 0 0 0 1.88.34A1.7 1.7 0 0 0 13.39 6.5V6h2v.5a1.7 1.7 0 0 0 1.03 1.54 1.7 1.7 0 0 0 1.88-.34l.06-.06 1.42 1.42-.06.06A1.7 1.7 0 0 0 19.4 11a1.7 1.7 0 0 0 1.56 1.03H21v2h-.04A1.7 1.7 0 0 0 19.4 15Z" />
|
||||
</template>
|
||||
<path v-else-if="name === 'mic'" d="M12 14a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v5a3 3 0 0 0 3 3Zm-7-3a7 7 0 0 0 14 0m-7 7v3m-3 0h6" />
|
||||
<path v-else-if="name === 'mic-off'" d="m4 4 16 16M10 6v5a2 2 0 0 0 3.2 1.6M14 6V5a2 2 0 0 0-3.7-1M5 11a7 7 0 0 0 10.6 6m3.4-6a7 7 0 0 0-.5-2.5M12 18v3m-3 0h6" />
|
||||
<path v-else-if="name === 'headset'" d="M4 14v-2a8 8 0 0 1 16 0v2M4 14h3v5H5a1 1 0 0 1-1-1zm16 0h-3v5h2a1 1 0 0 0 1-1z" />
|
||||
<path v-else-if="name === 'volume'" d="M4 10v4h3l4 3V7l-4 3zm10.5-2.5a6 6 0 0 1 0 9m2-11a9 9 0 0 1 0 13" />
|
||||
<path v-else-if="name === 'volume-off'" d="m4 4 16 16M4 10v4h3l4 3V7l-4 3z" />
|
||||
<template v-else-if="name === 'search'">
|
||||
<circle cx="10.8" cy="10.8" r="6.8" />
|
||||
<path d="m16 16 4.5 4.5" />
|
||||
</template>
|
||||
<path v-else-if="name === 'bell'" d="M18 9a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M10 21h4" />
|
||||
<path v-else-if="name === 'help'" d="M9.3 9a3 3 0 1 1 4.9 2.3c-1.3 1-2.2 1.5-2.2 3m0 3h.01M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Z" />
|
||||
<template v-else-if="name === 'plus'">
|
||||
<path d="M12 5v14M5 12h14" />
|
||||
</template>
|
||||
<path v-else-if="name === 'chevron-down'" d="m6 9 6 6 6-6" />
|
||||
<path v-else-if="name === 'chevron-right'" d="m9 6 6 6-6 6" />
|
||||
<path v-else-if="name === 'hash'" d="M9 3 7 21M17 3l-2 18M4 9h16M3 15h16" />
|
||||
<path v-else-if="name === 'send'" d="m21 3-7.4 18-3.6-7-7-3.6zM21 3 10 14" />
|
||||
<template v-else-if="name === 'smile'">
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M8 14s1.5 2 4 2 4-2 4-2M9 9h.01M15 9h.01" />
|
||||
</template>
|
||||
<path v-else-if="name === 'paperclip'" d="m20 11-7.5 7.5a5 5 0 0 1-7-7L13 4a3.5 3.5 0 0 1 5 5l-7.5 7.5a2 2 0 0 1-3-3L14 7" />
|
||||
<path v-else-if="name === 'share'" d="M4 12v7a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7M16 6l-4-4-4 4m4-4v13" />
|
||||
<path v-else-if="name === 'copy'" d="M8 8V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-3M6 8h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2Z" />
|
||||
<path v-else-if="name === 'close'" d="m6 6 12 12M18 6 6 18" />
|
||||
<path v-else-if="name === 'more'" d="M5 12h.01M12 12h.01M19 12h.01" stroke-width="3" />
|
||||
<path v-else-if="name === 'refresh'" d="M20 11a8 8 0 0 0-14-4L4 9m0-4v4h4M4 13a8 8 0 0 0 14 4l2-2m0 4v-4h-4" />
|
||||
<path v-else-if="name === 'lock'" d="M6 10h12v10H6zM8 10V7a4 4 0 0 1 8 0v3" />
|
||||
<path v-else-if="name === 'users'" d="M16 21v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2m6-10a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm6-7a4 4 0 0 1 0 7m2 5h1a4 4 0 0 1 4 4v1" />
|
||||
<path v-else-if="name === 'message'" d="M20 11.5a7.5 7.5 0 0 1-8 7.5 9.4 9.4 0 0 1-3-.5L4 20l1.5-3.6A7.2 7.2 0 0 1 4 11.5 7.5 7.5 0 0 1 12 4a7.5 7.5 0 0 1 8 7.5Z" />
|
||||
<path v-else-if="name === 'door'" d="M10 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5m5 14 5-5-5-5m5 5H9" />
|
||||
<path v-else-if="name === 'waveform'" d="M3 12h2l2-6 3 12 3-9 2 6h6" />
|
||||
<path v-else-if="name === 'shield'" d="M12 21s8-3.5 8-10V5l-8-3-8 3v6c0 6.5 8 10 8 10Z" />
|
||||
<path v-else-if="name === 'monitor'" d="M4 4h16v12H4zM8 20h8M12 16v4" />
|
||||
<path v-else-if="name === 'check'" d="m5 12 4 4L19 6" />
|
||||
<circle v-else cx="12" cy="12" r="8" />
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
withDefaults(defineProps<{ name: string; size?: number }>(), { size: 18 });
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.ui-icon {
|
||||
display: block;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,521 @@
|
||||
import { reactive, ref } from "vue";
|
||||
|
||||
export interface VoiceState {
|
||||
connected: boolean;
|
||||
connecting: boolean;
|
||||
tsClientId: number;
|
||||
error: string;
|
||||
}
|
||||
|
||||
export interface ChannelMember {
|
||||
id: number;
|
||||
nickname: string;
|
||||
isSelf?: boolean;
|
||||
}
|
||||
|
||||
export interface AudioInputDevice {
|
||||
deviceId: string;
|
||||
label: string;
|
||||
groupId: string;
|
||||
}
|
||||
|
||||
export interface ChannelInfo {
|
||||
id: string;
|
||||
parentID: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
members?: { id: number; nickname: string }[];
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string;
|
||||
invokerName: string;
|
||||
message: string;
|
||||
timestamp: number;
|
||||
isSelf?: boolean;
|
||||
}
|
||||
|
||||
export function useVoiceWebSocket() {
|
||||
const ws = ref<WebSocket | null>(null);
|
||||
const state = reactive<VoiceState>({ connected: false, connecting: false, tsClientId: 0, error: "" });
|
||||
const members = reactive<ChannelMember[]>([]);
|
||||
const channels = reactive<ChannelInfo[]>([]);
|
||||
const chatMessages = reactive<ChatMessage[]>([]);
|
||||
|
||||
// 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 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<AudioInputDevice[]>([]);
|
||||
const selectedInputDeviceId = ref(typeof localStorage !== "undefined" ? localStorage.getItem("webspeak:input-device") ?? "" : "");
|
||||
const micLevel = ref(0);
|
||||
const microphoneTestActive = ref(false);
|
||||
let pttPressed = false;
|
||||
const micMode = ref<"vox" | "ptt">("vox");
|
||||
const inputVolume = ref(1);
|
||||
const outputVolume = ref(1);
|
||||
let voxHold = 0;
|
||||
const VOX_HOLD = 15;
|
||||
const VOX_THRESHOLD = 0.008;
|
||||
let convBuf = new Int16Array(1024);
|
||||
let accumBuf = new Int16Array(2048);
|
||||
let accumLen = 0;
|
||||
|
||||
// Playback is kept per client so frames from multiple speakers cannot
|
||||
// interleave into one decoder or one scheduling queue.
|
||||
const remoteDecoders = new Map<number, AudioDecoder>();
|
||||
const remotePlayTimes = new Map<number, number>();
|
||||
const remoteGains = new Map<number, GainNode>();
|
||||
const remoteDecodeTimestamps = new Map<number, number>();
|
||||
const volumes = reactive<Record<number, number>>({});
|
||||
const speakingIds = reactive(new Set<number>());
|
||||
const speakingTimers = new Map<number, ReturnType<typeof setTimeout>>();
|
||||
const SPEAKING_HOLD_MS = 360;
|
||||
|
||||
function markSpeaking(clientId: number): void {
|
||||
if (!clientId) return;
|
||||
speakingIds.add(clientId);
|
||||
const previous = speakingTimers.get(clientId);
|
||||
if (previous) clearTimeout(previous);
|
||||
const timer = setTimeout(() => {
|
||||
speakingIds.delete(clientId);
|
||||
speakingTimers.delete(clientId);
|
||||
}, SPEAKING_HOLD_MS);
|
||||
speakingTimers.set(clientId, timer);
|
||||
}
|
||||
|
||||
function clearSpeaking(clientId: number): void {
|
||||
const timer = speakingTimers.get(clientId);
|
||||
if (timer) clearTimeout(timer);
|
||||
speakingTimers.delete(clientId);
|
||||
speakingIds.delete(clientId);
|
||||
}
|
||||
|
||||
function clearSpeakingState(): void {
|
||||
for (const timer of speakingTimers.values()) clearTimeout(timer);
|
||||
speakingTimers.clear();
|
||||
speakingIds.clear();
|
||||
}
|
||||
|
||||
function getAudioCtx(): AudioContext {
|
||||
if (!audioCtx) audioCtx = new AudioContext({ sampleRate: 48000 });
|
||||
return audioCtx;
|
||||
}
|
||||
|
||||
function checkSupport(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
if (!window.isSecureContext) return "语音功能需要 HTTPS 安全连接";
|
||||
if (!navigator.mediaDevices?.getUserMedia) return "当前浏览器不支持麦克风访问";
|
||||
if (typeof AudioDecoder === "undefined") return "当前浏览器不支持音频解码,请使用最新版 Chrome 或 Edge";
|
||||
return null;
|
||||
}
|
||||
|
||||
function microphoneConstraints(): MediaTrackConstraints {
|
||||
const constraints: MediaTrackConstraints = {
|
||||
sampleRate: { ideal: 48000 },
|
||||
channelCount: { ideal: 1 },
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
};
|
||||
if (selectedInputDeviceId.value) constraints.deviceId = { exact: selectedInputDeviceId.value };
|
||||
return constraints;
|
||||
}
|
||||
|
||||
async function refreshInputDevices(): Promise<void> {
|
||||
if (!navigator.mediaDevices?.enumerateDevices) {
|
||||
inputDevices.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 }));
|
||||
inputDevices.splice(0, inputDevices.length, ...microphones);
|
||||
if (selectedInputDeviceId.value && !microphones.some((device) => device.deviceId === selectedInputDeviceId.value)) {
|
||||
selectedInputDeviceId.value = microphones[0]?.deviceId ?? "";
|
||||
localStorage.setItem("webspeak:input-device", selectedInputDeviceId.value);
|
||||
}
|
||||
}
|
||||
|
||||
async function startMicrophone(): Promise<void> {
|
||||
const ctx = getAudioCtx();
|
||||
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() });
|
||||
stopMicrophone(false);
|
||||
micStream = nextStream;
|
||||
|
||||
micSource = ctx.createMediaStreamSource(micStream);
|
||||
micGain = ctx.createGain();
|
||||
micGain.gain.value = inputVolume.value;
|
||||
scriptNode = ctx.createScriptProcessor(1024, 1, 1);
|
||||
silentGain = ctx.createGain();
|
||||
silentGain.gain.value = 0;
|
||||
|
||||
scriptNode.onaudioprocess = (event) => {
|
||||
const input = event.inputBuffer.getChannelData(0);
|
||||
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);
|
||||
if (!shouldSend) {
|
||||
accumLen = 0;
|
||||
return;
|
||||
}
|
||||
if (ws.value?.readyState === WebSocket.OPEN) markSpeaking(state.tsClientId);
|
||||
|
||||
if (convBuf.length < input.length) convBuf = new Int16Array(input.length);
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const sample = Math.max(-1, Math.min(1, input[i]));
|
||||
convBuf[i] = sample < 0 ? sample * 0x8000 : sample * 0x7fff;
|
||||
}
|
||||
|
||||
const need = accumLen + input.length;
|
||||
if (accumBuf.length < need) accumBuf = new Int16Array(Math.max(need, accumBuf.length * 2));
|
||||
accumBuf.set(convBuf.subarray(0, input.length), accumLen);
|
||||
accumLen = need;
|
||||
|
||||
let offset = 0;
|
||||
while (offset + 960 <= accumLen && ws.value?.readyState === WebSocket.OPEN) {
|
||||
ws.value.send(accumBuf.slice(offset, offset + 960).buffer);
|
||||
offset += 960;
|
||||
}
|
||||
accumLen -= offset;
|
||||
if (offset > 0) accumBuf.set(accumBuf.subarray(offset, offset + accumLen), 0);
|
||||
};
|
||||
|
||||
micSource.connect(micGain);
|
||||
micGain.connect(scriptNode);
|
||||
scriptNode.connect(silentGain);
|
||||
silentGain.connect(ctx.destination);
|
||||
await refreshInputDevices();
|
||||
}
|
||||
|
||||
function voxGate(samples: Float32Array): boolean {
|
||||
let sum = 0;
|
||||
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 (voxHold > 0) {
|
||||
voxHold--;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function stopMicrophone(closeContext = true): void {
|
||||
accumLen = 0;
|
||||
voxHold = 0;
|
||||
micLevel.value = 0;
|
||||
scriptNode?.disconnect();
|
||||
micGain?.disconnect();
|
||||
micSource?.disconnect();
|
||||
silentGain?.disconnect();
|
||||
scriptNode = null;
|
||||
micGain = null;
|
||||
micSource = null;
|
||||
silentGain = null;
|
||||
micStream?.getTracks().forEach((track) => track.stop());
|
||||
micStream = null;
|
||||
if (closeContext) {
|
||||
audioCtx?.close();
|
||||
audioCtx = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareInputDevices(): Promise<void> {
|
||||
if (!micStream) await startMicrophone();
|
||||
else await refreshInputDevices();
|
||||
}
|
||||
|
||||
async function setInputDevice(deviceId: string): Promise<void> {
|
||||
const previousDeviceId = selectedInputDeviceId.value;
|
||||
selectedInputDeviceId.value = deviceId;
|
||||
localStorage.setItem("webspeak:input-device", deviceId);
|
||||
try {
|
||||
if (micStream) await startMicrophone();
|
||||
await refreshInputDevices();
|
||||
} catch (error) {
|
||||
selectedInputDeviceId.value = previousDeviceId;
|
||||
localStorage.setItem("webspeak:input-device", previousDeviceId);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function startMicrophoneTest(): Promise<void> {
|
||||
await prepareInputDevices();
|
||||
microphoneTestActive.value = true;
|
||||
}
|
||||
|
||||
function stopMicrophoneTest(): void {
|
||||
microphoneTestActive.value = false;
|
||||
if (!state.connected) stopMicrophone();
|
||||
}
|
||||
|
||||
function playAudioFrame(clientId: number, opusData: Uint8Array): void {
|
||||
if (opusData.length < 3) return;
|
||||
let decoder = remoteDecoders.get(clientId);
|
||||
if (!decoder) {
|
||||
const ctx = getAudioCtx();
|
||||
const gainNode = ctx.createGain();
|
||||
gainNode.gain.value = (volumes[clientId] ?? 1) * outputVolume.value;
|
||||
gainNode.connect(ctx.destination);
|
||||
remoteGains.set(clientId, gainNode);
|
||||
decoder = new AudioDecoder({
|
||||
output: (chunk: AudioData) => {
|
||||
try {
|
||||
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
|
||||
const buffer = ctx.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
|
||||
for (let ch = 0; ch < numberOfChannels; ch++) {
|
||||
const data = new Float32Array(numberOfFrames);
|
||||
chunk.copyTo(data, { planeIndex: ch, format: "f32-planar" });
|
||||
buffer.copyToChannel(data, ch);
|
||||
}
|
||||
const source = ctx.createBufferSource();
|
||||
source.buffer = buffer;
|
||||
source.connect(gainNode);
|
||||
let playTime = remotePlayTimes.get(clientId) ?? ctx.currentTime;
|
||||
if (playTime < ctx.currentTime) playTime = ctx.currentTime;
|
||||
source.start(playTime);
|
||||
remotePlayTimes.set(clientId, playTime + numberOfFrames / sampleRate);
|
||||
} catch {
|
||||
// A decoder can finish while the audio context is being torn down.
|
||||
}
|
||||
chunk.close();
|
||||
},
|
||||
error: () => {
|
||||
remoteDecoders.delete(clientId);
|
||||
},
|
||||
});
|
||||
decoder.configure({ codec: "opus", sampleRate: 48000, numberOfChannels: 1 });
|
||||
remoteDecoders.set(clientId, decoder);
|
||||
}
|
||||
|
||||
try {
|
||||
const timestamp = remoteDecodeTimestamps.get(clientId) ?? 0;
|
||||
decoder.decode(new EncodedAudioChunk({ type: "key", timestamp, duration: 20_000, data: opusData }));
|
||||
remoteDecodeTimestamps.set(clientId, timestamp + 20_000);
|
||||
} catch {
|
||||
// Ignore malformed frames; the next valid frame can still be decoded.
|
||||
}
|
||||
}
|
||||
|
||||
function connect(tsHost: string, tsPort: number, channel: string, nickname: string): void {
|
||||
disconnect();
|
||||
state.error = "";
|
||||
state.connecting = true;
|
||||
const proto = location.protocol === "https:" ? "wss:" : "ws:";
|
||||
const params = new URLSearchParams({ tsHost, tsPort: String(tsPort), nickname });
|
||||
if (channel) params.set("channel", channel);
|
||||
const socket = new WebSocket(`${proto}//${location.host}/ws/voice?${params.toString()}`);
|
||||
socket.binaryType = "arraybuffer";
|
||||
ws.value = socket;
|
||||
socket.onopen = () => {
|
||||
startMicrophone().catch((error: unknown) => {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
});
|
||||
};
|
||||
socket.onmessage = (event) => {
|
||||
if (typeof event.data === "string") {
|
||||
try {
|
||||
handleMessage(JSON.parse(event.data));
|
||||
} catch {
|
||||
// Ignore malformed control frames.
|
||||
}
|
||||
} else {
|
||||
handleAudioFrame(new Uint8Array(event.data));
|
||||
}
|
||||
};
|
||||
socket.onclose = (event) => {
|
||||
state.connected = false;
|
||||
state.connecting = false;
|
||||
if (event.code !== 1000 && !state.error) state.error = closeReason(event.code);
|
||||
stopMicrophone();
|
||||
};
|
||||
socket.onerror = () => {
|
||||
state.error = "连接服务器失败,请检查邀请链接或服务器状态";
|
||||
};
|
||||
}
|
||||
|
||||
function closeReason(code: number): string {
|
||||
if (code === 4002) return "TeamSpeak 服务器地址无效";
|
||||
if (code === 4003) return "TeamSpeak 服务器连接失败";
|
||||
if (code === 4004) return "服务器当前已满,请稍后重试";
|
||||
return "连接已断开";
|
||||
}
|
||||
|
||||
function disconnect(): void {
|
||||
stopMicrophone();
|
||||
const socket = ws.value;
|
||||
ws.value = null;
|
||||
if (socket && socket.readyState < WebSocket.CLOSING) socket.close(1000);
|
||||
state.connected = false;
|
||||
state.connecting = false;
|
||||
state.tsClientId = 0;
|
||||
members.length = 0;
|
||||
channels.length = 0;
|
||||
chatMessages.length = 0;
|
||||
for (const decoder of remoteDecoders.values()) decoder.close();
|
||||
remoteDecoders.clear();
|
||||
remotePlayTimes.clear();
|
||||
remoteDecodeTimestamps.clear();
|
||||
for (const gain of remoteGains.values()) gain.disconnect();
|
||||
remoteGains.clear();
|
||||
clearSpeakingState();
|
||||
for (const key of Object.keys(volumes)) delete volumes[Number(key)];
|
||||
}
|
||||
|
||||
function handleMessage(msg: any): void {
|
||||
switch (msg.type) {
|
||||
case "connected":
|
||||
state.connected = true;
|
||||
state.connecting = false;
|
||||
state.tsClientId = Number(msg.tsClientId) || 0;
|
||||
if (Array.isArray(msg.members)) {
|
||||
members.length = 0;
|
||||
for (const member of msg.members) {
|
||||
members.push({ ...member, isSelf: Number(member.id) === state.tsClientId });
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "memberEnter":
|
||||
if (!members.some((member) => member.id === msg.id)) {
|
||||
members.push({ id: msg.id, nickname: msg.nickname, isSelf: Boolean(msg.isSelf) });
|
||||
}
|
||||
break;
|
||||
case "memberLeave": {
|
||||
clearSpeaking(Number(msg.id));
|
||||
const index = members.findIndex((member) => member.id === msg.id);
|
||||
if (index >= 0) members.splice(index, 1);
|
||||
break;
|
||||
}
|
||||
case "channelList":
|
||||
channels.length = 0;
|
||||
if (Array.isArray(msg.channels)) {
|
||||
for (const channel of msg.channels) channels.push(channel);
|
||||
}
|
||||
break;
|
||||
case "chatMessage":
|
||||
if (Number(msg.invokerId) === state.tsClientId) break;
|
||||
chatMessages.push({
|
||||
id: `remote-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
||||
invokerName: String(msg.invokerName || "Unknown"),
|
||||
message: String(msg.message || ""),
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
break;
|
||||
case "channelSwitched":
|
||||
break;
|
||||
case "disconnected":
|
||||
state.connected = false;
|
||||
state.connecting = false;
|
||||
state.error = "TeamSpeak 连接已断开";
|
||||
break;
|
||||
case "error":
|
||||
state.error = String(msg.message || "操作失败");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function handleAudioFrame(data: Uint8Array): void {
|
||||
if (data.length < 4) return;
|
||||
const clientId = (data[1] << 8) | data[2];
|
||||
if (clientId === state.tsClientId) return;
|
||||
markSpeaking(clientId);
|
||||
playAudioFrame(clientId, data.slice(3));
|
||||
}
|
||||
|
||||
function sendCmd(command: Record<string, unknown>): void {
|
||||
if (ws.value?.readyState === WebSocket.OPEN) ws.value.send(JSON.stringify(command));
|
||||
}
|
||||
|
||||
function switchChannel(channelId: string): void {
|
||||
sendCmd({ type: "switchChannel", channelId });
|
||||
}
|
||||
|
||||
function sendTextMessage(message: string): void {
|
||||
const trimmed = message.trim();
|
||||
if (!trimmed || trimmed.length > 500) return;
|
||||
sendCmd({ type: "sendTextMessage", message: trimmed });
|
||||
chatMessages.push({
|
||||
id: `self-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
||||
invokerName: "你",
|
||||
message: trimmed,
|
||||
timestamp: Date.now(),
|
||||
isSelf: true,
|
||||
});
|
||||
}
|
||||
|
||||
function setMicMode(mode: "vox" | "ptt"): void {
|
||||
micMode.value = mode;
|
||||
if (mode === "vox") pttPressed = false;
|
||||
}
|
||||
|
||||
function setPTT(pressed: boolean): void {
|
||||
pttPressed = pressed;
|
||||
}
|
||||
|
||||
function clearError(): void {
|
||||
state.error = "";
|
||||
}
|
||||
|
||||
function setVolume(clientId: number, volume: number): void {
|
||||
const normalized = Math.max(0, Math.min(4, volume));
|
||||
volumes[clientId] = normalized;
|
||||
const gain = remoteGains.get(clientId);
|
||||
if (gain) gain.gain.value = normalized * outputVolume.value;
|
||||
}
|
||||
|
||||
function setInputVolume(volume: number): void {
|
||||
inputVolume.value = Math.max(0, Math.min(1, volume));
|
||||
if (micGain) micGain.gain.value = inputVolume.value;
|
||||
}
|
||||
|
||||
function setOutputVolume(volume: number): void {
|
||||
outputVolume.value = Math.max(0, Math.min(1, volume));
|
||||
for (const [clientId, gain] of remoteGains) gain.gain.value = (volumes[clientId] ?? 1) * outputVolume.value;
|
||||
}
|
||||
|
||||
return {
|
||||
ws,
|
||||
state,
|
||||
members,
|
||||
channels,
|
||||
chatMessages,
|
||||
micMode,
|
||||
inputVolume,
|
||||
outputVolume,
|
||||
inputDevices,
|
||||
selectedInputDeviceId,
|
||||
micLevel,
|
||||
microphoneTestActive,
|
||||
speakingIds,
|
||||
volumes,
|
||||
setVolume,
|
||||
setInputVolume,
|
||||
setOutputVolume,
|
||||
prepareInputDevices,
|
||||
setInputDevice,
|
||||
startMicrophoneTest,
|
||||
stopMicrophoneTest,
|
||||
connect,
|
||||
disconnect,
|
||||
switchChannel,
|
||||
sendTextMessage,
|
||||
setMicMode,
|
||||
setPTT,
|
||||
checkSupport,
|
||||
clearError,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { createApp } from "vue";
|
||||
import { createPinia } from "pinia";
|
||||
import { createRouter, createWebHistory } from "vue-router";
|
||||
import App from "./App.vue";
|
||||
import WebClient from "./views/WebClient.vue";
|
||||
|
||||
const routes = [
|
||||
{ path: "/", name: "webclient", component: WebClient },
|
||||
];
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes,
|
||||
});
|
||||
|
||||
const app = createApp(App);
|
||||
app.use(createPinia());
|
||||
app.use(router);
|
||||
app.mount("#app");
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"jsx": "preserve",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"esModuleInterop": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.vue"]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { defineConfig } from "vite";
|
||||
import vue from "@vitejs/plugin-vue";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
"/api": "http://localhost:3030",
|
||||
"/ws": {
|
||||
target: "ws://localhost:3030",
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user