glitchier-soc/app/javascript/flavours/glitch/store/middlewares/sounds.ts
Renaud Chaput e5f09f145a [Glitch] Upgrade to typescript-eslint v6
Port a09ed92a77 to glitch-soc

Signed-off-by: Claire <claire.github-309c@sitedethib.com>
2023-07-13 14:51:24 +02:00

67 lines
1.4 KiB
TypeScript

import type { Middleware, AnyAction } from 'redux';
import ready from 'flavours/glitch/ready';
import { assetHost } from 'flavours/glitch/utils/config';
import type { RootState } from '..';
interface AudioSource {
src: string;
type: string;
}
const createAudio = (sources: AudioSource[]) => {
const audio = new Audio();
sources.forEach(({ type, src }) => {
const source = document.createElement('source');
source.type = type;
source.src = src;
audio.appendChild(source);
});
return audio;
};
const play = (audio: HTMLAudioElement) => {
if (!audio.paused) {
audio.pause();
if (typeof audio.fastSeek === 'function') {
audio.fastSeek(0);
} else {
audio.currentTime = 0;
}
}
void audio.play();
};
export const soundsMiddleware = (): Middleware<
Record<string, never>,
RootState
> => {
const soundCache: Record<string, HTMLAudioElement> = {};
void ready(() => {
soundCache.boop = createAudio([
{
src: `${assetHost}/sounds/boop.ogg`,
type: 'audio/ogg',
},
{
src: `${assetHost}/sounds/boop.mp3`,
type: 'audio/mpeg',
},
]);
});
return () =>
(next) =>
(action: AnyAction & { meta?: { sound?: string } }) => {
const sound = action.meta?.sound;
if (sound && Object.hasOwn(soundCache, sound)) {
play(soundCache[sound]);
}
return next(action);
};
};