Created
April 19, 2019 12:24
-
-
Save erkobridee/fe37dc3b19209e853e5aaf130413ea3c to your computer and use it in GitHub Desktop.
a workaround to be able to play sounds anywhere (coded to be able to play sounds on iOS devices)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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