traffic light: every color has its own buzz sound volume

This commit is contained in:
Joeri Exelmans 2025-11-01 11:36:18 +01:00
parent 5dbe51d871
commit 254dbaf2fd
2 changed files with 18 additions and 13 deletions

View file

@ -40,21 +40,23 @@ export const TrafficLight = memo(function TrafficLight({state, speed, raiseUIEve
// preloadAudio(sndAtmosphere);
// the traffic light makes sound too:
// play wind
useEffect(() => {
const stopPlaying = playURL(sndAtmosphere, true);
return () => stopPlaying();
}, []);
useEffect(() => {
if (redOn || yellowOn || greenOn) {
const stopPlaying = playURL(sndBuzz, true);
return () => {
stopPlaying();
};
}
else return () => {};
}, [redOn || yellowOn || greenOn])
// for added realism, every light color has its own buzzing noise volume
for (const [color, gain] of [[redOn, 0.5], [yellowOn, 1], [greenOn, 0.3]] as [boolean, number][]) {
useEffect(() => {
if (color) {
const stopPlaying = playURL(sndBuzz, true, gain);
return () => {
stopPlaying();
};
}
}, [color]);
}
return <>
<style>{`

View file

@ -28,12 +28,15 @@ export function useAudioContext(speed: number) {
.then(buf => ref.current!.ctx.decodeAudioData(buf));
}), [ref.current]);
function play(url: string, loop: boolean) {
function play(url: string, loop: boolean, gain: number = 1) {
const srcPromise = url2AudioBuf(url)
.then(audioBuf => {
const src = ref.current!.ctx.createBufferSource();
const gainNode = ref.current!.ctx.createGain();
gainNode.gain.value = gain;
gainNode.connect(ref.current!.hipass);
src.buffer = audioBuf;
src.connect(ref.current!.hipass);
src.connect(gainNode);
src.playbackRate.value = speed;
src.loop = loop;
src.start();
@ -59,5 +62,5 @@ export function useAudioContext(speed: number) {
}
}, [speed]);
return [play, url2AudioBuf] as [(url: string, loop: boolean) => ()=>void, (url:string)=>void];
return [play, url2AudioBuf] as [(url: string, loop: boolean, gain?: number) => ()=>void, (url:string)=>void];
}