Wire up the real Wiedergabe/Aufnahme options panels

Builds out the Wiedergabe and Aufnahme sections of the Options dialog to
match the real TS3 client's layout, with the "Standard" profile only.
Everything technically feasible in a browser is wired to real behavior:
output/input device pickers (input device selection is new - MicCapture
can now target a specific deviceId), playback volume (new gain stage in
AudioPlayer), a real test tone, the voice-activation threshold/hangover
(hangover was previously hardcoded), noise suppression/echo cancellation
toggles (restart capture to apply new getUserMedia constraints), a live
mic level meter, and a mic self-monitoring ("Test starten") loopback.
Settings persist to localStorage. Everything the browser genuinely can't
do (Windows audio session mode, mono/surround downmix, ducking, typing
attenuation, mic-click sounds, comfort noise) stays as a disabled
placeholder control. Local-only for now, not deployed.
This commit is contained in:
Moepchi committed 2026-07-29 21:43:47 +02:00
1 parent e5c5cc3f80
commit 0f24c4b092
3 files changed
+680 -30

No files matched your search

+168
View File
@@ -847,6 +847,174 @@
color: var(--text-muted);
}
.ts-options-subtitle {
font-size: 11px;
color: var(--text-muted);
margin: 0 0 0.75rem;
}
.ts-options-columns {
display: flex;
gap: 1rem;
}
.ts-options-profile-list {
width: 110px;
flex-shrink: 0;
list-style: none;
margin: 0;
padding: 0;
}
.ts-options-profile-item-active {
padding: 0.3rem 0.4rem;
border-radius: 2px;
font-size: 12px;
background: var(--row-hover);
outline: 1px solid var(--border);
}
.ts-options-fields {
flex: 1;
display: flex;
flex-direction: column;
gap: 0.6rem;
min-width: 0;
}
.ts-options-field {
display: flex;
flex-direction: column;
gap: 0.2rem;
font-size: 11px;
color: var(--text-muted);
}
.ts-options-field select,
.ts-options-field-inline input {
background: var(--input-bg);
color: var(--text);
border: 1px solid var(--border);
border-radius: 2px;
padding: 0.3rem;
font-size: 12px;
}
.ts-options-field select:disabled {
opacity: 0.6;
}
.ts-options-slider-row {
display: flex;
justify-content: space-between;
font-size: 11px;
color: var(--text-muted);
}
.ts-options-slider-label {
font-weight: 600;
color: var(--text);
}
.ts-options-slider-with-value {
display: flex;
align-items: center;
gap: 0.5rem;
}
.ts-options-slider-with-value input[type="range"] {
flex: 1;
}
.ts-options-db-value {
font-size: 11px;
color: var(--text-muted);
width: 4.5em;
text-align: right;
}
.ts-options-fieldset {
border: 1px solid var(--border-soft);
border-radius: 4px;
padding: 0.5rem 0.75rem 0.75rem;
margin: 0;
}
.ts-options-fieldset legend {
font-size: 11px;
color: var(--text-muted);
padding: 0 0.3rem;
}
.ts-options-checkbox,
.ts-options-radio {
display: flex;
align-items: center;
gap: 0.4rem;
font-size: 12px;
padding: 0.15rem 0;
}
.ts-options-dsp-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.2rem 1rem;
}
.ts-options-level-wrap {
position: relative;
margin: 0.5rem 0;
}
.ts-options-level-track {
height: 8px;
border-radius: 4px;
background: var(--input-bg);
border: 1px solid var(--border-soft);
overflow: hidden;
}
.ts-options-level-fill {
height: 100%;
background: var(--accent);
transition: width 0.05s linear;
}
.ts-options-level-threshold {
width: 100%;
margin-top: 0.3rem;
}
.ts-options-field-row {
display: flex;
align-items: center;
gap: 0.5rem;
}
.ts-options-field-inline {
display: flex;
align-items: center;
gap: 0.3rem;
font-size: 11px;
color: var(--text-muted);
}
.ts-options-field-inline input[type="number"] {
width: 4em;
}
.ts-options-test-dot {
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--border);
display: inline-block;
}
.ts-options-test-dot-on {
background: #4caf50;
}
.ts-dialog-titlebar {
display: flex;
align-items: center;
+420 -21
View File
@@ -5,6 +5,7 @@ import {
MicCapture,
SAMPLE_RATE,
hasNativeOutputPicker,
listAudioInputDevices,
listAudioOutputDevices,
pickAudioOutputDevice,
} from "./voice";
@@ -19,6 +20,22 @@ const GATEWAY_URL = import.meta.env.DEV
const LAST_HOST_KEY = "ts-web-client:last-host";
const LAST_NICKNAME_KEY = "ts-web-client:last-nickname";
const FAVORITES_KEY = "ts-web-client:favorites";
const INPUT_DEVICE_KEY = "ts-web-client:input-device";
const PLAYBACK_VOLUME_KEY = "ts-web-client:playback-volume";
const NOISE_SUPPRESSION_KEY = "ts-web-client:noise-suppression";
const ECHO_CANCELLATION_KEY = "ts-web-client:echo-cancellation";
const VAD_HANGOVER_KEY = "ts-web-client:vad-hangover";
function loadBoolPref(key: string, fallback: boolean): boolean {
const raw = localStorage.getItem(key);
return raw === null ? fallback : raw === "1";
}
function loadNumberPref(key: string, fallback: number): number {
const raw = localStorage.getItem(key);
const parsed = raw === null ? NaN : Number(raw);
return Number.isFinite(parsed) ? parsed : fallback;
}
interface Favorite {
id: string;
@@ -751,14 +768,260 @@ const OPTIONS_SECTIONS = [
{ id: "meldungen", icon: "ℹ️", label: "Meldungen" },
] as const;
interface AudioSettings {
outputDevices: MediaDeviceInfo[];
outputDeviceId: string;
onOutputDeviceChange: (id: string, label?: string) => void;
onRefreshOutputDevices: () => void;
playbackVolume: number;
onPlaybackVolumeChange: (v: number) => void;
onPlayTestTone: () => void;
inputDevices: MediaDeviceInfo[];
inputDeviceId: string;
onInputDeviceChange: (id: string) => void;
onRefreshInputDevices: () => void;
micOn: boolean;
micLevelRef: React.MutableRefObject<number>;
micTestOn: boolean;
onToggleMicTest: () => void;
vadThreshold: number;
onVadThresholdChange: (v: number) => void;
vadHangover: number;
onVadHangoverChange: (v: number) => void;
noiseSuppressionEnabled: boolean;
onToggleNoiseSuppression: () => void;
echoCancellationEnabled: boolean;
onToggleEchoCancellation: () => void;
}
function MicLevelBar({ levelRef, active }: { levelRef: React.MutableRefObject<number>; active: boolean }) {
const [level, setLevel] = useState(0);
useEffect(() => {
if (!active) {
setLevel(0);
return;
}
let raf = 0;
const tick = () => {
setLevel(levelRef.current);
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [active, levelRef]);
const pct = Math.min(100, Math.round((level / 0.2) * 100));
return (
<div className="ts-options-level-track">
<div className="ts-options-level-fill" style={{ width: `${pct}%` }} />
</div>
);
}
function WiedergabePanel({ audio }: { audio: AudioSettings }) {
const volumeDb = Math.round(20 * Math.log10(audio.playbackVolume || 0.001) * 10) / 10;
return (
<>
<h3>Wiedergabe</h3>
<p className="ts-options-subtitle">Ändern der Wiedergabeeinstellungen</p>
<div className="ts-options-field-row">
<label>Profile</label>
</div>
<div className="ts-options-columns">
<ul className="ts-options-profile-list">
<li className="ts-options-profile-item-active">Standard</li>
</ul>
<div className="ts-options-fields">
<label className="ts-options-field">
Wiedergabemodus:
<select disabled value="wasapi">
<option value="wasapi">Windows Audio Session</option>
</select>
</label>
<label className="ts-options-field">
Wiedergabegerät:
<select
value={audio.outputDeviceId}
onFocus={audio.onRefreshOutputDevices}
onChange={(e) => audio.onOutputDeviceChange(e.target.value)}
>
<option value="">System default</option>
{audio.outputDevices.map((d) => (
<option key={d.deviceId} value={d.deviceId}>
{d.label || `Output ${d.deviceId.slice(0, 6)}`}
</option>
))}
</select>
</label>
<div className="ts-options-slider-row">
<span>Leise</span>
<span className="ts-options-slider-label">Sprachlautstärke</span>
<span>Laut</span>
</div>
<div className="ts-options-slider-with-value">
<input
type="range"
min={0}
max={2}
step={0.02}
value={audio.playbackVolume}
onChange={(e) => audio.onPlaybackVolumeChange(Number(e.target.value))}
/>
<span className="ts-options-db-value">
{volumeDb > 0 ? "+" : ""}
{volumeDb} dB
</span>
</div>
<button onClick={audio.onPlayTestTone}>▶ Test Ton abspielen</button>
<fieldset className="ts-options-fieldset">
<legend>Optionen</legend>
<label className="ts-options-checkbox">
<input type="checkbox" checked disabled readOnly />
Automatische Lautstärkeanpassung
</label>
<label className="ts-options-checkbox">
<input type="checkbox" checked disabled readOnly />
Eigener Client spielt Mikro Klicks
</label>
<label className="ts-options-checkbox">
<input type="checkbox" disabled readOnly />
Client 3D Positionen immer setzen wenn verfügbar
</label>
<label className="ts-options-checkbox">
<input type="checkbox" disabled readOnly />
Andere Clients spielen Mikro Klicks
</label>
<label className="ts-options-checkbox">
<input type="checkbox" disabled readOnly />
Comfort noise
</label>
</fieldset>
</div>
</div>
</>
);
}
function AufnahmePanel({ audio }: { audio: AudioSettings }) {
return (
<>
<h3>Aufnahme</h3>
<p className="ts-options-subtitle">Ändern der Aufnahmeeinstellungen</p>
<div className="ts-options-columns">
<ul className="ts-options-profile-list">
<li className="ts-options-profile-item-active">Standard</li>
</ul>
<div className="ts-options-fields">
<label className="ts-options-field">
Aufnahmemodus:
<select disabled value="wasapi">
<option value="wasapi">Windows Audio Session</option>
</select>
</label>
<label className="ts-options-field">
Aufnahmegerät:
<select
value={audio.inputDeviceId}
onFocus={audio.onRefreshInputDevices}
onChange={(e) => audio.onInputDeviceChange(e.target.value)}
>
<option value="">System default</option>
{audio.inputDevices.map((d) => (
<option key={d.deviceId} value={d.deviceId}>
{d.label || `Input ${d.deviceId.slice(0, 6)}`}
</option>
))}
</select>
</label>
<fieldset className="ts-options-fieldset">
<legend>Activation</legend>
<label className="ts-options-radio">
<input type="radio" name="activation" disabled readOnly />
Push-To-Talk
</label>
<label className="ts-options-radio">
<input type="radio" name="activation" disabled readOnly />
Dauersenden
</label>
<label className="ts-options-radio">
<input type="radio" name="activation" checked readOnly />
Automatische Spracherkennung
</label>
<div className="ts-options-level-wrap">
<MicLevelBar levelRef={audio.micLevelRef} active={audio.micOn} />
<input
className="ts-options-level-threshold"
type="range"
min={0.002}
max={0.15}
step={0.002}
value={audio.vadThreshold}
onChange={(e) => audio.onVadThresholdChange(Number(e.target.value))}
/>
</div>
<div className="ts-options-field-row">
<button onClick={audio.onToggleMicTest} disabled={!audio.micOn}>
{audio.micTestOn ? "Test beenden" : "Test starten"}
</button>
<span className={`ts-options-test-dot${audio.micTestOn ? " ts-options-test-dot-on" : ""}`} />
<label className="ts-options-field-inline">
Abschaltverzögerung:
<input
type="number"
min={0}
max={2}
step={0.1}
value={audio.vadHangover}
onChange={(e) => audio.onVadHangoverChange(Number(e.target.value))}
/>
Sek
</label>
</div>
</fieldset>
<fieldset className="ts-options-fieldset">
<legend>Digital Signal Processing</legend>
<div className="ts-options-dsp-grid">
<label className="ts-options-checkbox">
<input type="checkbox" disabled readOnly />
Typing attenuation
</label>
<label className="ts-options-checkbox">
<input
type="checkbox"
checked={audio.echoCancellationEnabled}
onChange={audio.onToggleEchoCancellation}
/>
Echo Dämpfung
</label>
<label className="ts-options-checkbox">
<input
type="checkbox"
checked={audio.noiseSuppressionEnabled}
onChange={audio.onToggleNoiseSuppression}
/>
Hintergrundgeräusche entfernen
</label>
<label className="ts-options-checkbox">
<input type="checkbox" disabled readOnly />
Echo Abschwächung (Ducking)
</label>
</div>
</fieldset>
</div>
</div>
</>
);
}
function OptionsDialog({
section,
onSectionChange,
onClose,
audio,
}: {
section: string;
onSectionChange: (id: string) => void;
onClose: () => void;
audio: AudioSettings;
}) {
const active = OPTIONS_SECTIONS.find((s) => s.id === section) ?? OPTIONS_SECTIONS[0];
return (
@@ -784,8 +1047,16 @@ function OptionsDialog({
))}
</div>
<div className="ts-options-content">
<h3>{active.label}</h3>
<p className="ts-options-placeholder">Diese Einstellungen sind noch nicht implementiert.</p>
{active.id === "wiedergabe" ? (
<WiedergabePanel audio={audio} />
) : active.id === "aufnahme" ? (
<AufnahmePanel audio={audio} />
) : (
<>
<h3>{active.label}</h3>
<p className="ts-options-placeholder">Diese Einstellungen sind noch nicht implementiert.</p>
</>
)}
</div>
</div>
<div className="ts-dialog-buttons">
@@ -836,9 +1107,20 @@ function App() {
const [talkers, setTalkers] = useState<Set<number>>(new Set());
const [selfActive, setSelfActive] = useState(false);
const [vadThreshold, setVadThreshold] = useState(0.02);
const [vadHangover, setVadHangover] = useState(() => loadNumberPref(VAD_HANGOVER_KEY, 0.3));
const [outputDevices, setOutputDevices] = useState<MediaDeviceInfo[]>([]);
const [outputDeviceId, setOutputDeviceId] = useState("");
const [outputDeviceLabel, setOutputDeviceLabel] = useState("System default");
const [inputDevices, setInputDevices] = useState<MediaDeviceInfo[]>([]);
const [inputDeviceId, setInputDeviceId] = useState(() => localStorage.getItem(INPUT_DEVICE_KEY) ?? "");
const [playbackVolume, setPlaybackVolume] = useState(() => loadNumberPref(PLAYBACK_VOLUME_KEY, 1));
const [noiseSuppressionEnabled, setNoiseSuppressionEnabled] = useState(() =>
loadBoolPref(NOISE_SUPPRESSION_KEY, true)
);
const [echoCancellationEnabled, setEchoCancellationEnabled] = useState(() =>
loadBoolPref(ECHO_CANCELLATION_KEY, true)
);
const [micTestOn, setMicTestOn] = useState(false);
const [connectionsMenuOpen, setConnectionsMenuOpen] = useState(false);
const [favorites, setFavorites] = useState<Favorite[]>(() => loadFavorites());
const [favoritesMenuOpen, setFavoritesMenuOpen] = useState(false);
@@ -866,6 +1148,7 @@ function App() {
const pokeIdRef = useRef(0);
const inputMutedRef = useRef(false);
const outputMutedRef = useRef(false);
const micLevelRef = useRef(0);
useEffect(() => {
chatEndRef.current?.scrollIntoView({ block: "nearest" });
@@ -881,6 +1164,28 @@ function App() {
if (micCaptureRef.current) micCaptureRef.current.threshold = vadThreshold;
}, [vadThreshold]);
useEffect(() => {
if (micCaptureRef.current) micCaptureRef.current.hangoverSeconds = vadHangover;
localStorage.setItem(VAD_HANGOVER_KEY, String(vadHangover));
}, [vadHangover]);
useEffect(() => {
audioPlayerRef.current?.setVolume(playbackVolume);
localStorage.setItem(PLAYBACK_VOLUME_KEY, String(playbackVolume));
}, [playbackVolume]);
useEffect(() => {
localStorage.setItem(NOISE_SUPPRESSION_KEY, noiseSuppressionEnabled ? "1" : "0");
}, [noiseSuppressionEnabled]);
useEffect(() => {
localStorage.setItem(ECHO_CANCELLATION_KEY, echoCancellationEnabled ? "1" : "0");
}, [echoCancellationEnabled]);
useEffect(() => {
if (inputDeviceId) localStorage.setItem(INPUT_DEVICE_KEY, inputDeviceId);
}, [inputDeviceId]);
useEffect(() => {
activeTabRef.current = activeTab;
if (activeTab !== "channel") {
@@ -901,9 +1206,22 @@ function App() {
}
};
const refreshInputDevices = async () => {
try {
const devices = await listAudioInputDevices();
setInputDevices(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);
const refreshBoth = () => {
void refreshOutputDevices();
void refreshInputDevices();
};
navigator.mediaDevices?.addEventListener?.("devicechange", refreshBoth);
return () => navigator.mediaDevices?.removeEventListener?.("devicechange", refreshBoth);
}, []);
useEffect(() => {
@@ -1250,25 +1568,52 @@ function App() {
return () => window.removeEventListener("keydown", onKeyDown);
}, [connected, connecting, host, nickname, serverPassword, defaultChannel, channelPassword]);
// Overrides let a device/DSP-setting change take effect immediately, without
// waiting for the next render's (possibly still-stale) state closure.
const startMic = async (overrides?: {
deviceId?: string;
echoCancellation?: boolean;
noiseSuppression?: boolean;
}) => {
const audioContext = ensureAudioContext();
try {
const mic = new MicCapture(audioContext, {
onFrame: (pcm) => {
if (!inputMutedRef.current) socketRef.current?.send(JSON.stringify({ type: "sendAudio", pcm }));
},
onActivity: (active) => setSelfActive(active),
onLevel: (rms) => {
micLevelRef.current = rms;
},
threshold: vadThreshold,
hangoverSeconds: vadHangover,
deviceId: overrides?.deviceId ?? (inputDeviceId || undefined),
echoCancellation: overrides?.echoCancellation ?? echoCancellationEnabled,
noiseSuppression: overrides?.noiseSuppression ?? noiseSuppressionEnabled,
});
await mic.start();
micCaptureRef.current = mic;
setMicOn(true);
refreshOutputDevices();
refreshInputDevices();
} catch (error) {
appendLog({ text: `Microphone error: ${(error as Error).message}`, kind: "error" });
}
};
const restartMic = async (overrides?: {
deviceId?: string;
echoCancellation?: boolean;
noiseSuppression?: boolean;
}) => {
micCaptureRef.current?.stop();
micCaptureRef.current = null;
await startMic(overrides);
};
const handleToggleMic = async () => {
if (!micOn) {
const audioContext = ensureAudioContext();
try {
const mic = new MicCapture(
audioContext,
(pcm) => {
if (!inputMutedRef.current) 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" });
}
await startMic();
return;
}
socketRef.current?.send(JSON.stringify({ type: "setInputMuted", muted: !inputMutedRef.current }));
@@ -1284,6 +1629,30 @@ function App() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleInputDeviceChange = (deviceId: string) => {
setInputDeviceId(deviceId);
if (micCaptureRef.current) void restartMic({ deviceId });
};
const handleToggleNoiseSuppression = () => {
const next = !noiseSuppressionEnabled;
setNoiseSuppressionEnabled(next);
if (micCaptureRef.current) void restartMic({ noiseSuppression: next });
};
const handleToggleEchoCancellation = () => {
const next = !echoCancellationEnabled;
setEchoCancellationEnabled(next);
if (micCaptureRef.current) void restartMic({ echoCancellation: next });
};
const handleToggleMicTest = () => {
const next = !micTestOn;
setMicTestOn(next);
const inputNode = audioPlayerRef.current?.getInputNode();
if (inputNode) micCaptureRef.current?.setMonitoring(next, inputNode);
};
const handleToggleOutputMuted = () => {
socketRef.current?.send(JSON.stringify({ type: "setOutputMuted", muted: !outputMutedRef.current }));
};
@@ -1303,6 +1672,11 @@ function App() {
}
};
const handlePlayTestTone = () => {
ensureAudioContext();
audioPlayerRef.current?.playTestTone();
};
const handleSwitchChannel = (channelId: number) => {
socketRef.current?.send(JSON.stringify({ type: "switchChannel", channelId }));
};
@@ -1705,6 +2079,31 @@ function App() {
section={optionsSection}
onSectionChange={setOptionsSection}
onClose={() => setOptionsDialogOpen(false)}
audio={{
outputDevices,
outputDeviceId,
onOutputDeviceChange: handleOutputDeviceChange,
onRefreshOutputDevices: refreshOutputDevices,
playbackVolume,
onPlaybackVolumeChange: setPlaybackVolume,
onPlayTestTone: handlePlayTestTone,
inputDevices,
inputDeviceId,
onInputDeviceChange: handleInputDeviceChange,
onRefreshInputDevices: refreshInputDevices,
micOn,
micLevelRef,
micTestOn,
onToggleMicTest: handleToggleMicTest,
vadThreshold,
onVadThresholdChange: setVadThreshold,
vadHangover,
onVadHangoverChange: setVadHangover,
noiseSuppressionEnabled,
onToggleNoiseSuppression: handleToggleNoiseSuppression,
echoCancellationEnabled,
onToggleEchoCancellation: handleToggleEchoCancellation,
}}
/>
)}
+92 -9
View File
@@ -24,8 +24,19 @@ function base64ToInt16(b64: string): Int16Array {
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;
export interface MicCaptureOptions {
onFrame: (base64Pcm: string) => void;
onActivity?: (active: boolean) => void;
/** Reports the raw input RMS (roughly 0-1) on every processing tick, for live level meters. */
onLevel?: (rms: number) => void;
threshold?: number;
/** How long transmission continues after the level drops back below the threshold, so words aren't clipped. */
hangoverSeconds?: number;
/** `MediaDeviceInfo.deviceId` of the input device to use - omit for the system default. */
deviceId?: string;
echoCancellation?: boolean;
noiseSuppression?: boolean;
}
/**
* Captures the microphone and emits base64-encoded mono 16-bit PCM frames.
@@ -40,18 +51,31 @@ export class MicCapture {
private source: MediaStreamAudioSourceNode | null = null;
private processor: ScriptProcessorNode | null = null;
private silence: GainNode | null = null;
private monitorTarget: AudioNode | null = null;
private pending: number[] = [];
private active = false;
private activeUntil = 0;
private onFrame: (base64Pcm: string) => void;
private onActivity?: (active: boolean) => void;
private onLevel?: (rms: number) => void;
private deviceId?: string;
private echoCancellation: boolean;
private noiseSuppression: boolean;
threshold: number;
hangoverSeconds: number;
constructor(
private context: AudioContext,
private onFrame: (base64Pcm: string) => void,
private onActivity?: (active: boolean) => void,
threshold = 0.02
options: MicCaptureOptions
) {
this.threshold = threshold;
this.onFrame = options.onFrame;
this.onActivity = options.onActivity;
this.onLevel = options.onLevel;
this.threshold = options.threshold ?? 0.02;
this.hangoverSeconds = options.hangoverSeconds ?? 0.3;
this.deviceId = options.deviceId;
this.echoCancellation = options.echoCancellation ?? true;
this.noiseSuppression = options.noiseSuppression ?? true;
}
async start(): Promise<void> {
@@ -59,7 +83,12 @@ export class MicCapture {
throw new Error("Microphone access requires HTTPS (or localhost) - the site is not a secure context.");
}
this.stream = await navigator.mediaDevices.getUserMedia({
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true },
audio: {
channelCount: 1,
echoCancellation: this.echoCancellation,
noiseSuppression: this.noiseSuppression,
...(this.deviceId ? { deviceId: { exact: this.deviceId } } : {}),
},
});
// Granting the permission prompt counts as a user gesture, so this can
// succeed even when start() was triggered automatically on page load,
@@ -73,9 +102,10 @@ export class MicCapture {
let sumSquares = 0;
for (let i = 0; i < input.length; i++) sumSquares += input[i] * input[i];
const rms = Math.sqrt(sumSquares / input.length);
this.onLevel?.(rms);
const now = this.context.currentTime;
if (rms >= this.threshold) this.activeUntil = now + VAD_HANGOVER_SECONDS;
if (rms >= this.threshold) this.activeUntil = now + this.hangoverSeconds;
const shouldBeActive = now < this.activeUntil;
if (shouldBeActive !== this.active) {
this.active = shouldBeActive;
@@ -105,7 +135,22 @@ export class MicCapture {
this.silence.connect(this.context.destination);
}
/** Routes the raw mic signal to `destination` too, so you can hear yourself (a mic test), until disabled again. */
setMonitoring(enabled: boolean, destination: AudioNode): void {
if (!this.source) return;
if (enabled && this.monitorTarget !== destination) {
if (this.monitorTarget) this.source.disconnect(this.monitorTarget);
this.source.connect(destination);
this.monitorTarget = destination;
} else if (!enabled && this.monitorTarget) {
this.source.disconnect(this.monitorTarget);
this.monitorTarget = null;
}
}
stop(): void {
if (this.source && this.monitorTarget) this.source.disconnect(this.monitorTarget);
this.monitorTarget = null;
this.processor?.disconnect();
this.silence?.disconnect();
this.source?.disconnect();
@@ -129,6 +174,13 @@ export async function listAudioOutputDevices(): Promise<MediaDeviceInfo[]> {
return devices.filter((d) => d.kind === "audiooutput");
}
/** Input ("audioinput") devices available for the mic, e.g. for a device picker. */
export async function listAudioInputDevices(): Promise<MediaDeviceInfo[]> {
if (!navigator.mediaDevices) return [];
const devices = await navigator.mediaDevices.enumerateDevices();
return devices.filter((d) => d.kind === "audioinput");
}
type MediaDevicesWithPicker = MediaDevices & { selectAudioOutput?: () => Promise<MediaDeviceInfo> };
/** Whether the browser supports the native OS output-device picker (Chrome/Edge 105+). */
@@ -169,9 +221,12 @@ export class AudioPlayer {
private nextTime = 0;
private destination: MediaStreamAudioDestinationNode;
private element: SinkableElement;
private gain: GainNode;
constructor(private context: AudioContext) {
this.destination = context.createMediaStreamDestination();
this.gain = context.createGain();
this.gain.connect(this.destination);
this.element = document.createElement("audio") as SinkableElement;
this.element.autoplay = true;
this.element.srcObject = this.destination.stream;
@@ -194,7 +249,7 @@ export class AudioPlayer {
const source = this.context.createBufferSource();
source.buffer = buffer;
source.connect(this.destination);
source.connect(this.gain);
const now = this.context.currentTime;
if (this.nextTime < now + 0.02) {
@@ -210,6 +265,34 @@ export class AudioPlayer {
this.nextTime = 0;
}
/** Playback volume as linear gain (1 = unity/0dB). */
setVolume(gain: number): void {
this.gain.gain.value = gain;
}
/** The node all voice/test audio ultimately reaches - use as a mic-monitoring target so it also respects volume/output device. */
getInputNode(): AudioNode {
return this.gain;
}
/** Plays a short sine-wave test tone through the same volume/output-device routing as voice playback. */
playTestTone(): void {
const osc = this.context.createOscillator();
osc.type = "sine";
osc.frequency.value = 440;
const toneGain = this.context.createGain();
toneGain.gain.value = 0.3;
osc.connect(toneGain);
toneGain.connect(this.gain);
const now = this.context.currentTime;
osc.start(now);
osc.stop(now + 0.6);
osc.onended = () => {
osc.disconnect();
toneGain.disconnect();
};
}
/** Routes playback to a specific device (empty string = system default). */
async setOutputDevice(deviceId: string): Promise<void> {
if (typeof this.element.setSinkId === "function") {