Add sound notifications for connect/disconnect, join/leave, chat, and poke

New Sounds options panel (Extras > Optionen > Sounds) with a master
enable toggle, volume control, and per-event upload/test/reset. Falls
back to synthesized soft two-note chimes when no custom file is set.
Sounds are routed through the same output device as voice playback.

Custom .ts3soundpack (ZIP+XML) import is left for later - this covers
the simpler per-event custom-file approach first.
This commit is contained in:
Moepchi committed 2026-07-30 22:58:53 +02:00
1 parent 3881742338
commit 7a69d8602c
4 files changed
+419 -3

No files matched your search

+22
View File
@@ -1011,6 +1011,28 @@
width: 4em;
}
.ts-options-sounds-table {
width: 100%;
border-collapse: collapse;
margin-top: 0.75rem;
font-size: 12px;
}
.ts-options-sounds-table td {
padding: 0.35rem 0.5rem 0.35rem 0;
vertical-align: middle;
border-bottom: 1px solid var(--border-color, rgba(255, 255, 255, 0.08));
}
.ts-options-sounds-source {
color: var(--text-muted);
}
.ts-options-sounds-table button {
font-size: 11px;
white-space: nowrap;
}
.ts-options-test-dot {
width: 10px;
height: 10px;
+153 -3
View File
@@ -10,6 +10,19 @@ import {
pickAudioOutputDevice,
} from "./voice";
import { LanguageProvider, useLanguage, useT, type LangPref } from "./i18n";
import {
SOUND_EVENTS,
clearCustomSound,
loadCustomSound,
loadSoundsEnabled,
loadSoundsVolume,
playSound,
saveCustomSound,
saveSoundsEnabled,
saveSoundsVolume,
setSoundsOutputDevice,
type SoundEventId,
} from "./sounds";
// In dev, the gateway runs standalone on its own port. In production it's
// served from the same origin/port as the web app (single container behind a
@@ -777,6 +790,7 @@ const OPTIONS_SECTIONS = [
{ id: "anwendung", icon: "🎧" },
{ id: "wiedergabe", icon: "🔊" },
{ id: "aufnahme", icon: "🎙️" },
{ id: "sounds", icon: "🔔" },
{ id: "design", icon: "🖌️" },
{ id: "erweiterungen", icon: "🧩" },
{ id: "hotkeys", icon: "⌨️" },
@@ -1029,6 +1043,116 @@ function AnwendungPanel() {
);
}
function SoundsPanel() {
const t = useT();
const [enabled, setEnabled] = useState(() => loadSoundsEnabled());
const [volume, setVolume] = useState(() => loadSoundsVolume());
const [customNames, setCustomNames] = useState<Partial<Record<SoundEventId, string>>>({});
const fileInputRef = useRef<HTMLInputElement | null>(null);
const uploadTargetRef = useRef<SoundEventId | null>(null);
useEffect(() => {
let cancelled = false;
(async () => {
const entries = await Promise.all(
SOUND_EVENTS.map(async (id) => [id, (await loadCustomSound(id))?.name] as const)
);
if (cancelled) return;
const next: Partial<Record<SoundEventId, string>> = {};
for (const [id, name] of entries) if (name) next[id] = name;
setCustomNames(next);
})();
return () => {
cancelled = true;
};
}, []);
const handleToggleEnabled = () => {
const next = !enabled;
setEnabled(next);
saveSoundsEnabled(next);
};
const handleVolumeChange = (v: number) => {
setVolume(v);
saveSoundsVolume(v);
};
const handleUploadClick = (event: SoundEventId) => {
uploadTargetRef.current = event;
fileInputRef.current?.click();
};
const handleFileSelected = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
const event = uploadTargetRef.current;
e.target.value = "";
if (!file || !event) return;
await saveCustomSound(event, file);
setCustomNames((prev) => ({ ...prev, [event]: file.name }));
};
const handleReset = async (event: SoundEventId) => {
await clearCustomSound(event);
setCustomNames((prev) => {
const next = { ...prev };
delete next[event];
return next;
});
};
return (
<>
<h3>{t("sounds.title")}</h3>
<p className="ts-options-subtitle">{t("sounds.subtitle")}</p>
<label className="ts-options-field-row">
<input type="checkbox" checked={enabled} onChange={handleToggleEnabled} />
{t("sounds.enable")}
</label>
<div className="ts-options-slider-with-value">
<span className="ts-options-slider-label">{t("sounds.volume")}</span>
<input
type="range"
min={0}
max={1}
step={0.05}
value={volume}
onChange={(e) => handleVolumeChange(Number(e.target.value))}
/>
<span>{Math.round(volume * 100)}%</span>
</div>
<table className="ts-options-sounds-table">
<tbody>
{SOUND_EVENTS.map((eventId) => (
<tr key={eventId}>
<td>{t(`sounds.event.${eventId}`)}</td>
<td className="ts-options-sounds-source">
{customNames[eventId] ? t("sounds.custom", { name: customNames[eventId]! }) : t("sounds.default")}
</td>
<td>
<button onClick={() => void playSound(eventId)}>{t("sounds.test")}</button>
</td>
<td>
<button onClick={() => handleUploadClick(eventId)}>{t("sounds.upload")}</button>
</td>
<td>
{customNames[eventId] && <button onClick={() => void handleReset(eventId)}>{t("sounds.reset")}</button>}
</td>
</tr>
))}
</tbody>
</table>
<input
ref={fileInputRef}
type="file"
accept="audio/*"
style={{ display: "none" }}
onChange={(e) => void handleFileSelected(e)}
/>
</>
);
}
function OptionsDialog({
section,
onSectionChange,
@@ -1071,6 +1195,8 @@ function OptionsDialog({
<WiedergabePanel audio={audio} />
) : active.id === "aufnahme" ? (
<AufnahmePanel audio={audio} />
) : active.id === "sounds" ? (
<SoundsPanel />
) : (
<>
<h3>{t(`options.section.${active.id}`)}</h3>
@@ -1165,6 +1291,7 @@ function AppInner() {
const micCaptureRef = useRef<MicCapture | null>(null);
const activeTabRef = useRef<ActiveTab>("channel");
const hasConnectedRef = useRef(false);
const previousClientsRef = useRef<ClientInfo[] | null>(null);
const pokeIdRef = useRef(0);
const inputMutedRef = useRef(false);
const outputMutedRef = useRef(false);
@@ -1381,16 +1508,32 @@ function AppInner() {
setServerBannerUrl(data.serverBannerUrl);
setSelected({ type: "server" });
setServerChat((prev) => [...prev, { from: "Server", message: data.welcomeMessage }]);
previousClientsRef.current = null;
void playSound("connect");
break;
case "channels":
case "channels": {
const newClients: ClientInfo[] = data.clients;
const prevClients = previousClientsRef.current;
if (prevClients) {
const prevIds = new Set(prevClients.map((c) => c.id));
const newIds = new Set(newClients.map((c) => c.id));
const joined = newClients.some((c) => !prevIds.has(c.id) && c.name !== connectNickname);
const left = prevClients.some((c) => !newIds.has(c.id) && c.name !== connectNickname);
if (joined) void playSound("clientJoin");
if (left) void playSound("clientLeave");
}
previousClientsRef.current = newClients;
setChannels(data.channels);
setClients(data.clients);
setClients(newClients);
break;
}
case "chatMessage":
setChat((prev) => [...prev, { from: data.from, message: data.message }]);
if (data.from !== connectNickname) void playSound("message");
break;
case "serverMessage":
setServerChat((prev) => [...prev, { from: data.from, message: data.message }]);
if (data.from !== connectNickname) void playSound("message");
break;
case "privateMessage":
setPmThreads((prev) => {
@@ -1411,6 +1554,7 @@ function AppInner() {
},
};
});
if (!data.fromSelf) void playSound("message");
break;
case "audioOut":
if (!outputMutedRef.current) audioPlayerRef.current?.playFrame(data.pcm);
@@ -1422,10 +1566,13 @@ function AppInner() {
const id = ++pokeIdRef.current;
setPokes((prev) => [...prev, { id, from: data.from, message: data.message }]);
setTimeout(() => setPokes((prev) => prev.filter((p) => p.id !== id)), 10000);
void playSound("poke");
break;
}
case "disconnected":
case "disconnected": {
const wasConnected = hasConnectedRef.current;
hasConnectedRef.current = false;
previousClientsRef.current = null;
setConnecting(false);
setConnected(false);
setChannels([]);
@@ -1439,7 +1586,9 @@ function AppInner() {
setTalkers(new Set());
stopMic();
appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" });
if (wasConnected) void playSound("disconnect");
break;
}
case "error":
if (hasConnectedRef.current) {
appendLog({ text: data.message, kind: "error" });
@@ -1710,6 +1859,7 @@ function AppInner() {
setOutputDeviceId(deviceId);
setOutputDeviceLabel(label || (deviceId ? `Output ${deviceId.slice(0, 6)}` : "System default"));
await audioPlayerRef.current?.setOutputDevice(deviceId);
setSoundsOutputDevice(deviceId);
};
const handlePickOutputDevice = async () => {
+34
View File
@@ -118,6 +118,7 @@ const translations: Record<Lang, Record<string, string>> = {
"options.section.sicherheit": "Sicherheit",
"options.section.nachrichten": "Nachrichten",
"options.section.meldungen": "Meldungen",
"options.section.sounds": "Sounds",
"app.title": "Anwendung",
"app.subtitle": "Allgemeine Anwendungseinstellungen",
@@ -197,6 +198,22 @@ const translations: Record<Lang, Record<string, string>> = {
"connectError.dismiss": "Schließen",
"dialog.close": "Schließen",
"sounds.title": "Sounds",
"sounds.subtitle": "Sound-Benachrichtigungen für Ereignisse festlegen",
"sounds.enable": "Sounds aktivieren",
"sounds.volume": "Lautstärke",
"sounds.event.connect": "Verbunden",
"sounds.event.disconnect": "Getrennt",
"sounds.event.clientJoin": "Client kommt",
"sounds.event.clientLeave": "Client geht",
"sounds.event.message": "Nachricht empfangen",
"sounds.event.poke": "Anstupsen erhalten",
"sounds.default": "Standard",
"sounds.custom": "Eigene Datei: {name}",
"sounds.test": "▶ Testen",
"sounds.upload": "Hochladen",
"sounds.reset": "Zurücksetzen",
},
en: {
"menu.connections": "Connections",
@@ -306,6 +323,7 @@ const translations: Record<Lang, Record<string, string>> = {
"options.section.sicherheit": "Security",
"options.section.nachrichten": "Notifications",
"options.section.meldungen": "Messages",
"options.section.sounds": "Sounds",
"app.title": "Application",
"app.subtitle": "General application settings",
@@ -385,6 +403,22 @@ const translations: Record<Lang, Record<string, string>> = {
"connectError.dismiss": "Dismiss",
"dialog.close": "Close",
"sounds.title": "Sounds",
"sounds.subtitle": "Configure sound notifications for events",
"sounds.enable": "Enable sounds",
"sounds.volume": "Volume",
"sounds.event.connect": "Connected",
"sounds.event.disconnect": "Disconnected",
"sounds.event.clientJoin": "Client joins",
"sounds.event.clientLeave": "Client leaves",
"sounds.event.message": "Message received",
"sounds.event.poke": "Poke received",
"sounds.default": "Default",
"sounds.custom": "Custom file: {name}",
"sounds.test": "▶ Test",
"sounds.upload": "Upload",
"sounds.reset": "Reset",
},
};
+210
View File
@@ -0,0 +1,210 @@
export type SoundEventId = "connect" | "disconnect" | "clientJoin" | "clientLeave" | "message" | "poke";
export const SOUND_EVENTS: SoundEventId[] = ["connect", "disconnect", "clientJoin", "clientLeave", "message", "poke"];
const ENABLED_KEY = "webspeak3:sounds-enabled";
const VOLUME_KEY = "webspeak3:sounds-volume";
const DB_NAME = "webspeak3-sounds";
const STORE_NAME = "custom";
interface StoredSound {
blob: Blob;
name: string;
}
function openDb(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, 1);
req.onupgradeneeded = () => {
req.result.createObjectStore(STORE_NAME);
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
export async function saveCustomSound(event: SoundEventId, file: File): Promise<void> {
const db = await openDb();
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readwrite");
tx.objectStore(STORE_NAME).put({ blob: file, name: file.name } satisfies StoredSound, event);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
db.close();
}
export async function loadCustomSound(event: SoundEventId): Promise<StoredSound | undefined> {
const db = await openDb();
const result = await new Promise<StoredSound | undefined>((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readonly");
const req = tx.objectStore(STORE_NAME).get(event);
req.onsuccess = () => resolve(req.result as StoredSound | undefined);
req.onerror = () => reject(req.error);
});
db.close();
return result;
}
export async function clearCustomSound(event: SoundEventId): Promise<void> {
const db = await openDb();
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readwrite");
tx.objectStore(STORE_NAME).delete(event);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
db.close();
}
export function loadSoundsEnabled(): boolean {
const raw = localStorage.getItem(ENABLED_KEY);
return raw === null ? true : raw === "true";
}
export function saveSoundsEnabled(enabled: boolean): void {
localStorage.setItem(ENABLED_KEY, String(enabled));
}
export function loadSoundsVolume(): number {
const raw = localStorage.getItem(VOLUME_KEY);
const n = raw ? Number(raw) : 0.5;
return Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : 0.5;
}
export function saveSoundsVolume(volume: number): void {
localStorage.setItem(VOLUME_KEY, String(volume));
}
type SinkableElement = HTMLAudioElement & { setSinkId?: (id: string) => Promise<void> };
/**
* Notification sounds get their own AudioContext, independent from the
* voice AudioContext in voice.ts - that one is created on connect and torn
* down on disconnect, but sounds must keep working (and be testable from
* Options) regardless of connection state.
*/
class NotificationSoundPlayer {
private context: AudioContext | null = null;
private destination: MediaStreamAudioDestinationNode | null = null;
private element: SinkableElement | null = null;
private outputDeviceId = "";
private ensure(): { context: AudioContext; destination: MediaStreamAudioDestinationNode } {
if (!this.context) {
const context = new AudioContext();
const destination = context.createMediaStreamDestination();
const element: SinkableElement = new Audio();
element.srcObject = destination.stream;
element.autoplay = true;
this.context = context;
this.destination = destination;
this.element = element;
if (this.outputDeviceId && typeof element.setSinkId === "function") {
element.setSinkId(this.outputDeviceId).catch(() => {});
}
}
return { context: this.context, destination: this.destination! };
}
async setOutputDevice(deviceId: string): Promise<void> {
this.outputDeviceId = deviceId;
if (this.element && typeof this.element.setSinkId === "function") {
await this.element.setSinkId(deviceId).catch(() => {});
}
}
async playBlob(blob: Blob, volume: number): Promise<void> {
const { context, destination } = this.ensure();
if (context.state === "suspended") await context.resume().catch(() => {});
const arrayBuffer = await blob.arrayBuffer();
const audioBuffer = await context.decodeAudioData(arrayBuffer);
const source = context.createBufferSource();
source.buffer = audioBuffer;
const gain = context.createGain();
gain.gain.value = volume;
source.connect(gain).connect(destination);
source.start();
}
playSynth(event: SoundEventId, volume: number): void {
const { context, destination } = this.ensure();
if (context.state === "suspended") context.resume().catch(() => {});
const now = context.currentTime;
for (const note of synthNotes(event)) {
this.playNote(context, destination, now + note.delay, note.freq, note.duration, volume * note.gain);
}
}
private playNote(
context: AudioContext,
destination: AudioNode,
startTime: number,
freq: number,
duration: number,
peakGain: number
): void {
const osc = context.createOscillator();
osc.type = "sine";
osc.frequency.value = freq;
const gain = context.createGain();
gain.gain.setValueAtTime(0, startTime);
gain.gain.linearRampToValueAtTime(peakGain, startTime + 0.02);
gain.gain.exponentialRampToValueAtTime(0.0001, startTime + duration);
osc.connect(gain).connect(destination);
osc.start(startTime);
osc.stop(startTime + duration + 0.05);
}
}
/** Soft, modern two/three-note chimes - a sine-wave, quick-attack/exponential-decay
* shape reads as gentle rather than the harsh square/saw beeps of classic UI sounds. */
function synthNotes(event: SoundEventId): { delay: number; freq: number; duration: number; gain: number }[] {
switch (event) {
case "connect":
return [
{ delay: 0, freq: 523.25, duration: 0.16, gain: 0.5 },
{ delay: 0.09, freq: 783.99, duration: 0.22, gain: 0.5 },
];
case "disconnect":
return [
{ delay: 0, freq: 659.25, duration: 0.16, gain: 0.45 },
{ delay: 0.09, freq: 440.0, duration: 0.24, gain: 0.45 },
];
case "clientJoin":
return [{ delay: 0, freq: 880.0, duration: 0.14, gain: 0.4 }];
case "clientLeave":
return [{ delay: 0, freq: 587.33, duration: 0.16, gain: 0.4 }];
case "message":
return [
{ delay: 0, freq: 987.77, duration: 0.09, gain: 0.35 },
{ delay: 0.06, freq: 1318.51, duration: 0.12, gain: 0.3 },
];
case "poke":
return [
{ delay: 0, freq: 987.77, duration: 0.1, gain: 0.5 },
{ delay: 0.12, freq: 987.77, duration: 0.1, gain: 0.5 },
];
}
}
const player = new NotificationSoundPlayer();
export function setSoundsOutputDevice(deviceId: string): void {
void player.setOutputDevice(deviceId);
}
export async function playSound(event: SoundEventId): Promise<void> {
if (!loadSoundsEnabled()) return;
const volume = loadSoundsVolume();
const custom = await loadCustomSound(event).catch(() => undefined);
if (custom) {
try {
await player.playBlob(custom.blob, volume);
return;
} catch {
// Stored file failed to decode (corrupted/unsupported) - fall back to the default chime.
}
}
player.playSynth(event, volume);
}