Reduce update frequency for volume

This commit is contained in:
Half-Shot
2024-12-03 13:16:43 +00:00
parent c3cf755fc4
commit 3d89b1033d
3 changed files with 52 additions and 35 deletions

View File

@@ -16,6 +16,9 @@ interface Props {
className?: string; className?: string;
label: string; label: string;
value: number; value: number;
/**
* Event handler called when the value changes during an interaction.
*/
onValueChange: (value: number) => void; onValueChange: (value: number) => void;
/** /**
* Event handler called when the value changes at the end of an interaction. * Event handler called when the value changes at the end of an interaction.
@@ -45,7 +48,7 @@ export const Slider: FC<Props> = ({
disabled, disabled,
}) => { }) => {
const onValueChange = useCallback( const onValueChange = useCallback(
([v]: number[]) => onValueChangeProp(v), ([v]: number[]) => onValueChangeProp?.(v),
[onValueChangeProp], [onValueChangeProp],
); );
const onValueCommit = useCallback( const onValueCommit = useCallback(

View File

@@ -6,7 +6,7 @@ Please see LICENSE in the repository root for full details.
*/ */
import { ReactNode, useEffect, useMemo, useRef, useState } from "react"; import { ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { filter, interval, throttle } from "rxjs"; import { filter, interval, skip, throttle } from "rxjs";
import { logger } from "matrix-js-sdk/src/logger"; import { logger } from "matrix-js-sdk/src/logger";
import { import {
@@ -19,6 +19,7 @@ import joinCallSoundOgg from "../sound/join_call.ogg";
import leftCallSoundMp3 from "../sound/left_call.mp3"; import leftCallSoundMp3 from "../sound/left_call.mp3";
import leftCallSoundOgg from "../sound/left_call.ogg"; import leftCallSoundOgg from "../sound/left_call.ogg";
import { useMediaDevices } from "../livekit/MediaDevicesContext"; import { useMediaDevices } from "../livekit/MediaDevicesContext";
import { useLatest } from "../useLatest";
// Do not play any sounds if the participant count has exceeded this // Do not play any sounds if the participant count has exceeded this
// number. // number.
@@ -35,13 +36,19 @@ async function loadAudioBuffer(filename: string) {
return await await response.arrayBuffer(); return await await response.arrayBuffer();
} }
function playSound(ctx?: AudioContext, buffer?: AudioBuffer): void { function playSound(
volume: number,
ctx?: AudioContext,
buffer?: AudioBuffer,
): void {
if (!ctx || !buffer) { if (!ctx || !buffer) {
return; return;
} }
const gain = ctx.createGain();
gain.gain.setValueAtTime(volume, 0);
const src = ctx.createBufferSource(); const src = ctx.createBufferSource();
src.buffer = buffer; src.buffer = buffer;
src.connect(ctx.destination); src.connect(gain).connect(ctx.destination);
src.start(); src.start();
} }
@@ -50,12 +57,13 @@ function getPreferredAudioFormat() {
if (a.canPlayType("audio/ogg") === "maybe") { if (a.canPlayType("audio/ogg") === "maybe") {
return "ogg"; return "ogg";
} }
// Otherwise just assume MP3, as that's a // Otherwise just assume MP3, as that has a chance of being more widely supported.
return "mp3"; return "mp3";
} }
// We prefer to load these sounds ahead of time, so there
// is no delay on call join.
const preferredFormat = getPreferredAudioFormat(); const preferredFormat = getPreferredAudioFormat();
// Preload sound effects
const JoinSoundBufferPromise = loadAudioBuffer( const JoinSoundBufferPromise = loadAudioBuffer(
preferredFormat === "ogg" ? joinCallSoundOgg : joinCallSoundMp3, preferredFormat === "ogg" ? joinCallSoundOgg : joinCallSoundMp3,
); );
@@ -77,43 +85,52 @@ export function CallEventAudioRenderer({
useEffect(() => { useEffect(() => {
const ctx = new AudioContext({ const ctx = new AudioContext({
// We want low latency for these effects.
latencyHint: "interactive", latencyHint: "interactive",
// XXX: Types don't include this yet. // XXX: Types don't include this yet.
...{ sinkId: devices.audioOutput.selectedId }, ...{ sinkId: devices.audioOutput.selectedId },
}); });
const controller = new AbortController(); const controller = new AbortController();
(async () => { (async () => {
if (controller.signal.aborted) { controller.signal.throwIfAborted();
return;
}
const enterCall = await ctx.decodeAudioData( const enterCall = await ctx.decodeAudioData(
(await JoinSoundBufferPromise).slice(0), (await JoinSoundBufferPromise).slice(0),
); );
if (controller.signal.aborted) { controller.signal.throwIfAborted();
return;
}
const leaveCall = await ctx.decodeAudioData( const leaveCall = await ctx.decodeAudioData(
(await LeftSoundBufferPromise).slice(0), (await LeftSoundBufferPromise).slice(0),
); );
if (controller.signal.aborted) { controller.signal.throwIfAborted();
return;
}
setJoinSoundNode(enterCall); setJoinSoundNode(enterCall);
setLeaveSoundNode(leaveCall); setLeaveSoundNode(leaveCall);
if (controller.signal.aborted) { })().catch((ex) => {
return; logger.debug("Failed to setup audio context", ex);
} });
})();
setAudioContext(ctx); setAudioContext(ctx);
return () => { return () => {
controller.abort("Closing"); controller.abort("Closing");
void ctx.close().catch((ex) => { void ctx.close().catch((ex) => {
logger.warn("Failed to close audio engine", ex); logger.debug("Failed to close audio engine", ex);
}); });
setAudioContext(undefined); setAudioContext(undefined);
}; };
}, [devices.audioOutput]); }, []);
// Update the sink ID whenever we change devices.
useEffect(() => {
if (audioContext && "setSinkId" in audioContext) {
// setSinkId doesn't exist in types but does exist for some browsers.
// https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/setSinkId
// @ts-ignore
audioContext.setSinkId(devices.audioOutput.selectedId).catch((ex) => {
logger.warn("Unable to change sink for audio context", ex);
});
}
}, [audioContext, devices]);
// Prevent a rerender when t he
const soundVolume = useLatest(effectSoundVolume);
useEffect(() => { useEffect(() => {
const joinSub = vm.memberChanges const joinSub = vm.memberChanges
@@ -128,7 +145,7 @@ export function CallEventAudioRenderer({
throttle((_) => interval(DEBOUNCE_SOUND_EFFECT_MS)), throttle((_) => interval(DEBOUNCE_SOUND_EFFECT_MS)),
) )
.subscribe(() => { .subscribe(() => {
playSound(audioContext, joinCallBuffer); playSound(soundVolume.current, audioContext, joinCallBuffer);
}); });
const leftSub = vm.memberChanges const leftSub = vm.memberChanges
@@ -140,21 +157,14 @@ export function CallEventAudioRenderer({
throttle((_) => interval(DEBOUNCE_SOUND_EFFECT_MS)), throttle((_) => interval(DEBOUNCE_SOUND_EFFECT_MS)),
) )
.subscribe(() => { .subscribe(() => {
playSound(audioContext, leaveCallBuffer); playSound(soundVolume.current, audioContext, leaveCallBuffer);
}); });
return (): void => { return (): void => {
joinSub.unsubscribe(); joinSub.unsubscribe();
leftSub.unsubscribe(); leftSub.unsubscribe();
}; };
}, [joinCallBuffer, leaveCallBuffer, vm]); }, [joinCallBuffer, leaveCallBuffer, soundVolume, vm]);
// Set volume.
useEffect(() => {
if (audioSourceElement.current) {
audioSourceElement.current.volume = effectSoundVolume;
}
}, [effectSoundVolume]);
return <audio ref={audioSourceElement} hidden />; return <audio ref={audioSourceElement} hidden />;
} }

View File

@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only
Please see LICENSE in the repository root for full details. Please see LICENSE in the repository root for full details.
*/ */
import { ChangeEvent, FC, useCallback } from "react"; import { ChangeEvent, FC, useCallback, useEffect, useState } from "react";
import { Trans, useTranslation } from "react-i18next"; import { Trans, useTranslation } from "react-i18next";
import { MatrixClient } from "matrix-js-sdk/src/matrix"; import { MatrixClient } from "matrix-js-sdk/src/matrix";
import { Root as Form, Text } from "@vector-im/compound-web"; import { Root as Form, Text } from "@vector-im/compound-web";
@@ -83,8 +83,11 @@ export const SettingsModal: FC<Props> = ({
const devices = useMediaDevices(); const devices = useMediaDevices();
useMediaDeviceNames(devices, open); useMediaDeviceNames(devices, open);
const [soundVolume, setSoundVolume] = useSetting(soundEffectVolumeSetting); const [soundVolume, setSoundVolume] = useSetting(soundEffectVolumeSetting);
const [soundVolumeRaw, setSoundVolumeRaw] = useState(soundVolume);
// Debounce saving the sound volume as it triggers certain components to reload.
useEffect(() => {});
const audioTab: Tab<SettingsTab> = { const audioTab: Tab<SettingsTab> = {
key: "audio", key: "audio",
@@ -107,8 +110,9 @@ export const SettingsModal: FC<Props> = ({
<p>{t("settings.audio_tab.effect_volume_description")}</p> <p>{t("settings.audio_tab.effect_volume_description")}</p>
<Slider <Slider
label={t("video_tile.volume")} label={t("video_tile.volume")}
value={soundVolume} value={soundVolumeRaw}
onValueChange={setSoundVolume} onValueChange={setSoundVolumeRaw}
onValueCommit={setSoundVolume}
min={0} min={0}
max={1} max={1}
step={0.01} step={0.01}