This repository has been archived on 2023-03-18. You can view files and clone it, but cannot push or open issues or pull requests.
osr-discourse-src/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.js
Joffrey JAFFEUX c8beefc1ee
FIX: reimplements chat audio into a service (#18983)
This implementation attempts to be more resilient to background tab.

Notes:
- adds support for immediate arg in @debounce decorators
- fixes a bug in discourseDebounce which was not supporting immediate arg in tests
- chat-audio-manager has no tests as audio requires real user interaction and is hard to test reliably
2022-11-11 13:11:41 +01:00

69 lines
1.6 KiB
JavaScript

import Service from "@ember/service";
import { debounce } from "discourse-common/utils/decorators";
const AUDIO_DEBOUNCE_DELAY = 3000;
export const CHAT_SOUNDS = {
bell: [{ src: "/plugins/chat/audio/bell.mp3", type: "audio/mpeg" }],
ding: [{ src: "/plugins/chat/audio/ding.mp3", type: "audio/mpeg" }],
};
const DEFAULT_SOUND_NAME = "bell";
const createAudioCache = (sources) => {
const audio = new Audio();
sources.forEach(({ type, src }) => {
const source = document.createElement("source");
source.type = type;
source.src = src;
audio.appendChild(source);
});
return audio;
};
export default class ChatAudioManager extends Service {
_audioCache = {};
setup() {
Object.keys(CHAT_SOUNDS).forEach((soundName) => {
this._audioCache[soundName] = createAudioCache(CHAT_SOUNDS[soundName]);
});
}
willDestroy() {
this._super(...arguments);
this._audioCache = {};
}
playImmediately(soundName) {
return this._play(soundName);
}
@debounce(AUDIO_DEBOUNCE_DELAY, true)
play(soundName) {
return this._play(soundName);
}
_play(soundName) {
const audio =
this._audioCache[soundName] || this._audioCache[DEFAULT_SOUND_NAME];
if (!audio.paused) {
audio.pause();
if (typeof audio.fastSeek === "function") {
audio.fastSeek(0);
} else {
audio.currentTime = 0;
}
}
return audio.play().catch(() => {
// eslint-disable-next-line no-console
console.info(
"[chat] User needs to interact with DOM before we can play notification sounds."
);
});
}
}