Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
a workaround to be able to play sounds anywhere (coded to be able to play sounds on iOS devices)
// empty sound
const TEST_AUDIO_MP3 = [
'data:audio/mpeg;base64',
',/+MYxAAAAANIAUAAAASEEB/jwOFM/0MM/90b/+RhST//w4NFwOjf',
'///PZu//',
'//9lns5GFDv//l9GlUIEEIAAAgIg8Ir/JGq3/',
'+MYxDsLIj5QMYcoAP0dv9HIjUcH//yYSg+CIbkGP//',
'8w0bLVjUP///3Z0x5QCAv/yLjwtGKTEFNRTMuOTeqqqqqqqqqqqqq/',
'+MYxEkNmdJkUYc4AKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq',
'qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq'
].join('');
const GLOBAL_AUDIO_PLAYER_NAME = '___REUSABLE_GLOBAL_AUDIO_PLAYER___';
const setupGlobalAudioPlay = (): HTMLAudioElement => {
const audio = new Audio();
audio.src = TEST_AUDIO_MP3;
const eventName = 'ontouchstart' in window.document.documentElement ? 'touchstart' : 'click';
const firstPlay = () => {
audio.play();
window.removeEventListener(eventName, firstPlay);
};
window.addEventListener(eventName, firstPlay);
(window as any)[GLOBAL_AUDIO_PLAYER_NAME] = audio;
return audio;
};
const getGlobalAudioPlayer = (): HTMLAudioElement => {
let globalAudioPlayer = (window as any)[GLOBAL_AUDIO_PLAYER_NAME] as HTMLAudioElement;
if (!globalAudioPlayer) {
globalAudioPlayer = setupGlobalAudioPlay();
}
return globalAudioPlayer;
};
export interface IAudioPlayer {
setSrc: (src: string) => void;
play: (src?: string) => void;
pause: () => void;
isPaused: () => boolean;
}
export const AudioPlayer: IAudioPlayer = ((): IAudioPlayer => {
const audio = getGlobalAudioPlayer();
const setSrc = (audioSrc: string) => {
if (audio.src === audioSrc) {
return;
}
audio.src = audioSrc;
audio.load();
};
const play = (audioSrc?: string) => {
if (audioSrc) {
setSrc(audioSrc);
}
audio.play();
};
const pause = () => audio.pause();
const isPaused = () => audio.paused;
return {
setSrc,
play,
pause,
isPaused
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.