2023-05-09 16:56:26 +02:00
|
|
|
import { Middleware, AnyAction } from 'redux';
|
|
|
|
import { RootState } from '..';
|
|
|
|
|
|
|
|
interface AudioSource {
|
|
|
|
src: string
|
|
|
|
type: string
|
|
|
|
}
|
|
|
|
|
|
|
|
const createAudio = (sources: AudioSource[]) => {
|
2017-05-10 16:58:54 +02: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-20 17:31:47 +02:00
|
|
|
};
|
2017-05-10 16:58:54 +02:00
|
|
|
|
2023-05-09 16:56:26 +02:00
|
|
|
const play = (audio: HTMLAudioElement) => {
|
2017-03-13 17:12:30 +01:00
|
|
|
if (!audio.paused) {
|
|
|
|
audio.pause();
|
2017-10-18 17:13:51 +02:00
|
|
|
if (typeof audio.fastSeek === 'function') {
|
|
|
|
audio.fastSeek(0);
|
|
|
|
} else {
|
2018-09-06 18:33:49 +02:00
|
|
|
audio.currentTime = 0;
|
2017-10-18 17:13:51 +02:00
|
|
|
}
|
2017-03-13 17:12:30 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
audio.play();
|
|
|
|
};
|
|
|
|
|
2023-05-09 16:56:26 +02:00
|
|
|
export const soundsMiddleware = (): Middleware<Record<string, never>, RootState> => {
|
|
|
|
const soundCache: {[key: string]: HTMLAudioElement} = {
|
2017-05-10 16:58:54 +02:00
|
|
|
boop: createAudio([
|
|
|
|
{
|
|
|
|
src: '/sounds/boop.ogg',
|
|
|
|
type: 'audio/ogg',
|
|
|
|
},
|
|
|
|
{
|
|
|
|
src: '/sounds/boop.mp3',
|
2017-05-20 17:31:47 +02:00
|
|
|
type: 'audio/mpeg',
|
2017-05-10 16:58:54 +02:00
|
|
|
},
|
|
|
|
]),
|
2017-03-13 17:12:30 +01:00
|
|
|
};
|
|
|
|
|
2023-05-09 16:56:26 +02:00
|
|
|
return () => next => (action: AnyAction) => {
|
|
|
|
const sound = action?.meta?.sound;
|
|
|
|
|
|
|
|
if (sound && soundCache[sound]) {
|
|
|
|
play(soundCache[sound]);
|
2017-03-13 17:12:30 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return next(action);
|
|
|
|
};
|
2023-05-09 16:56:26 +02:00
|
|
|
};
|