You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.1 KiB
57 lines
1.1 KiB
2 years ago
|
import { Middleware, AnyAction } from 'redux';
|
||
|
import { RootState } from '..';
|
||
|
|
||
|
interface AudioSource {
|
||
|
src: string
|
||
|
type: string
|
||
|
}
|
||
|
|
||
|
const createAudio = (sources: AudioSource[]) => {
|
||
8 years ago
|
const audio = new Audio();
|
||
|
sources.forEach(({ type, src }) => {
|
||
|
const source = document.createElement('source');
|
||
|
source.type = type;
|
||
|
source.src = src;
|
||
|
audio.appendChild(source);
|
||
|
});
|
||
|
return audio;
|
||
8 years ago
|
};
|
||
8 years ago
|
|
||
2 years ago
|
const play = (audio: HTMLAudioElement) => {
|
||
8 years ago
|
if (!audio.paused) {
|
||
|
audio.pause();
|
||
7 years ago
|
if (typeof audio.fastSeek === 'function') {
|
||
|
audio.fastSeek(0);
|
||
|
} else {
|
||
6 years ago
|
audio.currentTime = 0;
|
||
7 years ago
|
}
|
||
8 years ago
|
}
|
||
|
|
||
|
audio.play();
|
||
|
};
|
||
|
|
||
2 years ago
|
export const soundsMiddleware = (): Middleware<Record<string, never>, RootState> => {
|
||
|
const soundCache: {[key: string]: HTMLAudioElement} = {
|
||
8 years ago
|
boop: createAudio([
|
||
|
{
|
||
|
src: '/sounds/boop.ogg',
|
||
|
type: 'audio/ogg',
|
||
|
},
|
||
|
{
|
||
|
src: '/sounds/boop.mp3',
|
||
8 years ago
|
type: 'audio/mpeg',
|
||
8 years ago
|
},
|
||
|
]),
|
||
8 years ago
|
};
|
||
|
|
||
2 years ago
|
return () => next => (action: AnyAction) => {
|
||
|
const sound = action?.meta?.sound;
|
||
|
|
||
|
if (sound && soundCache[sound]) {
|
||
|
play(soundCache[sound]);
|
||
8 years ago
|
}
|
||
|
|
||
|
return next(action);
|
||
|
};
|
||
2 years ago
|
};
|