2023-05-10 19:59:29 +09:00
|
|
|
import type { Middleware, AnyAction } from 'redux';
|
|
|
|
|
2023-07-12 10:02:32 +09:00
|
|
|
import ready from 'flavours/glitch/ready';
|
|
|
|
import { assetHost } from 'flavours/glitch/utils/config';
|
|
|
|
|
2023-05-10 19:59:29 +09:00
|
|
|
import type { RootState } from '..';
|
2023-05-09 23:56:26 +09:00
|
|
|
|
|
|
|
interface AudioSource {
|
2023-05-10 06:41:18 +09:00
|
|
|
src: string;
|
|
|
|
type: string;
|
2023-05-09 23:56:26 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
const createAudio = (sources: AudioSource[]) => {
|
2017-05-10 23:58:54 +09:00
|
|
|
const audio = new Audio();
|
|
|
|
sources.forEach(({ type, src }) => {
|
|
|
|
const source = document.createElement('source');
|
|
|
|
source.type = type;
|
|
|
|
source.src = src;
|
|
|
|
audio.appendChild(source);
|
|
|
|
});
|
|
|
|
return audio;
|
2017-05-21 00:31:47 +09:00
|
|
|
};
|
2017-05-10 23:58:54 +09:00
|
|
|
|
2023-05-09 23:56:26 +09:00
|
|
|
const play = (audio: HTMLAudioElement) => {
|
2017-03-14 01:12:30 +09:00
|
|
|
if (!audio.paused) {
|
|
|
|
audio.pause();
|
2017-10-19 00:13:51 +09:00
|
|
|
if (typeof audio.fastSeek === 'function') {
|
|
|
|
audio.fastSeek(0);
|
|
|
|
} else {
|
2018-09-07 01:33:49 +09:00
|
|
|
audio.currentTime = 0;
|
2017-10-19 00:13:51 +09:00
|
|
|
}
|
2017-03-14 01:12:30 +09:00
|
|
|
}
|
|
|
|
|
2023-05-10 19:59:29 +09:00
|
|
|
void audio.play();
|
2017-03-14 01:12:30 +09:00
|
|
|
};
|
|
|
|
|
2023-05-10 06:41:18 +09:00
|
|
|
export const soundsMiddleware = (): Middleware<
|
|
|
|
Record<string, never>,
|
|
|
|
RootState
|
|
|
|
> => {
|
2023-07-13 18:49:16 +09:00
|
|
|
const soundCache: Record<string, HTMLAudioElement> = {};
|
2023-07-12 10:02:32 +09:00
|
|
|
|
|
|
|
void ready(() => {
|
|
|
|
soundCache.boop = createAudio([
|
2017-05-10 23:58:54 +09:00
|
|
|
{
|
2023-07-12 10:02:32 +09:00
|
|
|
src: `${assetHost}/sounds/boop.ogg`,
|
2017-05-10 23:58:54 +09:00
|
|
|
type: 'audio/ogg',
|
|
|
|
},
|
|
|
|
{
|
2023-07-12 10:02:32 +09:00
|
|
|
src: `${assetHost}/sounds/boop.mp3`,
|
2017-05-21 00:31:47 +09:00
|
|
|
type: 'audio/mpeg',
|
2017-05-10 23:58:54 +09:00
|
|
|
},
|
2023-07-12 10:02:32 +09:00
|
|
|
]);
|
|
|
|
});
|
2017-03-14 01:12:30 +09:00
|
|
|
|
2023-05-10 19:59:29 +09:00
|
|
|
return () =>
|
|
|
|
(next) =>
|
|
|
|
(action: AnyAction & { meta?: { sound?: string } }) => {
|
2023-07-13 18:49:16 +09:00
|
|
|
const sound = action.meta?.sound;
|
2023-05-09 23:56:26 +09:00
|
|
|
|
2023-07-13 18:49:16 +09:00
|
|
|
if (sound && Object.hasOwn(soundCache, sound)) {
|
2023-05-10 19:59:29 +09:00
|
|
|
play(soundCache[sound]);
|
|
|
|
}
|
2017-03-14 01:12:30 +09:00
|
|
|
|
2023-05-10 19:59:29 +09:00
|
|
|
return next(action);
|
|
|
|
};
|
2023-05-09 23:56:26 +09:00
|
|
|
};
|