mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-01 00:42:49 +08:00
Initial commit: browser-based TeamSpeak client
React frontend + Node gateway + Rust connector (tsclientlib) providing connect, channel tree/switching, channel/server/private text chat, and voice with voice activation and output device selection.
This commit is contained in:
commit
b3e55a60b5
33 files changed
+7383
No files matched your search
+334
@@ -0,0 +1,334 @@
|
||||
.ts-app {
|
||||
--bg: #ffffff;
|
||||
--bg-toolbar-1: #f5f6f8;
|
||||
--bg-toolbar-2: #dfe2e6;
|
||||
--border: #b7bcc3;
|
||||
--border-soft: #d3d7db;
|
||||
--text: #1a1a1a;
|
||||
--text-muted: #888;
|
||||
--accent: #2b4a6b;
|
||||
--input-bg: #ffffff;
|
||||
--input-text: #1a1a1a;
|
||||
--button-bg-1: #fdfdfd;
|
||||
--button-bg-2: #dde2e8;
|
||||
--button-bg-hover-1: #ffffff;
|
||||
--button-bg-hover-2: #e7ecf1;
|
||||
--row-hover: #cfe4fb;
|
||||
--client-text: #333;
|
||||
--self-text: #0b5fa5;
|
||||
--log-bg: #f7f8f9;
|
||||
--log-text: #333;
|
||||
--log-error: #b3261e;
|
||||
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
.ts-app.ts-theme-dark {
|
||||
--bg: #1e1f22;
|
||||
--bg-toolbar-1: #2b2d31;
|
||||
--bg-toolbar-2: #232428;
|
||||
--border: #3a3c42;
|
||||
--border-soft: #35373d;
|
||||
--text: #e3e5e8;
|
||||
--text-muted: #9a9ca1;
|
||||
--accent: #9db4d1;
|
||||
--input-bg: #313338;
|
||||
--input-text: #e3e5e8;
|
||||
--button-bg-1: #3a3c42;
|
||||
--button-bg-2: #2b2d31;
|
||||
--button-bg-hover-1: #45474e;
|
||||
--button-bg-hover-2: #35373d;
|
||||
--row-hover: #35404d;
|
||||
--client-text: #d5d7db;
|
||||
--self-text: #7db2f0;
|
||||
--log-bg: #202124;
|
||||
--log-text: #c7c9cc;
|
||||
--log-error: #f2867a;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
/* Toolbar */
|
||||
|
||||
.ts-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1.5rem;
|
||||
padding: 0.4rem 0.75rem;
|
||||
background: linear-gradient(to bottom, var(--bg-toolbar-1), var(--bg-toolbar-2));
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ts-app-title {
|
||||
font-weight: 600;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.ts-toolbar-fields {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.ts-toolbar-fields label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.ts-toolbar-fields input:not([type="range"]) {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 2px;
|
||||
padding: 0.15rem 0.4rem;
|
||||
font-size: 12px;
|
||||
background: var(--input-bg);
|
||||
color: var(--input-text);
|
||||
}
|
||||
|
||||
.ts-toolbar-fields input[type="range"] {
|
||||
width: 80px;
|
||||
}
|
||||
|
||||
.ts-toolbar-fields select {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 2px;
|
||||
padding: 0.1rem 0.3rem;
|
||||
font-size: 12px;
|
||||
background: var(--input-bg);
|
||||
color: var(--input-text);
|
||||
max-width: 200px;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.ts-toolbar-fields button {
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ts-toolbar-fields button {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 3px;
|
||||
background: linear-gradient(to bottom, var(--button-bg-1), var(--button-bg-2));
|
||||
color: var(--text);
|
||||
padding: 0.25rem 0.9rem;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.ts-toolbar-fields button:hover {
|
||||
background: linear-gradient(to bottom, var(--button-bg-hover-1), var(--button-bg-hover-2));
|
||||
}
|
||||
|
||||
.ts-theme-toggle {
|
||||
padding: 0.2rem 0.5rem !important;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
/* Body / tree */
|
||||
|
||||
.ts-body {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.ts-tree-panel {
|
||||
width: 260px;
|
||||
flex-shrink: 0;
|
||||
overflow-y: auto;
|
||||
padding: 0.4rem 0.5rem;
|
||||
border-right: 1px solid var(--border-soft);
|
||||
}
|
||||
|
||||
.ts-tree-empty {
|
||||
color: var(--text-muted);
|
||||
padding: 1rem;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.ts-tree-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding-left: 1.1rem;
|
||||
}
|
||||
|
||||
.ts-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 1px 0.3rem;
|
||||
border-radius: 2px;
|
||||
white-space: nowrap;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.ts-server-row {
|
||||
font-weight: 600;
|
||||
color: var(--accent);
|
||||
padding-left: 0.3rem;
|
||||
margin-bottom: 0.15rem;
|
||||
}
|
||||
|
||||
.ts-channel-row {
|
||||
cursor: pointer;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.ts-channel-row:hover {
|
||||
background: var(--row-hover);
|
||||
}
|
||||
|
||||
.ts-client-row {
|
||||
color: var(--client-text);
|
||||
padding-left: 0.65rem;
|
||||
}
|
||||
|
||||
.ts-client-row.ts-self {
|
||||
font-weight: 700;
|
||||
color: var(--self-text);
|
||||
}
|
||||
|
||||
.ts-client-row:not(.ts-self) {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ts-client-row:not(.ts-self):hover {
|
||||
background: var(--row-hover);
|
||||
}
|
||||
|
||||
.ts-client-row.ts-talking {
|
||||
outline: 1px solid #4caf50;
|
||||
border-radius: 2px;
|
||||
background: color-mix(in srgb, #4caf50 15%, transparent);
|
||||
}
|
||||
|
||||
.ts-mic-on {
|
||||
background: color-mix(in srgb, #4caf50 30%, var(--button-bg-1)) !important;
|
||||
}
|
||||
|
||||
/* Chat */
|
||||
|
||||
.ts-chat-panel {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ts-chat-tabs {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
padding: 0.3rem 0.5rem 0;
|
||||
border-bottom: 1px solid var(--border-soft);
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.ts-chat-tab {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
border: 1px solid var(--border-soft);
|
||||
border-bottom: none;
|
||||
border-radius: 3px 3px 0 0;
|
||||
background: var(--bg-toolbar-1);
|
||||
color: var(--text-muted);
|
||||
padding: 0.25rem 0.6rem;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ts-chat-tab-active {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ts-chat-tab-unread:not(.ts-chat-tab-active) {
|
||||
color: var(--self-text);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ts-chat-tab-close {
|
||||
color: var(--text-muted);
|
||||
padding: 0 0.15rem;
|
||||
}
|
||||
|
||||
.ts-chat-tab-close:hover {
|
||||
color: var(--log-error);
|
||||
}
|
||||
|
||||
.ts-chat-messages {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 0.5rem 0.75rem;
|
||||
}
|
||||
|
||||
.ts-chat-line {
|
||||
padding: 1px 0;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.ts-chat-from {
|
||||
font-weight: 600;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.ts-chat-input-row {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
padding: 0.4rem 0.6rem;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
}
|
||||
|
||||
.ts-chat-input-row input {
|
||||
flex: 1;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 2px;
|
||||
padding: 0.3rem 0.5rem;
|
||||
font-size: 12px;
|
||||
background: var(--input-bg);
|
||||
color: var(--input-text);
|
||||
}
|
||||
|
||||
.ts-chat-input-row button {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 3px;
|
||||
background: linear-gradient(to bottom, var(--button-bg-1), var(--button-bg-2));
|
||||
color: var(--text);
|
||||
padding: 0.2rem 0.9rem;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* Log */
|
||||
|
||||
.ts-log {
|
||||
flex-shrink: 0;
|
||||
max-height: 6.5rem;
|
||||
overflow-y: auto;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
background: var(--log-bg);
|
||||
padding: 0.3rem 0.6rem;
|
||||
font-family: ui-monospace, Consolas, monospace;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.ts-log-info {
|
||||
color: var(--log-text);
|
||||
}
|
||||
|
||||
.ts-log-error {
|
||||
color: var(--log-error);
|
||||
}
|
||||
+563
@@ -0,0 +1,563 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import "./App.css";
|
||||
import {
|
||||
AudioPlayer,
|
||||
MicCapture,
|
||||
SAMPLE_RATE,
|
||||
hasNativeOutputPicker,
|
||||
listAudioOutputDevices,
|
||||
pickAudioOutputDevice,
|
||||
setAudioOutputDevice,
|
||||
} from "./voice";
|
||||
|
||||
const GATEWAY_URL = "ws://localhost:8080";
|
||||
|
||||
type LogEntry = { text: string; kind: "info" | "error" };
|
||||
|
||||
interface ChannelInfo {
|
||||
id: number;
|
||||
parent: number;
|
||||
order: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface ClientInfo {
|
||||
id: number;
|
||||
channel: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
function ChannelIcon() {
|
||||
return (
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">
|
||||
<path
|
||||
d="M1.5 3.5c0-.55.45-1 1-1h3.4l1.2 1.4h6.4c.55 0 1 .45 1 1v7.1c0 .55-.45 1-1 1h-11c-.55 0-1-.45-1-1v-8.5Z"
|
||||
fill="#e8c46a"
|
||||
stroke="#b8923f"
|
||||
strokeWidth="0.6"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function ClientIcon() {
|
||||
return (
|
||||
<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true">
|
||||
<circle cx="8" cy="5.2" r="3" fill="#6d8fb0" />
|
||||
<path d="M2 14c0-3.3 2.7-5.2 6-5.2s6 1.9 6 5.2v.3H2V14Z" fill="#6d8fb0" />
|
||||
<circle cx="12.3" cy="12.3" r="2.6" fill="#4caf50" stroke="#fff" strokeWidth="0.8" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function ServerIcon() {
|
||||
return (
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">
|
||||
<rect x="1.5" y="2" width="13" height="4.2" rx="0.6" fill="#7a8a99" stroke="#5c6b78" strokeWidth="0.5" />
|
||||
<rect x="1.5" y="7" width="13" height="4.2" rx="0.6" fill="#8a9aab" stroke="#5c6b78" strokeWidth="0.5" />
|
||||
<circle cx="3.5" cy="4.1" r="0.6" fill="#4caf50" />
|
||||
<circle cx="3.5" cy="9.1" r="0.6" fill="#4caf50" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function ChannelTree({
|
||||
channels,
|
||||
clients,
|
||||
parent,
|
||||
ownClientId,
|
||||
talkers,
|
||||
onSelectChannel,
|
||||
onOpenPrivateChat,
|
||||
}: {
|
||||
channels: ChannelInfo[];
|
||||
clients: ClientInfo[];
|
||||
parent: number;
|
||||
ownClientId: number | null;
|
||||
talkers: Set<number>;
|
||||
onSelectChannel: (channelId: number) => void;
|
||||
onOpenPrivateChat: (clientId: number, clientName: string) => void;
|
||||
}) {
|
||||
const children = channels.filter((c) => c.parent === parent).sort((a, b) => a.order - b.order);
|
||||
if (children.length === 0) return null;
|
||||
|
||||
return (
|
||||
<ul className="ts-tree-list">
|
||||
{children.map((channel) => (
|
||||
<li key={channel.id}>
|
||||
<div className="ts-row ts-channel-row" onClick={() => onSelectChannel(channel.id)}>
|
||||
<ChannelIcon />
|
||||
<span>{channel.name}</span>
|
||||
</div>
|
||||
<ul className="ts-tree-list">
|
||||
{clients
|
||||
.filter((c) => c.channel === channel.id)
|
||||
.map((c) => (
|
||||
<li key={c.id}>
|
||||
<div
|
||||
className={`ts-row ts-client-row${c.id === ownClientId ? " ts-self" : ""}${
|
||||
talkers.has(c.id) ? " ts-talking" : ""
|
||||
}`}
|
||||
onClick={c.id === ownClientId ? undefined : () => onOpenPrivateChat(c.id, c.name)}
|
||||
title={c.id === ownClientId ? undefined : `Private chat with ${c.name}`}
|
||||
>
|
||||
<ClientIcon />
|
||||
<span>{c.name}</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<ChannelTree
|
||||
channels={channels}
|
||||
clients={clients}
|
||||
parent={channel.id}
|
||||
ownClientId={ownClientId}
|
||||
talkers={talkers}
|
||||
onSelectChannel={onSelectChannel}
|
||||
onOpenPrivateChat={onOpenPrivateChat}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
interface ChatEntry {
|
||||
from: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface PmMessage {
|
||||
fromSelf: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface PmThread {
|
||||
partnerId: number;
|
||||
partnerName: string;
|
||||
messages: PmMessage[];
|
||||
unread: boolean;
|
||||
}
|
||||
|
||||
type ActiveTab = "channel" | "server" | number;
|
||||
|
||||
function App() {
|
||||
const [host, setHost] = useState("localhost");
|
||||
const [nickname, setNickname] = useState("Claude Code");
|
||||
const [log, setLog] = useState<LogEntry[]>([]);
|
||||
const [connected, setConnected] = useState(false);
|
||||
const [channels, setChannels] = useState<ChannelInfo[]>([]);
|
||||
const [clients, setClients] = useState<ClientInfo[]>([]);
|
||||
const [chat, setChat] = useState<ChatEntry[]>([]);
|
||||
const [serverChat, setServerChat] = useState<ChatEntry[]>([]);
|
||||
const [chatInput, setChatInput] = useState("");
|
||||
const [pmThreads, setPmThreads] = useState<Record<number, PmThread>>({});
|
||||
const [activeTab, setActiveTab] = useState<ActiveTab>("channel");
|
||||
const [theme, setTheme] = useState<"light" | "dark">(() =>
|
||||
window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light"
|
||||
);
|
||||
const [micOn, setMicOn] = useState(false);
|
||||
const [talkers, setTalkers] = useState<Set<number>>(new Set());
|
||||
const [selfActive, setSelfActive] = useState(false);
|
||||
const [vadThreshold, setVadThreshold] = useState(0.02);
|
||||
const [outputDevices, setOutputDevices] = useState<MediaDeviceInfo[]>([]);
|
||||
const [outputDeviceId, setOutputDeviceId] = useState("");
|
||||
const [outputDeviceLabel, setOutputDeviceLabel] = useState("System default");
|
||||
const socketRef = useRef<WebSocket | null>(null);
|
||||
const chatEndRef = useRef<HTMLDivElement | null>(null);
|
||||
const audioContextRef = useRef<AudioContext | null>(null);
|
||||
const audioPlayerRef = useRef<AudioPlayer | null>(null);
|
||||
const micCaptureRef = useRef<MicCapture | null>(null);
|
||||
const activeTabRef = useRef<ActiveTab>("channel");
|
||||
|
||||
useEffect(() => {
|
||||
chatEndRef.current?.scrollIntoView({ block: "nearest" });
|
||||
}, [chat, serverChat, pmThreads, activeTab]);
|
||||
|
||||
useEffect(() => {
|
||||
if (micCaptureRef.current) micCaptureRef.current.threshold = vadThreshold;
|
||||
}, [vadThreshold]);
|
||||
|
||||
useEffect(() => {
|
||||
activeTabRef.current = activeTab;
|
||||
if (activeTab !== "channel") {
|
||||
setPmThreads((prev) => {
|
||||
const thread = prev[activeTab];
|
||||
if (!thread || !thread.unread) return prev;
|
||||
return { ...prev, [activeTab]: { ...thread, unread: false } };
|
||||
});
|
||||
}
|
||||
}, [activeTab]);
|
||||
|
||||
const refreshOutputDevices = async () => {
|
||||
try {
|
||||
const devices = await listAudioOutputDevices();
|
||||
setOutputDevices(devices);
|
||||
} catch {
|
||||
// Device labels/enumeration may be unavailable before mic permission is granted.
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
navigator.mediaDevices?.addEventListener?.("devicechange", refreshOutputDevices);
|
||||
return () => navigator.mediaDevices?.removeEventListener?.("devicechange", refreshOutputDevices);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => socketRef.current?.close();
|
||||
}, []);
|
||||
|
||||
const appendLog = (entry: LogEntry) => setLog((prev) => [...prev, entry]);
|
||||
|
||||
const stopMic = () => {
|
||||
micCaptureRef.current?.stop();
|
||||
micCaptureRef.current = null;
|
||||
setMicOn(false);
|
||||
setSelfActive(false);
|
||||
};
|
||||
|
||||
const handleConnect = () => {
|
||||
const audioContext = new AudioContext({ sampleRate: SAMPLE_RATE });
|
||||
audioContextRef.current = audioContext;
|
||||
audioPlayerRef.current = new AudioPlayer(audioContext);
|
||||
|
||||
const socket = new WebSocket(GATEWAY_URL);
|
||||
socketRef.current = socket;
|
||||
|
||||
socket.onopen = () => {
|
||||
socket.send(JSON.stringify({ type: "connect", host, nickname }));
|
||||
};
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
switch (data.type) {
|
||||
case "connected":
|
||||
setConnected(true);
|
||||
setServerChat((prev) => [...prev, { from: "Server", message: data.welcomeMessage }]);
|
||||
break;
|
||||
case "channels":
|
||||
setChannels(data.channels);
|
||||
setClients(data.clients);
|
||||
break;
|
||||
case "chatMessage":
|
||||
setChat((prev) => [...prev, { from: data.from, message: data.message }]);
|
||||
break;
|
||||
case "serverMessage":
|
||||
setServerChat((prev) => [...prev, { from: data.from, message: data.message }]);
|
||||
break;
|
||||
case "privateMessage":
|
||||
setPmThreads((prev) => {
|
||||
const existing = prev[data.partnerId];
|
||||
const thread: PmThread = existing ?? {
|
||||
partnerId: data.partnerId,
|
||||
partnerName: data.partnerName,
|
||||
messages: [],
|
||||
unread: false,
|
||||
};
|
||||
return {
|
||||
...prev,
|
||||
[data.partnerId]: {
|
||||
...thread,
|
||||
partnerName: data.partnerName,
|
||||
messages: [...thread.messages, { fromSelf: data.fromSelf, message: data.message }],
|
||||
unread: thread.unread || (!data.fromSelf && activeTabRef.current !== data.partnerId),
|
||||
},
|
||||
};
|
||||
});
|
||||
break;
|
||||
case "audioOut":
|
||||
audioPlayerRef.current?.playFrame(data.pcm);
|
||||
break;
|
||||
case "talkers":
|
||||
setTalkers(new Set<number>(data.clients));
|
||||
break;
|
||||
case "disconnected":
|
||||
setConnected(false);
|
||||
setChannels([]);
|
||||
setClients([]);
|
||||
setChat([]);
|
||||
setServerChat([]);
|
||||
setPmThreads({});
|
||||
setActiveTab("channel");
|
||||
setTalkers(new Set());
|
||||
stopMic();
|
||||
appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" });
|
||||
break;
|
||||
case "error":
|
||||
appendLog({ text: data.message, kind: "error" });
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
socket.onerror = () => appendLog({ text: "WebSocket error (is the gateway running?)", kind: "error" });
|
||||
socket.onclose = () => {
|
||||
setConnected(false);
|
||||
stopMic();
|
||||
audioContextRef.current?.close();
|
||||
audioContextRef.current = null;
|
||||
audioPlayerRef.current = null;
|
||||
};
|
||||
};
|
||||
|
||||
const handleDisconnect = () => socketRef.current?.close();
|
||||
|
||||
const handleToggleMic = async () => {
|
||||
if (micOn) {
|
||||
stopMic();
|
||||
return;
|
||||
}
|
||||
const audioContext = audioContextRef.current;
|
||||
if (!audioContext) return;
|
||||
try {
|
||||
const mic = new MicCapture(
|
||||
audioContext,
|
||||
(pcm) => socketRef.current?.send(JSON.stringify({ type: "sendAudio", pcm })),
|
||||
(active) => setSelfActive(active),
|
||||
vadThreshold
|
||||
);
|
||||
await mic.start();
|
||||
micCaptureRef.current = mic;
|
||||
setMicOn(true);
|
||||
refreshOutputDevices();
|
||||
} catch (error) {
|
||||
appendLog({ text: `Microphone error: ${(error as Error).message}`, kind: "error" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleOutputDeviceChange = async (deviceId: string, label?: string) => {
|
||||
setOutputDeviceId(deviceId);
|
||||
setOutputDeviceLabel(label || (deviceId ? `Output ${deviceId.slice(0, 6)}` : "System default"));
|
||||
if (audioContextRef.current) await setAudioOutputDevice(audioContextRef.current, deviceId);
|
||||
};
|
||||
|
||||
const handlePickOutputDevice = async () => {
|
||||
try {
|
||||
const device = await pickAudioOutputDevice();
|
||||
if (device) await handleOutputDeviceChange(device.deviceId, device.label);
|
||||
} catch (error) {
|
||||
appendLog({ text: `Output device error: ${(error as Error).message}`, kind: "error" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectChannel = (channelId: number) => {
|
||||
socketRef.current?.send(JSON.stringify({ type: "switchChannel", channelId }));
|
||||
};
|
||||
|
||||
const handleSendChat = () => {
|
||||
const message = chatInput.trim();
|
||||
if (!message) return;
|
||||
if (activeTab === "channel") {
|
||||
socketRef.current?.send(JSON.stringify({ type: "sendChatMessage", message }));
|
||||
} else if (activeTab === "server") {
|
||||
socketRef.current?.send(JSON.stringify({ type: "sendServerMessage", message }));
|
||||
} else {
|
||||
socketRef.current?.send(JSON.stringify({ type: "sendPrivateMessage", clientId: activeTab, message }));
|
||||
}
|
||||
setChatInput("");
|
||||
};
|
||||
|
||||
const handleOpenPrivateChat = (clientId: number, clientName: string) => {
|
||||
setPmThreads((prev) => ({
|
||||
...prev,
|
||||
[clientId]: prev[clientId] ?? { partnerId: clientId, partnerName: clientName, messages: [], unread: false },
|
||||
}));
|
||||
setActiveTab(clientId);
|
||||
};
|
||||
|
||||
const handleClosePrivateChat = (clientId: number) => {
|
||||
setPmThreads((prev) => {
|
||||
const next = { ...prev };
|
||||
delete next[clientId];
|
||||
return next;
|
||||
});
|
||||
setActiveTab((current) => (current === clientId ? "channel" : current));
|
||||
};
|
||||
|
||||
const ownClient = clients.find((c) => c.name === nickname) ?? null;
|
||||
const displayTalkers =
|
||||
selfActive && ownClient ? new Set(talkers).add(ownClient.id) : talkers;
|
||||
|
||||
return (
|
||||
<div className={`ts-app ts-theme-${theme}`}>
|
||||
<div className="ts-toolbar">
|
||||
<span className="ts-app-title">TS Web Client</span>
|
||||
<div className="ts-toolbar-fields">
|
||||
<label>
|
||||
Server
|
||||
<input value={host} onChange={(e) => setHost(e.target.value)} disabled={connected} />
|
||||
</label>
|
||||
<label>
|
||||
Nickname
|
||||
<input value={nickname} onChange={(e) => setNickname(e.target.value)} disabled={connected} />
|
||||
</label>
|
||||
{!connected ? (
|
||||
<button onClick={handleConnect}>Connect</button>
|
||||
) : (
|
||||
<button onClick={handleDisconnect}>Disconnect</button>
|
||||
)}
|
||||
<button
|
||||
className={micOn ? "ts-mic-on" : undefined}
|
||||
onClick={handleToggleMic}
|
||||
disabled={!connected}
|
||||
title={micOn ? "Voice activation on - click to mute" : "Enable microphone (voice activation)"}
|
||||
>
|
||||
{micOn ? "🎤" : "🔇"}
|
||||
</button>
|
||||
<label title="Voice activation sensitivity">
|
||||
🎚️
|
||||
<input
|
||||
type="range"
|
||||
min={0.002}
|
||||
max={0.15}
|
||||
step={0.002}
|
||||
value={vadThreshold}
|
||||
onChange={(e) => setVadThreshold(Number(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
{hasNativeOutputPicker() ? (
|
||||
<button onClick={handlePickOutputDevice} title="Choose output device">
|
||||
🔊 {outputDeviceLabel}
|
||||
</button>
|
||||
) : (
|
||||
<label>
|
||||
🔊
|
||||
<select
|
||||
value={outputDeviceId}
|
||||
onChange={(e) => handleOutputDeviceChange(e.target.value)}
|
||||
onFocus={refreshOutputDevices}
|
||||
>
|
||||
<option value="">System default</option>
|
||||
{outputDevices.map((d) => (
|
||||
<option key={d.deviceId} value={d.deviceId}>
|
||||
{d.label || `Output ${d.deviceId.slice(0, 6)}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<button
|
||||
className="ts-theme-toggle"
|
||||
onClick={() => setTheme((t) => (t === "dark" ? "light" : "dark"))}
|
||||
title="Toggle theme"
|
||||
>
|
||||
{theme === "dark" ? "☀️" : "🌙"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ts-body">
|
||||
<div className="ts-tree-panel">
|
||||
{connected ? (
|
||||
<>
|
||||
<div className="ts-row ts-server-row">
|
||||
<ServerIcon />
|
||||
<span>{host}</span>
|
||||
</div>
|
||||
<ChannelTree
|
||||
channels={channels}
|
||||
clients={clients}
|
||||
parent={0}
|
||||
ownClientId={ownClient?.id ?? null}
|
||||
talkers={displayTalkers}
|
||||
onSelectChannel={handleSelectChannel}
|
||||
onOpenPrivateChat={handleOpenPrivateChat}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<div className="ts-tree-empty">Not connected</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="ts-chat-panel">
|
||||
<div className="ts-chat-tabs">
|
||||
<button
|
||||
className={`ts-chat-tab${activeTab === "server" ? " ts-chat-tab-active" : ""}`}
|
||||
onClick={() => setActiveTab("server")}
|
||||
>
|
||||
Server
|
||||
</button>
|
||||
<button
|
||||
className={`ts-chat-tab${activeTab === "channel" ? " ts-chat-tab-active" : ""}`}
|
||||
onClick={() => setActiveTab("channel")}
|
||||
>
|
||||
Channel
|
||||
</button>
|
||||
{Object.values(pmThreads).map((thread) => (
|
||||
<button
|
||||
key={thread.partnerId}
|
||||
className={`ts-chat-tab${activeTab === thread.partnerId ? " ts-chat-tab-active" : ""}${
|
||||
thread.unread ? " ts-chat-tab-unread" : ""
|
||||
}`}
|
||||
onClick={() => setActiveTab(thread.partnerId)}
|
||||
>
|
||||
{thread.partnerName}
|
||||
<span
|
||||
className="ts-chat-tab-close"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleClosePrivateChat(thread.partnerId);
|
||||
}}
|
||||
>
|
||||
×
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="ts-chat-messages">
|
||||
{activeTab === "channel"
|
||||
? chat.map((entry, i) => (
|
||||
<div key={i} className="ts-chat-line">
|
||||
<span className="ts-chat-from">{entry.from}:</span> <span>{entry.message}</span>
|
||||
</div>
|
||||
))
|
||||
: activeTab === "server"
|
||||
? serverChat.map((entry, i) => (
|
||||
<div key={i} className="ts-chat-line">
|
||||
<span className="ts-chat-from">{entry.from}:</span> <span>{entry.message}</span>
|
||||
</div>
|
||||
))
|
||||
: pmThreads[activeTab]?.messages.map((entry, i) => (
|
||||
<div key={i} className="ts-chat-line">
|
||||
<span className="ts-chat-from">
|
||||
{entry.fromSelf ? "You" : pmThreads[activeTab].partnerName}:
|
||||
</span>{" "}
|
||||
<span>{entry.message}</span>
|
||||
</div>
|
||||
))}
|
||||
<div ref={chatEndRef} />
|
||||
</div>
|
||||
<div className="ts-chat-input-row">
|
||||
<input
|
||||
value={chatInput}
|
||||
onChange={(e) => setChatInput(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && handleSendChat()}
|
||||
disabled={!connected}
|
||||
placeholder={
|
||||
!connected
|
||||
? "Not connected"
|
||||
: activeTab === "channel"
|
||||
? "Message channel..."
|
||||
: activeTab === "server"
|
||||
? "Message server..."
|
||||
: `Message ${pmThreads[activeTab]?.partnerName}...`
|
||||
}
|
||||
/>
|
||||
<button onClick={handleSendChat} disabled={!connected}>
|
||||
Send
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ts-log">
|
||||
{log.map((entry, i) => (
|
||||
<div key={i} className={entry.kind === "error" ? "ts-log-error" : "ts-log-info"}>
|
||||
{entry.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="77" height="47" fill="none" aria-labelledby="vite-logo-title" viewBox="0 0 77 47"><title id="vite-logo-title">Vite</title><style>.parenthesis{fill:#000}@media (prefers-color-scheme:dark){.parenthesis{fill:#fff}}</style><path fill="#9135ff" d="M40.151 45.71c-.663.844-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.493c-.92 0-1.457-1.04-.92-1.788l7.479-10.471c1.07-1.498 0-3.578-1.842-3.578H15.443c-.92 0-1.456-1.04-.92-1.788l9.696-13.576c.213-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.472c-1.07 1.497 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.087.89 1.83L40.153 45.712z"/><mask id="a" width="48" height="47" x="14" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M40.047 45.71c-.663.843-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.389c-.92 0-1.457-1.04-.92-1.788l7.479-10.472c1.07-1.497 0-3.578-1.842-3.578H15.34c-.92 0-1.456-1.04-.92-1.788l9.696-13.575c.213-.297.556-.474.92-.474H53.93c.92 0 1.456 1.04.92 1.788L47.37 13.03c-1.07 1.498 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.088.89 1.831L40.049 45.712z"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#eee6ff" rx="5.508" ry="14.704" transform="rotate(269.814 20.96 11.29)scale(-1 1)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#eee6ff" rx="10.399" ry="29.851" transform="rotate(89.814 -16.902 -8.275)scale(1 -1)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#8900ff" rx="5.508" ry="30.487" transform="rotate(89.814 -19.197 -7.127)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.928 4.177)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.738 5.52)scale(1 -1)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#eee6ff" rx="14.072" ry="22.078" transform="rotate(93.35 31.245 55.578)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx="14.592" cy="9.743" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(39.51 14.592 9.743)"/></g><g filter="url(#k)"><ellipse cx="61.728" cy="-5.321" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 61.728 -5.32)"/></g><g filter="url(#l)"><ellipse cx="55.618" cy="7.104" fill="#00c2ff" rx="5.971" ry="9.665" transform="rotate(37.892 55.618 7.104)"/></g><g filter="url(#m)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#n)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#o)"><ellipse cx="49.857" cy="30.678" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 49.857 30.678)"/></g><g filter="url(#p)"><ellipse cx="52.623" cy="33.171" fill="#00c2ff" rx="5.971" ry="15.297" transform="rotate(37.892 52.623 33.17)"/></g></g><path d="M6.919 0c-9.198 13.166-9.252 33.575 0 46.789h6.215c-9.25-13.214-9.196-33.623 0-46.789zm62.424 0h-6.215c9.198 13.166 9.252 33.575 0 46.789h6.215c9.25-13.214 9.196-33.623 0-46.789" class="parenthesis"/><defs><filter id="b" width="60.045" height="41.654" x="-5.564" y="16.92" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-40.407" y="-6.762" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-35.435" y="2.801" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-30.84" y="20.8" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-29.307" y="21.949" color-interpolation-filters="sRGB" filterUnits="usLine truncated
|
||||
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,22 @@
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
#root {
|
||||
height: 100vh;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,190 @@
|
||||
// Encoding/decoding and Web Audio plumbing for the voice feature.
|
||||
//
|
||||
// The connector always speaks 48kHz PCM in 20ms frames: mono for the
|
||||
// microphone -> server direction (which it Opus-encodes), stereo mixed
|
||||
// for the server -> speakers direction (already decoded/mixed for us).
|
||||
|
||||
export const SAMPLE_RATE = 48000;
|
||||
export const FRAME_SAMPLES = 960; // 20ms @ 48kHz
|
||||
|
||||
function int16ToBase64(samples: Int16Array): string {
|
||||
const bytes = new Uint8Array(samples.buffer, samples.byteOffset, samples.byteLength);
|
||||
let binary = "";
|
||||
const chunkSize = 0x8000;
|
||||
for (let i = 0; i < bytes.length; i += chunkSize) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
function base64ToInt16(b64: string): Int16Array {
|
||||
const binary = atob(b64);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
||||
return new Int16Array(bytes.buffer);
|
||||
}
|
||||
|
||||
/** How long transmission continues after the level drops back below the threshold, so words aren't clipped. */
|
||||
const VAD_HANGOVER_SECONDS = 0.4;
|
||||
|
||||
/**
|
||||
* Captures the microphone and emits base64-encoded mono 16-bit PCM frames.
|
||||
*
|
||||
* Uses voice activation (like TeamSpeak's own "Sprachaktivierung"): frames are
|
||||
* only sent while the input level is above `threshold`, plus a short hangover
|
||||
* so the tail of a word isn't cut off. `onActivity` reports transitions so the
|
||||
* UI can show a local "currently transmitting" indicator.
|
||||
*/
|
||||
export class MicCapture {
|
||||
private stream: MediaStream | null = null;
|
||||
private source: MediaStreamAudioSourceNode | null = null;
|
||||
private processor: ScriptProcessorNode | null = null;
|
||||
private silence: GainNode | null = null;
|
||||
private pending: number[] = [];
|
||||
private active = false;
|
||||
private activeUntil = 0;
|
||||
threshold: number;
|
||||
|
||||
constructor(
|
||||
private context: AudioContext,
|
||||
private onFrame: (base64Pcm: string) => void,
|
||||
private onActivity?: (active: boolean) => void,
|
||||
threshold = 0.02
|
||||
) {
|
||||
this.threshold = threshold;
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true },
|
||||
});
|
||||
this.source = this.context.createMediaStreamSource(this.stream);
|
||||
this.processor = this.context.createScriptProcessor(2048, 1, 1);
|
||||
this.processor.onaudioprocess = (event) => {
|
||||
const input = event.inputBuffer.getChannelData(0);
|
||||
|
||||
let sumSquares = 0;
|
||||
for (let i = 0; i < input.length; i++) sumSquares += input[i] * input[i];
|
||||
const rms = Math.sqrt(sumSquares / input.length);
|
||||
|
||||
const now = this.context.currentTime;
|
||||
if (rms >= this.threshold) this.activeUntil = now + VAD_HANGOVER_SECONDS;
|
||||
const shouldBeActive = now < this.activeUntil;
|
||||
if (shouldBeActive !== this.active) {
|
||||
this.active = shouldBeActive;
|
||||
this.onActivity?.(this.active);
|
||||
if (!this.active) this.pending = [];
|
||||
}
|
||||
|
||||
if (!this.active) return;
|
||||
|
||||
for (let i = 0; i < input.length; i++) this.pending.push(input[i]);
|
||||
while (this.pending.length >= FRAME_SAMPLES) {
|
||||
const frame = this.pending.splice(0, FRAME_SAMPLES);
|
||||
const int16 = new Int16Array(FRAME_SAMPLES);
|
||||
for (let i = 0; i < FRAME_SAMPLES; i++) {
|
||||
const clamped = Math.max(-1, Math.min(1, frame[i]));
|
||||
int16[i] = clamped < 0 ? clamped * 32768 : clamped * 32767;
|
||||
}
|
||||
this.onFrame(int16ToBase64(int16));
|
||||
}
|
||||
};
|
||||
// A ScriptProcessorNode only fires while connected to a destination; route
|
||||
// it through a muted gain node so we don't hear our own mic echoed back.
|
||||
this.silence = this.context.createGain();
|
||||
this.silence.gain.value = 0;
|
||||
this.source.connect(this.processor);
|
||||
this.processor.connect(this.silence);
|
||||
this.silence.connect(this.context.destination);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.processor?.disconnect();
|
||||
this.silence?.disconnect();
|
||||
this.source?.disconnect();
|
||||
this.stream?.getTracks().forEach((t) => t.stop());
|
||||
this.processor = null;
|
||||
this.silence = null;
|
||||
this.source = null;
|
||||
this.stream = null;
|
||||
this.pending = [];
|
||||
if (this.active) {
|
||||
this.active = false;
|
||||
this.onActivity?.(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Output ("audiooutput") devices available for playback, e.g. for a device picker. */
|
||||
export async function listAudioOutputDevices(): Promise<MediaDeviceInfo[]> {
|
||||
const devices = await navigator.mediaDevices.enumerateDevices();
|
||||
return devices.filter((d) => d.kind === "audiooutput");
|
||||
}
|
||||
|
||||
type MediaDevicesWithPicker = MediaDevices & { selectAudioOutput?: () => Promise<MediaDeviceInfo> };
|
||||
|
||||
/** Whether the browser supports the native OS output-device picker (Chrome/Edge 105+). */
|
||||
export function hasNativeOutputPicker(): boolean {
|
||||
return typeof (navigator.mediaDevices as MediaDevicesWithPicker).selectAudioOutput === "function";
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the browser's native OS device chooser for audio output. Unlike
|
||||
* `enumerateDevices()`, this lists every device the OS knows about (including
|
||||
* ones like a USB headset that plain enumeration can otherwise omit) and asks
|
||||
* the user to pick one, each call - no persistent listing to keep in sync.
|
||||
*/
|
||||
export async function pickAudioOutputDevice(): Promise<MediaDeviceInfo | null> {
|
||||
const md = navigator.mediaDevices as MediaDevicesWithPicker;
|
||||
if (typeof md.selectAudioOutput !== "function") return null;
|
||||
return md.selectAudioOutput();
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes an AudioContext's output to a specific device (empty string = system default).
|
||||
* `setSinkId` on AudioContext is a fairly recent addition (Chrome 110+); older
|
||||
* browsers simply keep using the system default output.
|
||||
*/
|
||||
export async function setAudioOutputDevice(context: AudioContext, deviceId: string): Promise<void> {
|
||||
const ctx = context as AudioContext & { setSinkId?: (id: string) => Promise<void> };
|
||||
if (typeof ctx.setSinkId !== "function") return;
|
||||
await ctx.setSinkId(deviceId);
|
||||
}
|
||||
|
||||
/** Schedules incoming base64-encoded stereo 16-bit PCM frames for gap-free playback. */
|
||||
export class AudioPlayer {
|
||||
private nextTime = 0;
|
||||
|
||||
constructor(private context: AudioContext) {}
|
||||
|
||||
playFrame(base64Pcm: string): void {
|
||||
const int16 = base64ToInt16(base64Pcm);
|
||||
const frames = int16.length / 2;
|
||||
if (frames <= 0) return;
|
||||
|
||||
const buffer = this.context.createBuffer(2, frames, SAMPLE_RATE);
|
||||
const left = buffer.getChannelData(0);
|
||||
const right = buffer.getChannelData(1);
|
||||
for (let i = 0; i < frames; i++) {
|
||||
left[i] = int16[i * 2] / 32768;
|
||||
right[i] = int16[i * 2 + 1] / 32768;
|
||||
}
|
||||
|
||||
const source = this.context.createBufferSource();
|
||||
source.buffer = buffer;
|
||||
source.connect(this.context.destination);
|
||||
|
||||
const now = this.context.currentTime;
|
||||
if (this.nextTime < now + 0.02) {
|
||||
// First frame, or we fell behind - restart just ahead of now instead of
|
||||
// letting a backlog build up.
|
||||
this.nextTime = now + 0.02;
|
||||
}
|
||||
source.start(this.nextTime);
|
||||
this.nextTime += frames / SAMPLE_RATE;
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.nextTime = 0;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user