Created
February 13, 2022 09:58
-
-
Save rickd-uk/338eec0120a14ac293ac518d5b6de9ad to your computer and use it in GitHub Desktop.
Ask User Permission To Allow Sound (JS)
This file contains 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
const audio = new Audio( 'https://dl.dropboxusercontent.com/s/h8pvqqol3ovyle8/tom.mp3' ); | |
audio.muted = true; | |
const alert_elem = document.querySelector( '.alert' ); | |
audio.play().then( () => { | |
// already allowed | |
alert_elem.remove(); | |
resetAudio(); | |
} ) | |
.catch( () => { | |
// need user interaction | |
alert_elem.addEventListener( 'click', ({ target }) => { | |
if( target.matches('button') ) { | |
const allowed = target.value === "1"; | |
if( allowed ) { | |
audio.play() | |
.then( resetAudio ); | |
} | |
alert_elem.remove(); | |
} | |
} ); | |
} ); | |
document.getElementById( 'btn' ).addEventListener( 'click', (e) => { | |
if( audio.muted ) { | |
console.log( 'silent notification' ); | |
} | |
else { | |
audio.play(); | |
} | |
} ); | |
function resetAudio() { | |
audio.pause(); | |
audio.currentTime = 0; | |
audio.muted = false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment