2023-05-10 06:59:29 -04:00
|
|
|
import type { Middleware, AnyAction } from 'redux';
|
|
|
|
|
2023-07-11 21:02:32 -04:00
|
|
|
import ready from 'mastodon/ready';
|
|
|
|
import { assetHost } from 'mastodon/utils/config';
|
|
|
|
|
2023-05-10 06:59:29 -04:00
|
|
|
import type { RootState } from '..';
|
2023-05-09 10:56:26 -04:00
|
|
|
|
|
|
|
interface AudioSource {
|
2023-05-09 13:02:12 -04:00
|
|
|
src: string;
|
|
|
|
type: string;
|
2023-05-09 10:56:26 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
const createAudio = (sources: AudioSource[]) => {
|
2017-05-10 10:58:54 -04: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 11:31:47 -04:00
|
|
|
};
|
2017-05-10 10:58:54 -04:00
|
|
|
|
2023-05-09 10:56:26 -04:00
|
|
|
const play = (audio: HTMLAudioElement) => {
|
2017-03-13 12:12:30 -04:00
|
|
|
if (!audio.paused) {
|
|
|
|
audio.pause();
|
2017-10-18 11:13:51 -04:00
|
|
|
if (typeof audio.fastSeek === 'function') {
|
|
|
|
audio.fastSeek(0);
|
|
|
|
} else {
|
2017-12-08 19:25:00 -05:00
|
|
|
audio.currentTime = 0;
|
2017-10-18 11:13:51 -04:00
|
|
|
}
|
2017-03-13 12:12:30 -04:00
|
|
|
}
|
|
|
|
|
2023-05-10 06:59:29 -04:00
|
|
|
void audio.play();
|
2017-03-13 12:12:30 -04:00
|
|
|
};
|
|
|
|
|
2023-05-09 13:02:12 -04:00
|
|
|
export const soundsMiddleware = (): Middleware<
|
|
|
|
Record<string, never>,
|
|
|
|
RootState
|
|
|
|
> => {
|
2023-07-11 21:02:32 -04:00
|
|
|
const soundCache: { [key: string]: HTMLAudioElement } = {};
|
|
|
|
|
|
|
|
void ready(() => {
|
|
|
|
soundCache.boop = createAudio([
|
2017-05-10 10:58:54 -04:00
|
|
|
{
|
2023-07-11 21:02:32 -04:00
|
|
|
src: `${assetHost}/sounds/boop.ogg`,
|
2017-05-10 10:58:54 -04:00
|
|
|
type: 'audio/ogg',
|
|
|
|
},
|
|
|
|
{
|
2023-07-11 21:02:32 -04:00
|
|
|
src: `${assetHost}/sounds/boop.mp3`,
|
2017-05-20 11:31:47 -04:00
|
|
|
type: 'audio/mpeg',
|
2017-05-10 10:58:54 -04:00
|
|
|
},
|
2023-07-11 21:02:32 -04:00
|
|
|
]);
|
|
|
|
});
|
2017-03-13 12:12:30 -04:00
|
|
|
|
2023-05-10 06:59:29 -04:00
|
|
|
return () =>
|
|
|
|
(next) =>
|
|
|
|
(action: AnyAction & { meta?: { sound?: string } }) => {
|
|
|
|
const sound = action?.meta?.sound;
|
2023-05-09 10:56:26 -04:00
|
|
|
|
2023-05-10 06:59:29 -04:00
|
|
|
if (sound && soundCache[sound]) {
|
|
|
|
play(soundCache[sound]);
|
|
|
|
}
|
2017-03-13 12:12:30 -04:00
|
|
|
|
2023-05-10 06:59:29 -04:00
|
|
|
return next(action);
|
|
|
|
};
|
2023-05-09 10:56:26 -04:00
|
|
|
};
|