diff --git a/app/javascript/shared/helpers/AudioNotificationHelper.js b/app/javascript/shared/helpers/AudioNotificationHelper.js index 7db280fa2..a0d5e196e 100644 --- a/app/javascript/shared/helpers/AudioNotificationHelper.js +++ b/app/javascript/shared/helpers/AudioNotificationHelper.js @@ -5,29 +5,46 @@ import { showBadgeOnFavicon } from './faviconHelper'; export const initOnEvents = ['click', 'touchstart', 'keypress', 'keydown']; export const getAlertAudio = async (baseUrl = '', type = 'dashboard') => { - const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); + const audioCtx = getAudioContext(); + const playsound = audioBuffer => { window.playAudioAlert = () => { - const source = audioCtx.createBufferSource(); - source.buffer = audioBuffer; - source.connect(audioCtx.destination); - source.loop = false; - source.start(); + if (audioCtx) { + const source = audioCtx.createBufferSource(); + source.buffer = audioBuffer; + source.connect(audioCtx.destination); + source.loop = false; + source.start(); + } }; }; - const resourceUrl = `${baseUrl}/audio/${type}/ding.mp3`; - const audioRequest = new Request(resourceUrl); + if (audioCtx) { + const resourceUrl = `${baseUrl}/audio/${type}/ding.mp3`; + const audioRequest = new Request(resourceUrl); - fetch(audioRequest) - .then(response => response.arrayBuffer()) - .then(buffer => { - audioCtx.decodeAudioData(buffer).then(playsound); - return new Promise(res => res()); - }) - .catch(() => { - // error - }); + fetch(audioRequest) + .then(response => response.arrayBuffer()) + .then(buffer => { + audioCtx.decodeAudioData(buffer).then(playsound); + return new Promise(res => res()); + }) + .catch(() => { + // error + }); + } +}; + +export const getAudioContext = () => { + let audioCtx; + + try { + audioCtx = new (window.AudioContext || window.webkitAudioContext)(); + } catch { + // AudioContext is not available. + } + + return audioCtx; }; export const notificationEnabled = (enableAudioAlerts, id, userId) => {